Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d5041492a9 | |||
| ec5d93efab | |||
| b90533c535 | |||
| 03a9dfa0de | |||
| 1884853e4b | |||
| 882801c71d | |||
| dea8eed184 | |||
| 915a5d4742 | |||
| 4f9b910a94 | |||
| 3df5645f73 | |||
| 5f7498b755 | |||
| 733d4c8d36 |
@@ -504,45 +504,60 @@ object DataManager : IDataManager {
|
||||
* Also refreshes the summary from the updated kanban data.
|
||||
*/
|
||||
fun updateTask(task: TaskResponse) {
|
||||
// Update in allTasks
|
||||
_allTasks.value?.let { current ->
|
||||
val targetColumn = task.kanbanColumn ?: "upcoming_tasks"
|
||||
val newColumns = current.columns.map { column ->
|
||||
// Remove task from this column if present
|
||||
val filteredTasks = column.tasks.filter { it.id != task.id }
|
||||
// Add task if this is the target column
|
||||
val updatedTasks = if (column.name == targetColumn) {
|
||||
filteredTasks + task
|
||||
} else {
|
||||
filteredTasks
|
||||
}
|
||||
column.copy(tasks = updatedTasks, count = updatedTasks.size)
|
||||
}
|
||||
_allTasks.value = current.copy(columns = newColumns)
|
||||
}
|
||||
val targetColumn = task.kanbanColumn ?: "upcoming_tasks"
|
||||
|
||||
// Update in tasksByResidence if this task's residence is cached
|
||||
task.residenceId?.let { residenceId ->
|
||||
_tasksByResidence.value[residenceId]?.let { current ->
|
||||
val targetColumn = task.kanbanColumn ?: "upcoming_tasks"
|
||||
val newColumns = current.columns.map { column ->
|
||||
val filteredTasks = column.tasks.filter { it.id != task.id }
|
||||
val updatedTasks = if (column.name == targetColumn) {
|
||||
filteredTasks + task
|
||||
} else {
|
||||
filteredTasks
|
||||
}
|
||||
column.copy(tasks = updatedTasks, count = updatedTasks.size)
|
||||
}
|
||||
_tasksByResidence.value = _tasksByResidence.value + (residenceId to current.copy(columns = newColumns))
|
||||
}
|
||||
// Upsert into _allTasks. Crucially, when _allTasks is null (fresh
|
||||
// launch, kanban never fetched — the gitea#2 bug scenario), seed
|
||||
// an empty kanban shell so the new task isn't silently dropped.
|
||||
// The Phase 2 force-refresh after bulkCreateTasks/createTask will
|
||||
// replace this shell with authoritative server data shortly.
|
||||
val current = _allTasks.value ?: emptyKanbanShell()
|
||||
val columnsWithTarget = if (current.columns.any { it.name == targetColumn }) {
|
||||
current.columns
|
||||
} else {
|
||||
// Server returned a kanban_column the client doesn't know about
|
||||
// yet — append it so the task is still reachable.
|
||||
current.columns + emptyColumn(targetColumn)
|
||||
}
|
||||
val newColumns = columnsWithTarget.map { column ->
|
||||
val filteredTasks = column.tasks.filter { it.id != task.id }
|
||||
val updatedTasks = if (column.name == targetColumn) filteredTasks + task else filteredTasks
|
||||
column.copy(tasks = updatedTasks, count = updatedTasks.size)
|
||||
}
|
||||
_allTasks.value = current.copy(columns = newColumns)
|
||||
|
||||
// Refresh summary from updated kanban data (API no longer returns summaries for CRUD)
|
||||
refreshSummaryFromKanban()
|
||||
persistToDisk()
|
||||
}
|
||||
|
||||
/// Default kanban skeleton used when `_allTasks` was never populated.
|
||||
/// Display metadata is intentionally placeholder — the Phase 2 force-refresh
|
||||
/// in `APILayer.bulkCreateTasks` / `createTask` replaces these shortly with
|
||||
/// authoritative server values. The `name` field is the contract — every
|
||||
/// observer keys off it.
|
||||
private fun emptyKanbanShell(): TaskColumnsResponse = TaskColumnsResponse(
|
||||
columns = listOf(
|
||||
emptyColumn("overdue_tasks"),
|
||||
emptyColumn("due_soon_tasks"),
|
||||
emptyColumn("in_progress_tasks"),
|
||||
emptyColumn("upcoming_tasks"),
|
||||
emptyColumn("completed_tasks")
|
||||
),
|
||||
daysThreshold = 30,
|
||||
residenceId = ""
|
||||
)
|
||||
|
||||
private fun emptyColumn(name: String): TaskColumn = TaskColumn(
|
||||
name = name,
|
||||
displayName = "",
|
||||
buttonTypes = emptyList(),
|
||||
icons = emptyMap(),
|
||||
color = "",
|
||||
tasks = emptyList(),
|
||||
count = 0
|
||||
)
|
||||
|
||||
fun removeTask(taskId: Int) {
|
||||
// Remove from allTasks
|
||||
_allTasks.value?.let { current ->
|
||||
|
||||
@@ -615,36 +615,22 @@ object APILayer {
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns kanban data for a single residence. Single source of truth
|
||||
* is `_allTasks`; this function ensures it's fresh, then filters.
|
||||
*
|
||||
* Replaces the previous 3-path implementation (per-residence cache →
|
||||
* filter from allTasks → API) that produced inconsistent results
|
||||
* when the per-residence cache slot was empty but `_allTasks` was
|
||||
* stale. Phase 3 deletes the per-residence cache entirely.
|
||||
*/
|
||||
suspend fun getTasksByResidence(residenceId: Int, forceRefresh: Boolean = false): ApiResult<TaskColumnsResponse> {
|
||||
// 1. Check residence-specific cache first
|
||||
if (!forceRefresh && DataManager.isCacheValid(DataManager.tasksByResidenceCacheTime[residenceId] ?: 0L)) {
|
||||
val cached = DataManager.tasksByResidence.value[residenceId]
|
||||
if (cached != null) {
|
||||
return ApiResult.Success(cached)
|
||||
}
|
||||
}
|
||||
val allTasksResult = getTasks(forceRefresh = forceRefresh)
|
||||
if (allTasksResult is ApiResult.Error) return allTasksResult
|
||||
|
||||
// 2. Try filtering from allTasks cache before hitting API (optimization)
|
||||
// This avoids a redundant API call when we already have all tasks loaded
|
||||
if (!forceRefresh && DataManager.isCacheValid(DataManager.tasksCacheTime)) {
|
||||
val filtered = DataManager.getTasksForResidence(residenceId)
|
||||
if (filtered != null) {
|
||||
// Cache the filtered result for future use
|
||||
DataManager.setTasksForResidence(residenceId, filtered)
|
||||
return ApiResult.Success(filtered)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fallback: Fetch from API
|
||||
val token = getToken() ?: return ApiResult.Error("Not authenticated", 401)
|
||||
val result = taskApi.getTasksByResidence(token, residenceId)
|
||||
|
||||
// Update DataManager on success
|
||||
if (result is ApiResult.Success) {
|
||||
DataManager.setTasksForResidence(residenceId, result.data)
|
||||
}
|
||||
|
||||
return result
|
||||
val filtered = DataManager.getTasksForResidence(residenceId)
|
||||
?: return ApiResult.Error("Tasks unavailable", 0)
|
||||
return ApiResult.Success(filtered)
|
||||
}
|
||||
|
||||
suspend fun createTask(request: TaskCreateRequest): ApiResult<TaskResponse> {
|
||||
@@ -667,9 +653,15 @@ object APILayer {
|
||||
|
||||
/**
|
||||
* Atomically creates 1-50 tasks via POST /api/tasks/bulk/. The whole
|
||||
* batch succeeds or fails together on the server. On success, every
|
||||
* returned task is merged into DataManager.allTasks so observing views
|
||||
* render the new batch immediately.
|
||||
* batch succeeds or fails together on the server. On success, force-
|
||||
* refreshes _allTasks from the server — the server is the
|
||||
* authoritative kanban categorizer, and a single round-trip
|
||||
* eliminates any drift between the per-task `kanbanColumn` hint and
|
||||
* the global kanban view.
|
||||
*
|
||||
* This is the bug-class fix for gitea#2: the previous per-task
|
||||
* updateTask loop was a no-op when _allTasks was null (fresh launch
|
||||
* after onboarding), silently dropping the new tasks from cache.
|
||||
*/
|
||||
suspend fun bulkCreateTasks(request: BulkCreateTasksRequest): ApiResult<BulkCreateTasksResponse> {
|
||||
val token = getToken() ?: return ApiResult.Error("Not authenticated", 401)
|
||||
@@ -677,7 +669,9 @@ object APILayer {
|
||||
|
||||
if (result is ApiResult.Success) {
|
||||
DataManager.setTotalSummary(result.data.summary)
|
||||
result.data.tasks.forEach { DataManager.updateTask(it) }
|
||||
// Authoritative refresh — replaces any placeholder kanban
|
||||
// shell from updateTask with proper server data.
|
||||
getTasks(forceRefresh = true)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -70,15 +70,26 @@ class ResidenceViewModel(
|
||||
/** Drives the residence-scoped projections. */
|
||||
private val _selectedResidenceId = MutableStateFlow<Int?>(null)
|
||||
|
||||
/// Residence-scoped kanban derived from `DataManager.allTasks` filtered
|
||||
/// by `_selectedResidenceId`. Single source of truth — eliminates the
|
||||
/// gitea#2 race window where the per-residence cache slot could be
|
||||
/// empty while `_allTasks` was populated. The per-residence cache
|
||||
/// (`tasksByResidence`) was deleted in cec521b.
|
||||
val residenceTasksState: StateFlow<ApiResult<TaskColumnsResponse>> =
|
||||
combine(_selectedResidenceId, dataManager.tasksByResidence) { id, map ->
|
||||
if (id == null) ApiResult.Idle
|
||||
else map[id]?.let { ApiResult.Success(it) } ?: ApiResult.Idle
|
||||
combine(_selectedResidenceId, DataManager.allTasks) { id, all ->
|
||||
when {
|
||||
id == null -> ApiResult.Idle
|
||||
all == null -> ApiResult.Loading
|
||||
else -> {
|
||||
val filtered = DataManager.getTasksForResidence(id)
|
||||
if (filtered != null) ApiResult.Success(filtered) else ApiResult.Loading
|
||||
}
|
||||
}
|
||||
}.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.Eagerly,
|
||||
_selectedResidenceId.value?.let { id ->
|
||||
dataManager.tasksByResidence.value[id]?.let { ApiResult.Success(it) }
|
||||
DataManager.getTasksForResidence(id)?.let { ApiResult.Success(it) }
|
||||
} ?: ApiResult.Idle,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.tt.honeyDue.data
|
||||
|
||||
import com.tt.honeyDue.models.TaskResponse
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.test.BeforeTest
|
||||
|
||||
/**
|
||||
* Regression tests for the gitea#2 task-cache bug:
|
||||
* `DataManager.updateTask` was a no-op when both `_allTasks` was null AND
|
||||
* `_tasksByResidence[residenceId]` was empty — exactly the cache state
|
||||
* after a fresh register-then-bulkCreateTasks flow. The just-created
|
||||
* tasks would only appear after an app restart.
|
||||
*
|
||||
* After the fix, `updateTask` must seed `_allTasks` from empty rather
|
||||
* than skipping the update.
|
||||
*/
|
||||
class DataManagerTaskCacheTest {
|
||||
|
||||
@BeforeTest
|
||||
fun resetState() {
|
||||
DataManager.clear()
|
||||
}
|
||||
|
||||
/// Onboarding-flow scenario: brand-new user, fresh launch, no kanban
|
||||
/// has ever been fetched, then a task arrives via bulkCreateTasks →
|
||||
/// DataManager.updateTask. The new task MUST land in `_allTasks` and
|
||||
/// be visible to any observer.
|
||||
@Test
|
||||
fun updateTask_seedsAllTasks_whenCacheIsEmpty() {
|
||||
// Given: fresh DataManager, kanban never loaded
|
||||
assertEquals(null, DataManager.allTasks.value, "_allTasks must start null after clear()")
|
||||
|
||||
// When: a new task arrives via the same path bulkCreateTasks uses
|
||||
DataManager.updateTask(sampleTask(id = 1, residenceId = 100, column = "upcoming_tasks"))
|
||||
|
||||
// Then: _allTasks must contain that task in the right column
|
||||
val allTasks = DataManager.allTasks.value
|
||||
assertNotNull(allTasks, "updateTask must seed _allTasks even when it was null")
|
||||
|
||||
val upcoming = allTasks.columns.firstOrNull { it.name == "upcoming_tasks" }
|
||||
assertNotNull(upcoming, "the seeded kanban must include an upcoming_tasks column")
|
||||
assertTrue(
|
||||
upcoming.tasks.any { it.id == 1 },
|
||||
"the new task must land in upcoming_tasks; got columns=${allTasks.columns.map { it.name to it.tasks.map { t -> t.id } }}"
|
||||
)
|
||||
assertEquals(upcoming.tasks.size, upcoming.count, "column count must match tasks.size")
|
||||
}
|
||||
|
||||
/// Reasonable-defaults sanity check for the bulk-create scenario:
|
||||
/// multiple tasks land across different kanban columns and end up
|
||||
/// distributed correctly. This exercises the upsert when _allTasks
|
||||
/// was seeded by a previous call.
|
||||
@Test
|
||||
fun updateTask_distributesAcrossColumns_whenSeedingThenAdding() {
|
||||
DataManager.updateTask(sampleTask(id = 1, residenceId = 100, column = "overdue_tasks"))
|
||||
DataManager.updateTask(sampleTask(id = 2, residenceId = 100, column = "upcoming_tasks"))
|
||||
DataManager.updateTask(sampleTask(id = 3, residenceId = 100, column = "upcoming_tasks"))
|
||||
|
||||
val allTasks = DataManager.allTasks.value
|
||||
assertNotNull(allTasks)
|
||||
|
||||
val overdue = allTasks.columns.first { it.name == "overdue_tasks" }
|
||||
val upcoming = allTasks.columns.first { it.name == "upcoming_tasks" }
|
||||
|
||||
assertEquals(setOf(1), overdue.tasks.map { it.id }.toSet())
|
||||
assertEquals(setOf(2, 3), upcoming.tasks.map { it.id }.toSet())
|
||||
}
|
||||
|
||||
/// Replacement contract: calling updateTask with the same id twice
|
||||
/// must not duplicate; the second call replaces the first wherever it
|
||||
/// lives. Catches the "always-append" implementation mistake.
|
||||
@Test
|
||||
fun updateTask_replacesExistingTaskById_acrossColumns() {
|
||||
DataManager.updateTask(sampleTask(id = 5, residenceId = 100, column = "upcoming_tasks", title = "v1"))
|
||||
DataManager.updateTask(sampleTask(id = 5, residenceId = 100, column = "in_progress_tasks", title = "v2"))
|
||||
|
||||
val allTasks = DataManager.allTasks.value
|
||||
assertNotNull(allTasks)
|
||||
|
||||
val upcoming = allTasks.columns.first { it.name == "upcoming_tasks" }
|
||||
val inProgress = allTasks.columns.first { it.name == "in_progress_tasks" }
|
||||
|
||||
assertTrue(upcoming.tasks.none { it.id == 5 }, "task 5 must move out of upcoming_tasks")
|
||||
assertEquals(1, inProgress.tasks.count { it.id == 5 }, "task 5 must appear once in in_progress_tasks")
|
||||
assertEquals("v2", inProgress.tasks.first { it.id == 5 }.title)
|
||||
}
|
||||
|
||||
/// Characterization: getTasksForResidence filters _allTasks by
|
||||
/// residence id. This is the helper that becomes the primary path
|
||||
/// for residence-detail in Phase 3 (collapse the dual cache).
|
||||
@Test
|
||||
fun getTasksForResidence_filtersAllTasksByResidenceId() {
|
||||
// Seed _allTasks with tasks across two residences via the upsert path.
|
||||
DataManager.updateTask(sampleTask(id = 1, residenceId = 100, column = "upcoming_tasks"))
|
||||
DataManager.updateTask(sampleTask(id = 2, residenceId = 100, column = "overdue_tasks"))
|
||||
DataManager.updateTask(sampleTask(id = 3, residenceId = 200, column = "upcoming_tasks"))
|
||||
|
||||
val r100 = DataManager.getTasksForResidence(100)
|
||||
assertNotNull(r100)
|
||||
val r100Ids = r100.columns.flatMap { it.tasks }.map { it.id }.toSet()
|
||||
assertEquals(setOf(1, 2), r100Ids)
|
||||
|
||||
val r200 = DataManager.getTasksForResidence(200)
|
||||
assertNotNull(r200)
|
||||
val r200Ids = r200.columns.flatMap { it.tasks }.map { it.id }.toSet()
|
||||
assertEquals(setOf(3), r200Ids)
|
||||
|
||||
// Counts on each column must match the filtered task lists.
|
||||
for (column in r100.columns) {
|
||||
assertEquals(column.tasks.size, column.count, "column ${column.name} count mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
/// Characterization: residenceId with no tasks returns a non-null
|
||||
/// shell so the residence-detail screen can distinguish "loading"
|
||||
/// (null) from "loaded, no tasks" (non-null with empty columns).
|
||||
@Test
|
||||
fun getTasksForResidence_returnsEmptyShellForResidenceWithNoTasks() {
|
||||
DataManager.updateTask(sampleTask(id = 1, residenceId = 100, column = "upcoming_tasks"))
|
||||
|
||||
val r999 = DataManager.getTasksForResidence(999)
|
||||
assertNotNull(r999, "residence with no tasks must return an empty shell, not null")
|
||||
assertEquals(0, r999.columns.sumOf { it.tasks.size })
|
||||
}
|
||||
|
||||
/// Characterization: when _allTasks is null entirely (cache never
|
||||
/// populated), getTasksForResidence returns null — caller must call
|
||||
/// the API path. Phase 3's getTasksByResidence relies on this.
|
||||
@Test
|
||||
fun getTasksForResidence_returnsNullWhenAllTasksIsNull() {
|
||||
DataManager.clear()
|
||||
assertEquals(null, DataManager.getTasksForResidence(100))
|
||||
}
|
||||
|
||||
/// Lockdown: updateTask must NOT touch `_tasksByResidence`. That cache
|
||||
/// is being deleted in Phase 3; until then, updateTask must leave it
|
||||
/// alone. If a future commit re-introduces the conditional write
|
||||
/// branch this test catches it.
|
||||
@Test
|
||||
fun updateTask_doesNotMutate_tasksByResidence() {
|
||||
val before = DataManager.tasksByResidence.value
|
||||
DataManager.updateTask(sampleTask(id = 1, residenceId = 100, column = "upcoming_tasks"))
|
||||
assertEquals(
|
||||
before,
|
||||
DataManager.tasksByResidence.value,
|
||||
"updateTask must not write to _tasksByResidence — that cache is deprecated"
|
||||
)
|
||||
}
|
||||
|
||||
private fun sampleTask(
|
||||
id: Int,
|
||||
residenceId: Int,
|
||||
column: String,
|
||||
title: String = "Task $id"
|
||||
) = TaskResponse(
|
||||
id = id,
|
||||
residenceId = residenceId,
|
||||
createdById = 1,
|
||||
title = title,
|
||||
kanbanColumn = column,
|
||||
createdAt = "2026-04-25T00:00:00Z",
|
||||
updatedAt = "2026-04-25T00:00:00Z"
|
||||
)
|
||||
}
|
||||
+10
-2
@@ -1,9 +1,17 @@
|
||||
#Kotlin
|
||||
kotlin.code.style=official
|
||||
kotlin.daemon.jvmargs=-Xmx3072M
|
||||
# Heap sizing for KMP builds.
|
||||
# Kotlin daemon runs the K2 compiler + native linker; 4 GB headroom
|
||||
# prevents long-tail OOMs during iosArm64 framework link.
|
||||
# MaxMetaspaceSize caps slow class-loading leaks across daemon reuse;
|
||||
# G1GC keeps pauses short during incremental builds.
|
||||
kotlin.daemon.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=1g -XX:+UseG1GC
|
||||
|
||||
#Gradle
|
||||
org.gradle.jvmargs=-Xmx4096M -Dfile.encoding=UTF-8
|
||||
# Gradle daemon drives configuration cache + dependency resolution +
|
||||
# Compose/Android compilers. OOMs at 4 GB during ComposeApp.framework
|
||||
# generation; 6 GB is the usual safe size for projects this size.
|
||||
org.gradle.jvmargs=-Xmx6144M -XX:MaxMetaspaceSize=1g -XX:+UseG1GC -Dfile.encoding=UTF-8
|
||||
org.gradle.configuration-cache=true
|
||||
org.gradle.caching=true
|
||||
|
||||
|
||||
@@ -34,6 +34,23 @@ class AuthenticatedUITestCase: BaseUITestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/// When `true`, every test in the suite forces a logout → login cycle
|
||||
/// in `setUp`, guaranteeing a freshly-issued auth token on each run.
|
||||
///
|
||||
/// Default is `false`: tests reuse the existing logged-in session
|
||||
/// from the previous test in the same suite — much faster (one login
|
||||
/// per suite, not one per test) and resilient to suites where the
|
||||
/// current screen has no logout affordance (`UITestHelpers.ensureLoggedOut`
|
||||
/// times out → the test fails before its body runs).
|
||||
///
|
||||
/// Override to `true` in suites that have observed transient
|
||||
/// `Invalid token` 401s on POST/PATCH while reads continue to work.
|
||||
/// The recipe was added after a 2026-05 incident where the API
|
||||
/// container was rebuilt mid-suite and in-memory tokens went stale.
|
||||
/// In normal CI runs against a stable API + freshly-erased simulator,
|
||||
/// session reuse is the correct default.
|
||||
var forceFreshLoginPerTest: Bool { false }
|
||||
|
||||
override func setUpWithError() throws {
|
||||
guard TestAccountAPIClient.isBackendReachable() else {
|
||||
throw XCTSkip("Backend not reachable at \(TestAccountAPIClient.baseURL)")
|
||||
@@ -41,27 +58,27 @@ class AuthenticatedUITestCase: BaseUITestCase {
|
||||
|
||||
try super.setUpWithError()
|
||||
|
||||
// If already logged in (tab bar visible), skip the login flow
|
||||
let tabBar = app.tabBars.firstMatch
|
||||
if tabBar.waitForExistence(timeout: defaultTimeout) {
|
||||
// Already logged in — just set up API session if needed
|
||||
if needsAPISession {
|
||||
guard let apiSession = TestAccountManager.loginSeededAccount(
|
||||
username: apiCredentials.username,
|
||||
password: apiCredentials.password
|
||||
) else {
|
||||
XCTFail("Could not login API account '\(apiCredentials.username)'")
|
||||
return
|
||||
}
|
||||
session = apiSession
|
||||
cleaner = TestDataCleaner(token: apiSession.token)
|
||||
}
|
||||
return
|
||||
}
|
||||
let alreadyLoggedIn = tabBar.waitForExistence(timeout: defaultTimeout)
|
||||
|
||||
// Not logged in — do the full login flow
|
||||
UITestHelpers.ensureLoggedOut(app: app)
|
||||
loginToMainApp()
|
||||
// Force-fresh path: log out (if needed) and re-authenticate per
|
||||
// test so every test starts with a freshly-issued JWT. Catches
|
||||
// server-side token invalidation that would otherwise surface
|
||||
// mid-suite as opaque 401s on the first mutation call.
|
||||
if forceFreshLoginPerTest {
|
||||
if alreadyLoggedIn {
|
||||
UITestHelpers.ensureLoggedOut(app: app)
|
||||
} else {
|
||||
UITestHelpers.ensureLoggedOut(app: app)
|
||||
}
|
||||
loginToMainApp()
|
||||
} else if !alreadyLoggedIn {
|
||||
// Legacy session-reuse path: only log in when not already in.
|
||||
UITestHelpers.ensureLoggedOut(app: app)
|
||||
loginToMainApp()
|
||||
}
|
||||
// (When `forceFreshLoginPerTest == false` AND we're already
|
||||
// logged in, fall through with the existing session.)
|
||||
|
||||
if needsAPISession {
|
||||
guard let apiSession = TestAccountManager.loginSeededAccount(
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import XCTest
|
||||
|
||||
/// Suite 11 — captures the gitea#2 regression at the user-visible level:
|
||||
/// after onboarding (register → name residence → bulk-create tasks → land
|
||||
/// on home), tapping the residence cell shows "no tasks" even though the
|
||||
/// server has them. Restarting the app fixes it. This test reproduces the
|
||||
/// flow without an app restart and asserts that tasks render on the
|
||||
/// residence detail screen.
|
||||
///
|
||||
/// CRITICAL: this test must FAIL at the cache-unification fix's first
|
||||
/// commit and must PASS after Phase 1-3 lands. The failing assertion is
|
||||
/// pinned to a specific message so the regression is unambiguous.
|
||||
///
|
||||
/// The test deliberately does NOT visit the Tasks tab between onboarding
|
||||
/// and tapping the residence cell. Visiting the Tasks tab would prime
|
||||
/// `_allTasks` and mask the bug — the bug is that residence detail
|
||||
/// cannot recover from the empty-cache + sink-timing window on its own.
|
||||
final class Suite11_TaskCacheRegressionTests: BaseUITestCase {
|
||||
// We need to start at the onboarding welcome screen, not the standalone
|
||||
// login screen — `completeOnboarding` would skip the entire flow.
|
||||
override var completeOnboarding: Bool { false }
|
||||
// Single test in this suite — relaunch isn't necessary, but we want a
|
||||
// clean state every time (handled by the default --reset-state).
|
||||
override var relaunchBetweenTests: Bool { true }
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// DEBUG_FIXED_CODES=true on the local Go API hardcodes this code.
|
||||
private let debugVerificationCode = "123456"
|
||||
|
||||
/// Stable name for the residence we create in onboarding. Used both for
|
||||
/// the form input and to address the cell on the home screen via
|
||||
/// `app.staticTexts[residenceName]` if the id-based identifier doesn't
|
||||
/// resolve in time.
|
||||
private let residenceName = "UI Test Property"
|
||||
|
||||
// MARK: - Test
|
||||
|
||||
/// Reproduces gitea#2: tasks created via the onboarding bulk endpoint
|
||||
/// must appear on the residence detail screen without an app restart
|
||||
/// and without first visiting the Tasks tab.
|
||||
@MainActor
|
||||
func test_tasksAppearOnResidenceDetail_afterOnboarding_withoutRestart() throws {
|
||||
// Step 1 — Register a fresh user via the onboarding Start Fresh flow.
|
||||
// The flow is: Welcome → ValueProps → NameResidence → CreateAccount
|
||||
// → VerifyEmail → HomeProfile → FirstTask → main app.
|
||||
let createAccount = TestFlows.navigateStartFreshToCreateAccount(
|
||||
app: app,
|
||||
residenceName: residenceName
|
||||
)
|
||||
createAccount.waitForLoad(timeout: navigationTimeout)
|
||||
|
||||
// Step 2 — Fill the create-account form. We address the onboarding
|
||||
// form's fields (not the standalone register sheet's fields).
|
||||
let creds = TestAccountManager.uniqueCredentials(prefix: "gitea2")
|
||||
|
||||
createAccount.expandEmailSignup()
|
||||
|
||||
// Use the same focusAndType path that OnboardingTests uses — it
|
||||
// already handles SecureTextField + iOS strong-password panel.
|
||||
// Under --ui-testing, OrganicOnboardingSecureField defaults to
|
||||
// visibility=ON (renders as TextField) to dodge the iOS 26 SecureField
|
||||
// keyboard bug. Query textFields, not secureTextFields.
|
||||
let usernameField = app.textFields[AccessibilityIdentifiers.Onboarding.usernameField]
|
||||
let emailField = app.textFields[AccessibilityIdentifiers.Onboarding.emailField]
|
||||
let passwordField = app.textFields[AccessibilityIdentifiers.Onboarding.passwordField]
|
||||
let confirmPasswordField = app.textFields[AccessibilityIdentifiers.Onboarding.confirmPasswordField]
|
||||
|
||||
usernameField.waitForExistenceOrFail(timeout: navigationTimeout)
|
||||
usernameField.focusAndType(creds.username, app: app)
|
||||
emailField.waitForExistenceOrFail(timeout: navigationTimeout)
|
||||
emailField.focusAndType(creds.email, app: app)
|
||||
passwordField.waitForExistenceOrFail(timeout: navigationTimeout)
|
||||
passwordField.focusAndType(creds.password, app: app)
|
||||
confirmPasswordField.waitForExistenceOrFail(timeout: navigationTimeout)
|
||||
confirmPasswordField.focusAndType(creds.password, app: app)
|
||||
|
||||
let createAccountButton = app.descendants(matching: .any)
|
||||
.matching(identifier: AccessibilityIdentifiers.Onboarding.createAccountButton)
|
||||
.firstMatch
|
||||
createAccountButton.waitForExistenceOrFail(timeout: navigationTimeout)
|
||||
createAccountButton.forceTap()
|
||||
|
||||
// Step 3 — Verify email with the debug fixed code.
|
||||
let verification = VerificationScreen(app: app)
|
||||
verification.waitForLoad(timeout: loginTimeout)
|
||||
verification.enterCode(debugVerificationCode)
|
||||
// Many onboarding verification screens auto-submit on a 6-digit
|
||||
// code. If a verify button still exists and a code field is still
|
||||
// visible, tap it to push past edge cases.
|
||||
if verification.codeField.waitForExistence(timeout: 1) && verification.verifyButton.exists {
|
||||
verification.submitCode()
|
||||
}
|
||||
|
||||
// Step 4 — Skip the home-profile step. The home-profile screen has
|
||||
// its own Skip button (the shared onboarding skip in the nav bar)
|
||||
// which routes to the first-task step without making us pick climate
|
||||
// / appliance fields.
|
||||
let onboardingSkipButton = app.buttons[AccessibilityIdentifiers.Onboarding.skipButton]
|
||||
XCTAssertTrue(
|
||||
onboardingSkipButton.waitForExistence(timeout: loginTimeout),
|
||||
"Onboarding skip button should exist on the home-profile screen"
|
||||
)
|
||||
// The skip button can briefly be non-hittable during the screen-in
|
||||
// transition. Use forceTap() to bypass the strict hittable check.
|
||||
// We confirmed existence above; if the tap doesn't land on the
|
||||
// intended button the next assertion (Browse All tab) will catch it.
|
||||
onboardingSkipButton.forceTap()
|
||||
|
||||
// Step 5 — Switch to the "Browse All" tab on the First-Task screen.
|
||||
// "For You" suggestions can be empty for a fresh residence with no
|
||||
// home-profile data, so deterministic browsing is required.
|
||||
// The tab bar is a SwiftUI segmented Picker — its segments are
|
||||
// exposed as buttons with the segment label, regardless of an
|
||||
// identifier on the parent.
|
||||
let browseAllTab = app.buttons["Browse All"]
|
||||
XCTAssertTrue(
|
||||
browseAllTab.waitForExistence(timeout: loginTimeout),
|
||||
"Browse All tab should appear on the first-task screen"
|
||||
)
|
||||
browseAllTab.tap()
|
||||
|
||||
// Step 6 — Pick 3 templates by accessibility identifier prefix.
|
||||
// The catalog is loaded via GET /api/tasks/templates/grouped/, so
|
||||
// we need to wait for at least one row to render before tapping.
|
||||
let templateRowQuery = app.buttons.matching(
|
||||
NSPredicate(format: "identifier BEGINSWITH %@",
|
||||
AccessibilityIdentifiers.Onboarding.templateRowPrefix)
|
||||
)
|
||||
|
||||
// Wait for the catalog to load. The grouped endpoint returns first
|
||||
// category expanded by default in the view, so rows should appear
|
||||
// shortly after Browse All becomes visible. Network call: 10s.
|
||||
let firstRow = templateRowQuery.element(boundBy: 0)
|
||||
XCTAssertTrue(
|
||||
firstRow.waitForExistence(timeout: loginTimeout),
|
||||
"At least one template row must render on the Browse All tab. " +
|
||||
"If no rows appear, the catalog endpoint failed — bug repro is invalid."
|
||||
)
|
||||
|
||||
// Tap the first 3 visible rows. Some categories may collapse rows
|
||||
// we never see; we only need at least 1, so the floor is 1 with a
|
||||
// soft cap of 3.
|
||||
let rowCount = templateRowQuery.count
|
||||
let toPick = min(3, rowCount)
|
||||
XCTAssertGreaterThanOrEqual(toPick, 1, "Expected at least one template row")
|
||||
for index in 0..<toPick {
|
||||
let row = templateRowQuery.element(boundBy: index)
|
||||
row.waitUntilHittable(timeout: navigationTimeout)
|
||||
row.tap()
|
||||
}
|
||||
|
||||
// Step 7 — Submit the bulk-create. This is the
|
||||
// POST /api/tasks/bulk/ call that produces the inconsistent client
|
||||
// cache state at the heart of gitea#2.
|
||||
let submitButton = app.buttons[AccessibilityIdentifiers.Onboarding.submitTasksButton]
|
||||
XCTAssertTrue(
|
||||
submitButton.waitForExistence(timeout: navigationTimeout),
|
||||
"Submit-tasks button must exist on the first-task screen"
|
||||
)
|
||||
submitButton.waitUntilHittable(timeout: navigationTimeout).tap()
|
||||
|
||||
// Step 8 — Land on the main app (Residences tab is selected by
|
||||
// default). CRITICAL: do NOT tap the Tasks tab. Tapping it would
|
||||
// populate `_allTasks` and mask the bug.
|
||||
let mainTabs = app.otherElements[UITestID.Root.mainTabs]
|
||||
let tabBar = app.tabBars.firstMatch
|
||||
let reachedMain = mainTabs.waitForExistence(timeout: loginTimeout)
|
||||
|| tabBar.waitForExistence(timeout: navigationTimeout)
|
||||
XCTAssertTrue(reachedMain, "App should reach main tabs after onboarding submit")
|
||||
|
||||
// Step 9 — Tap the residence cell directly. Prefer the
|
||||
// identifier-prefix match for any cell; fall back to the static
|
||||
// text match by name.
|
||||
let residenceCellQuery = app.buttons.matching(
|
||||
NSPredicate(format: "identifier BEGINSWITH %@",
|
||||
AccessibilityIdentifiers.Residence.cellPrefix)
|
||||
)
|
||||
let residenceCell = residenceCellQuery.firstMatch
|
||||
if residenceCell.waitForExistence(timeout: navigationTimeout) && residenceCell.isHittable {
|
||||
residenceCell.tap()
|
||||
} else {
|
||||
// Fallback: tap the static text inside the card. The
|
||||
// NavigationLink wraps the entire card so a tap on the name
|
||||
// still routes into the detail view.
|
||||
let residenceText = app.staticTexts[residenceName]
|
||||
XCTAssertTrue(
|
||||
residenceText.waitForExistence(timeout: navigationTimeout),
|
||||
"Residence cell or name '\(residenceName)' must exist on the residences list"
|
||||
)
|
||||
residenceText.tap()
|
||||
}
|
||||
|
||||
// Step 10 — THE BUG ASSERTION. With the bug present:
|
||||
// - `_allTasks` is null on the client (never primed).
|
||||
// - `_tasksByResidence[id]` is empty (cache miss).
|
||||
// - residence detail attempts to load, hits the iOS Combine sink
|
||||
// timing window, and renders the empty state.
|
||||
// With the fix, both `_allTasks` is populated by `bulkCreateTasks`
|
||||
// and residence detail filters from it in-memory, so the empty
|
||||
// state must not appear.
|
||||
let taskRowQuery = app.descendants(matching: .any).matching(
|
||||
NSPredicate(format: "identifier BEGINSWITH %@",
|
||||
AccessibilityIdentifiers.Task.rowPrefix)
|
||||
)
|
||||
let firstTaskRow = taskRowQuery.element(boundBy: 0)
|
||||
let anyTaskAppeared = firstTaskRow.waitForExistence(timeout: 10)
|
||||
|
||||
let emptyState = app.otherElements[AccessibilityIdentifiers.Task.noTasksLabel]
|
||||
let emptyStateVisible = emptyState.exists
|
||||
|
||||
// Pin the failure message so the bug-capture is unambiguous. This
|
||||
// is the assertion that should FAIL at this commit and PASS after
|
||||
// the cache fix lands. Don't change the message — Task 12 grep's
|
||||
// for it.
|
||||
XCTAssertTrue(
|
||||
anyTaskAppeared && !emptyStateVisible,
|
||||
"Tasks created during onboarding must appear on residence detail without restart (gitea#2)"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -366,7 +366,12 @@ struct OnboardingCreateAccountContent: View {
|
||||
}
|
||||
.onChange(of: viewModel.isRegistered) { _, isRegistered in
|
||||
if isRegistered {
|
||||
// Registration successful - user is authenticated but not verified
|
||||
// Registration successful — server gave us a token, so we ARE
|
||||
// authenticated (just not verified yet). Mark the iOS-side auth
|
||||
// state to match, otherwise OnboardingState.completeOnboarding's
|
||||
// auth guard silently no-ops at the end of the flow and the
|
||||
// user gets stuck on the firstTask screen.
|
||||
AuthenticationManager.shared.login(verified: false)
|
||||
onAccountCreated(false)
|
||||
}
|
||||
}
|
||||
@@ -451,7 +456,13 @@ private struct OrganicOnboardingSecureField: View {
|
||||
@Binding var text: String
|
||||
var isFocused: Bool = false
|
||||
var accessibilityIdentifier: String? = nil
|
||||
@State private var showPassword = false
|
||||
// iOS 26 has a known bug where tapping a SwiftUI SecureField with
|
||||
// `.textContentType(.password)` doesn't reliably bring up the keyboard
|
||||
// — the strong-password autofill panel steals focus. Under UI tests
|
||||
// we force the visibility toggle ON, rendering as a plain TextField,
|
||||
// which has reliable focus behavior. The plaintext isn't a security
|
||||
// concern in test mode (test creds are throwaway).
|
||||
@State private var showPassword = UITestRuntime.isEnabled
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 14) {
|
||||
|
||||
@@ -42,6 +42,12 @@ class TaskViewModel: ObservableObject {
|
||||
private let dataManager: DataManagerObservable
|
||||
|
||||
// MARK: - Initialization
|
||||
/// Single source of truth = DataManager._allTasks. When this VM is
|
||||
/// residence-scoped (currentResidenceId set), filter in-memory by
|
||||
/// residence id. Eliminates the gitea#2 race window where the
|
||||
/// per-residence cache slot could be empty while _allTasks was
|
||||
/// populated. The per-residence cache is gone (cec521b).
|
||||
///
|
||||
/// - Parameter dataManager: Observable cache the VM subscribes to.
|
||||
/// Defaults to the shared singleton. Tests inject a fixture-backed
|
||||
/// instance so populated-state snapshots render real data.
|
||||
@@ -50,35 +56,26 @@ class TaskViewModel: ObservableObject {
|
||||
|
||||
// Seed from current cache so snapshot tests/previews render
|
||||
// populated state without waiting for Combine's async dispatch.
|
||||
// The seed path mirrors the steady-state filter below — if this
|
||||
// VM is residence-scoped at construction time the seed has to
|
||||
// pre-filter too, but currentResidenceId is set after init via
|
||||
// setResidenceFilter(...), so seeding the unfiltered list is fine.
|
||||
self.tasksResponse = dataManager.allTasks
|
||||
|
||||
// Observe injected DataManagerObservable for all tasks data
|
||||
// Observe injected DataManagerObservable for all tasks data.
|
||||
dataManager.$allTasks
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] allTasks in
|
||||
// Skip DataManager updates during completion animation to prevent
|
||||
// the task from being moved out of its column before the animation finishes
|
||||
guard self?.isAnimatingCompletion != true else { return }
|
||||
// Only update if we're showing all tasks (no residence filter)
|
||||
if self?.currentResidenceId == nil {
|
||||
self?.tasksResponse = allTasks
|
||||
if allTasks != nil {
|
||||
self?.isLoadingTasks = false
|
||||
}
|
||||
}
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
guard let self else { return }
|
||||
guard !self.isAnimatingCompletion else { return }
|
||||
|
||||
// Observe tasks by residence
|
||||
dataManager.$tasksByResidence
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] tasksByResidence in
|
||||
guard self?.isAnimatingCompletion != true else { return }
|
||||
// Only update if we're filtering by residence
|
||||
if let resId = self?.currentResidenceId,
|
||||
let tasks = tasksByResidence[resId] {
|
||||
self?.tasksResponse = tasks
|
||||
self?.isLoadingTasks = false
|
||||
if let allTasks {
|
||||
if let resId = self.currentResidenceId {
|
||||
self.tasksResponse = self.filterTasks(allTasks, residenceId: resId)
|
||||
} else {
|
||||
self.tasksResponse = allTasks
|
||||
}
|
||||
self.isLoadingTasks = false
|
||||
}
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
@@ -392,6 +389,28 @@ class TaskViewModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Filter the all-tasks kanban down to a single residence in-memory.
|
||||
/// Mirrors `DataManager.getTasksForResidence` on the Kotlin side.
|
||||
private func filterTasks(_ response: TaskColumnsResponse, residenceId: Int32) -> TaskColumnsResponse {
|
||||
let filteredColumns = response.columns.map { column -> TaskColumn in
|
||||
let filteredTasks = column.tasks.filter { Int32($0.residenceId) == residenceId }
|
||||
return TaskColumn(
|
||||
name: column.name,
|
||||
displayName: column.displayName,
|
||||
buttonTypes: column.buttonTypes,
|
||||
icons: column.icons,
|
||||
color: column.color,
|
||||
tasks: filteredTasks,
|
||||
count: Int32(filteredTasks.count)
|
||||
)
|
||||
}
|
||||
return TaskColumnsResponse(
|
||||
columns: filteredColumns,
|
||||
daysThreshold: response.daysThreshold,
|
||||
residenceId: String(residenceId)
|
||||
)
|
||||
}
|
||||
|
||||
/// Updates a task in the kanban board by moving it to the correct column based on kanban_column
|
||||
func updateTaskInKanban(_ updatedTask: TaskResponse) {
|
||||
guard let currentResponse = tasksResponse else { return }
|
||||
|
||||
Reference in New Issue
Block a user