Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 23f4d70ac1 | |||
| fdcf82757d | |||
| 3890dd6f52 | |||
| 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.
|
* Also refreshes the summary from the updated kanban data.
|
||||||
*/
|
*/
|
||||||
fun updateTask(task: TaskResponse) {
|
fun updateTask(task: TaskResponse) {
|
||||||
// Update in allTasks
|
|
||||||
_allTasks.value?.let { current ->
|
|
||||||
val targetColumn = task.kanbanColumn ?: "upcoming_tasks"
|
val targetColumn = task.kanbanColumn ?: "upcoming_tasks"
|
||||||
val newColumns = current.columns.map { column ->
|
|
||||||
// Remove task from this column if present
|
// Upsert into _allTasks. Crucially, when _allTasks is null (fresh
|
||||||
val filteredTasks = column.tasks.filter { it.id != task.id }
|
// launch, kanban never fetched — the gitea#2 bug scenario), seed
|
||||||
// Add task if this is the target column
|
// an empty kanban shell so the new task isn't silently dropped.
|
||||||
val updatedTasks = if (column.name == targetColumn) {
|
// The Phase 2 force-refresh after bulkCreateTasks/createTask will
|
||||||
filteredTasks + task
|
// 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 {
|
} else {
|
||||||
filteredTasks
|
// 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)
|
column.copy(tasks = updatedTasks, count = updatedTasks.size)
|
||||||
}
|
}
|
||||||
_allTasks.value = current.copy(columns = newColumns)
|
_allTasks.value = current.copy(columns = newColumns)
|
||||||
}
|
|
||||||
|
|
||||||
// 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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Refresh summary from updated kanban data (API no longer returns summaries for CRUD)
|
// Refresh summary from updated kanban data (API no longer returns summaries for CRUD)
|
||||||
refreshSummaryFromKanban()
|
refreshSummaryFromKanban()
|
||||||
persistToDisk()
|
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) {
|
fun removeTask(taskId: Int) {
|
||||||
// Remove from allTasks
|
// Remove from allTasks
|
||||||
_allTasks.value?.let { current ->
|
_allTasks.value?.let { current ->
|
||||||
|
|||||||
@@ -34,15 +34,20 @@ data class PresignUploadRequest(
|
|||||||
/**
|
/**
|
||||||
* Presigned upload session — response from POST /api/uploads/presign.
|
* Presigned upload session — response from POST /api/uploads/presign.
|
||||||
*
|
*
|
||||||
* The client uses [uploadUrl] + [fields] to perform a multipart/form-data
|
* The client makes one PUT request to [uploadUrl] with the raw object
|
||||||
* POST directly to B2, then passes [id] back in the upload_ids[] field of
|
* bytes as the body and [headers] as the request headers. On success,
|
||||||
* the next /api/task-completions/ or /api/documents/ create call.
|
* pass [id] back in the upload_ids[] field of the next
|
||||||
|
* /api/task-completions/ or /api/documents/ create call.
|
||||||
|
*
|
||||||
|
* PUT (not POST) because B2's S3-compatible endpoint does not implement
|
||||||
|
* the S3 POST Object form upload (returns HTTP 501).
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class PresignUploadResponse(
|
data class PresignUploadResponse(
|
||||||
val id: Int,
|
val id: Int,
|
||||||
@SerialName("upload_url") val uploadUrl: String,
|
@SerialName("upload_url") val uploadUrl: String,
|
||||||
val fields: Map<String, String>,
|
val method: String = "PUT",
|
||||||
|
val headers: Map<String, String> = emptyMap(),
|
||||||
val key: String,
|
val key: String,
|
||||||
@SerialName("expires_at") val expiresAt: String
|
@SerialName("expires_at") val expiresAt: String
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -615,37 +615,23 @@ object APILayer {
|
|||||||
return result
|
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> {
|
suspend fun getTasksByResidence(residenceId: Int, forceRefresh: Boolean = false): ApiResult<TaskColumnsResponse> {
|
||||||
// 1. Check residence-specific cache first
|
val allTasksResult = getTasks(forceRefresh = forceRefresh)
|
||||||
if (!forceRefresh && DataManager.isCacheValid(DataManager.tasksByResidenceCacheTime[residenceId] ?: 0L)) {
|
if (allTasksResult is ApiResult.Error) return allTasksResult
|
||||||
val cached = DataManager.tasksByResidence.value[residenceId]
|
|
||||||
if (cached != null) {
|
|
||||||
return ApiResult.Success(cached)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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)
|
val filtered = DataManager.getTasksForResidence(residenceId)
|
||||||
if (filtered != null) {
|
?: return ApiResult.Error("Tasks unavailable", 0)
|
||||||
// Cache the filtered result for future use
|
|
||||||
DataManager.setTasksForResidence(residenceId, filtered)
|
|
||||||
return ApiResult.Success(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
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun createTask(request: TaskCreateRequest): ApiResult<TaskResponse> {
|
suspend fun createTask(request: TaskCreateRequest): ApiResult<TaskResponse> {
|
||||||
val token = getToken() ?: return ApiResult.Error("Not authenticated", 401)
|
val token = getToken() ?: return ApiResult.Error("Not authenticated", 401)
|
||||||
@@ -667,9 +653,15 @@ object APILayer {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Atomically creates 1-50 tasks via POST /api/tasks/bulk/. The whole
|
* Atomically creates 1-50 tasks via POST /api/tasks/bulk/. The whole
|
||||||
* batch succeeds or fails together on the server. On success, every
|
* batch succeeds or fails together on the server. On success, force-
|
||||||
* returned task is merged into DataManager.allTasks so observing views
|
* refreshes _allTasks from the server — the server is the
|
||||||
* render the new batch immediately.
|
* 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> {
|
suspend fun bulkCreateTasks(request: BulkCreateTasksRequest): ApiResult<BulkCreateTasksResponse> {
|
||||||
val token = getToken() ?: return ApiResult.Error("Not authenticated", 401)
|
val token = getToken() ?: return ApiResult.Error("Not authenticated", 401)
|
||||||
@@ -677,7 +669,9 @@ object APILayer {
|
|||||||
|
|
||||||
if (result is ApiResult.Success) {
|
if (result is ApiResult.Success) {
|
||||||
DataManager.setTotalSummary(result.data.summary)
|
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
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ package com.tt.honeyDue.network
|
|||||||
*/
|
*/
|
||||||
object ApiConfig {
|
object ApiConfig {
|
||||||
// ⚠️ CHANGE THIS TO TOGGLE ENVIRONMENT ⚠️
|
// ⚠️ CHANGE THIS TO TOGGLE ENVIRONMENT ⚠️
|
||||||
val CURRENT_ENV = Environment.LOCAL
|
val CURRENT_ENV = Environment.PROD
|
||||||
|
|
||||||
enum class Environment {
|
enum class Environment {
|
||||||
LOCAL,
|
LOCAL,
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import com.tt.honeyDue.models.PresignUploadResponse
|
|||||||
import io.ktor.client.*
|
import io.ktor.client.*
|
||||||
import io.ktor.client.call.*
|
import io.ktor.client.call.*
|
||||||
import io.ktor.client.request.*
|
import io.ktor.client.request.*
|
||||||
import io.ktor.client.request.forms.*
|
|
||||||
import io.ktor.client.statement.*
|
import io.ktor.client.statement.*
|
||||||
import io.ktor.http.*
|
import io.ktor.http.*
|
||||||
import io.ktor.utils.io.core.*
|
import io.ktor.utils.io.core.*
|
||||||
@@ -14,17 +13,16 @@ import io.ktor.utils.io.core.*
|
|||||||
* Three-step direct-to-B2 upload helper.
|
* Three-step direct-to-B2 upload helper.
|
||||||
*
|
*
|
||||||
* Step 1: [presign] — call POST /api/uploads/presign on our API. Returns a
|
* Step 1: [presign] — call POST /api/uploads/presign on our API. Returns a
|
||||||
* B2 POST policy plus form fields the client needs to perform the
|
* signed PUT URL plus the headers the client must send.
|
||||||
* direct upload.
|
* Step 2: [putToStorage] — single PUT straight to B2. Bytes never traverse
|
||||||
* Step 2: [postToStorage] — multipart/form-data POST straight to B2.
|
* our API server.
|
||||||
* Bytes never traverse our API server.
|
|
||||||
* Step 3: caller invokes the relevant entity-creation endpoint
|
* Step 3: caller invokes the relevant entity-creation endpoint
|
||||||
* (POST /api/task-completions/, POST /api/documents/) with the
|
* (POST /api/task-completions/, POST /api/documents/) with the
|
||||||
* returned upload_id in the `upload_ids` field.
|
* returned upload_id in the `upload_ids` field.
|
||||||
*
|
*
|
||||||
* iOS uses its own native equivalent (PresignedUploader.swift) for memory
|
* iOS uses its own native equivalent (PresignedUploader.swift). Both paths
|
||||||
* reasons — Swift can stream a multipart body without buffering. Android
|
* use PUT because B2's S3-compatible endpoint does not implement the S3
|
||||||
* uses this Kotlin path which works fine for ≤10 MB images.
|
* POST Object form upload (returns HTTP 501 for any POST).
|
||||||
*/
|
*/
|
||||||
class UploadApi(private val client: HttpClient = ApiClient.httpClient) {
|
class UploadApi(private val client: HttpClient = ApiClient.httpClient) {
|
||||||
private val baseUrl = ApiClient.getBaseUrl()
|
private val baseUrl = ApiClient.getBaseUrl()
|
||||||
@@ -61,38 +59,36 @@ class UploadApi(private val client: HttpClient = ApiClient.httpClient) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Step 2 — POST `data` directly to B2 using the signed policy fields.
|
* Step 2 — PUT `data` directly to B2 using the signed URL + headers.
|
||||||
*
|
*
|
||||||
* The S3 POST policy spec requires every signed field to appear before
|
* The presign signature binds the headers exactly, so we send them
|
||||||
* the file part, and `key` + `Content-Type` must match the policy
|
* verbatim. Content-Length is filled in automatically by Ktor from
|
||||||
* exactly. Ktor's MultiPartFormDataContent preserves insertion order
|
* the body size, but we still pass through Content-Type which Ktor
|
||||||
* for the appended parts.
|
* would otherwise default to application/octet-stream.
|
||||||
*/
|
*/
|
||||||
suspend fun postToStorage(
|
suspend fun putToStorage(
|
||||||
uploadUrl: String,
|
uploadUrl: String,
|
||||||
fields: Map<String, String>,
|
headers: Map<String, String>,
|
||||||
data: ByteArray,
|
data: ByteArray,
|
||||||
contentType: String,
|
contentType: String,
|
||||||
fileName: String,
|
|
||||||
): ApiResult<Unit> {
|
): ApiResult<Unit> {
|
||||||
return try {
|
return try {
|
||||||
val parts = formData {
|
val response = client.put(uploadUrl) {
|
||||||
// Stable order: signed fields first, then file. We rely on
|
// Apply server-supplied headers verbatim. Skip Content-Length
|
||||||
// Ktor preserving the order in which append() is called.
|
// — Ktor sets it automatically from the body and will refuse
|
||||||
fields.forEach { (k, v) -> append(k, v) }
|
// a manual override on most engines.
|
||||||
append(
|
headers.forEach { (k, v) ->
|
||||||
key = "file",
|
if (!k.equals("Content-Length", ignoreCase = true)) {
|
||||||
value = data,
|
header(k, v)
|
||||||
headers = Headers.build {
|
}
|
||||||
append(HttpHeaders.ContentDisposition, "filename=\"$fileName\"")
|
}
|
||||||
append(HttpHeaders.ContentType, contentType)
|
// Defensive: ensure Content-Type is set even if the server
|
||||||
},
|
// omits it. The signed value (if present) takes precedence.
|
||||||
)
|
if (!headers.keys.any { it.equals("Content-Type", ignoreCase = true) }) {
|
||||||
|
header(HttpHeaders.ContentType, contentType)
|
||||||
|
}
|
||||||
|
setBody(data)
|
||||||
}
|
}
|
||||||
val response = client.submitFormWithBinaryData(
|
|
||||||
url = uploadUrl,
|
|
||||||
formData = parts,
|
|
||||||
)
|
|
||||||
if (response.status.isSuccess()) {
|
if (response.status.isSuccess()) {
|
||||||
ApiResult.Success(Unit)
|
ApiResult.Success(Unit)
|
||||||
} else {
|
} else {
|
||||||
@@ -124,7 +120,7 @@ class UploadApi(private val client: HttpClient = ApiClient.httpClient) {
|
|||||||
category: String,
|
category: String,
|
||||||
contentType: String,
|
contentType: String,
|
||||||
data: ByteArray,
|
data: ByteArray,
|
||||||
fileName: String,
|
@Suppress("UNUSED_PARAMETER") fileName: String,
|
||||||
): ApiResult<Int> {
|
): ApiResult<Int> {
|
||||||
val presignResult = presign(token, category, contentType, data.size.toLong())
|
val presignResult = presign(token, category, contentType, data.size.toLong())
|
||||||
val presigned = (presignResult as? ApiResult.Success)?.data
|
val presigned = (presignResult as? ApiResult.Success)?.data
|
||||||
@@ -133,16 +129,15 @@ class UploadApi(private val client: HttpClient = ApiClient.httpClient) {
|
|||||||
(presignResult as? ApiResult.Error)?.code,
|
(presignResult as? ApiResult.Error)?.code,
|
||||||
)
|
)
|
||||||
|
|
||||||
val postResult = postToStorage(
|
val putResult = putToStorage(
|
||||||
uploadUrl = presigned.uploadUrl,
|
uploadUrl = presigned.uploadUrl,
|
||||||
fields = presigned.fields,
|
headers = presigned.headers,
|
||||||
data = data,
|
data = data,
|
||||||
contentType = contentType,
|
contentType = contentType,
|
||||||
fileName = fileName,
|
|
||||||
)
|
)
|
||||||
return when (postResult) {
|
return when (putResult) {
|
||||||
is ApiResult.Success -> ApiResult.Success(presigned.id)
|
is ApiResult.Success -> ApiResult.Success(presigned.id)
|
||||||
is ApiResult.Error -> postResult
|
is ApiResult.Error -> putResult
|
||||||
else -> ApiResult.Error("Upload failed in unknown state")
|
else -> ApiResult.Error("Upload failed in unknown state")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,15 +70,26 @@ class ResidenceViewModel(
|
|||||||
/** Drives the residence-scoped projections. */
|
/** Drives the residence-scoped projections. */
|
||||||
private val _selectedResidenceId = MutableStateFlow<Int?>(null)
|
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>> =
|
val residenceTasksState: StateFlow<ApiResult<TaskColumnsResponse>> =
|
||||||
combine(_selectedResidenceId, dataManager.tasksByResidence) { id, map ->
|
combine(_selectedResidenceId, DataManager.allTasks) { id, all ->
|
||||||
if (id == null) ApiResult.Idle
|
when {
|
||||||
else map[id]?.let { ApiResult.Success(it) } ?: ApiResult.Idle
|
id == null -> ApiResult.Idle
|
||||||
|
all == null -> ApiResult.Loading
|
||||||
|
else -> {
|
||||||
|
val filtered = DataManager.getTasksForResidence(id)
|
||||||
|
if (filtered != null) ApiResult.Success(filtered) else ApiResult.Loading
|
||||||
|
}
|
||||||
|
}
|
||||||
}.stateIn(
|
}.stateIn(
|
||||||
viewModelScope,
|
viewModelScope,
|
||||||
SharingStarted.Eagerly,
|
SharingStarted.Eagerly,
|
||||||
_selectedResidenceId.value?.let { id ->
|
_selectedResidenceId.value?.let { id ->
|
||||||
dataManager.tasksByResidence.value[id]?.let { ApiResult.Success(it) }
|
DataManager.getTasksForResidence(id)?.let { ApiResult.Success(it) }
|
||||||
} ?: ApiResult.Idle,
|
} ?: 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
|
||||||
kotlin.code.style=official
|
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
|
#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.configuration-cache=true
|
||||||
org.gradle.caching=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 {
|
override func setUpWithError() throws {
|
||||||
guard TestAccountAPIClient.isBackendReachable() else {
|
guard TestAccountAPIClient.isBackendReachable() else {
|
||||||
throw XCTSkip("Backend not reachable at \(TestAccountAPIClient.baseURL)")
|
throw XCTSkip("Backend not reachable at \(TestAccountAPIClient.baseURL)")
|
||||||
@@ -41,27 +58,27 @@ class AuthenticatedUITestCase: BaseUITestCase {
|
|||||||
|
|
||||||
try super.setUpWithError()
|
try super.setUpWithError()
|
||||||
|
|
||||||
// If already logged in (tab bar visible), skip the login flow
|
|
||||||
let tabBar = app.tabBars.firstMatch
|
let tabBar = app.tabBars.firstMatch
|
||||||
if tabBar.waitForExistence(timeout: defaultTimeout) {
|
let alreadyLoggedIn = 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not logged in — do the full login flow
|
// 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)
|
UITestHelpers.ensureLoggedOut(app: app)
|
||||||
loginToMainApp()
|
loginToMainApp()
|
||||||
|
}
|
||||||
|
// (When `forceFreshLoginPerTest == false` AND we're already
|
||||||
|
// logged in, fall through with the existing session.)
|
||||||
|
|
||||||
if needsAPISession {
|
if needsAPISession {
|
||||||
guard let apiSession = TestAccountManager.loginSeededAccount(
|
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)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,15 +4,18 @@ import ComposeApp
|
|||||||
/// Three-step direct-to-B2 image upload.
|
/// Three-step direct-to-B2 image upload.
|
||||||
///
|
///
|
||||||
/// Flow:
|
/// Flow:
|
||||||
/// 1. POST /api/uploads/presign → server returns a B2 POST policy + form
|
/// 1. POST /api/uploads/presign → server returns a signed PUT URL plus
|
||||||
/// fields scoped to a single object key with a content-length-range
|
/// the headers (Content-Type, Content-Length) the client must send.
|
||||||
/// condition that B2 enforces at the protocol level.
|
/// The signature binds those headers — B2 rejects the upload if the
|
||||||
/// 2. Multipart POST the bytes directly to B2, no API server in the data
|
/// bytes/headers don't match exactly.
|
||||||
/// path. B2 rejects the upload if the bytes don't match the policy.
|
/// 2. PUT the bytes directly to B2, no API server in the data path.
|
||||||
/// 3. Caller passes the returned `uploadId` to /api/task-completions/ or
|
/// 3. Caller passes the returned `uploadId` to /api/task-completions/ or
|
||||||
/// /api/documents/ via `upload_ids[]`. The server HEADs the object,
|
/// /api/documents/ via `upload_ids[]`. The server HEADs the object,
|
||||||
/// confirms the size, and creates the linked entity rows.
|
/// confirms the size, and creates the linked entity rows.
|
||||||
///
|
///
|
||||||
|
/// We use PUT (not POST) because B2's S3-compatible endpoint does not
|
||||||
|
/// implement the S3 POST Object form upload — every POST returns HTTP 501.
|
||||||
|
///
|
||||||
/// All errors map to `PresignedUploaderError` — the Swift call site can
|
/// All errors map to `PresignedUploaderError` — the Swift call site can
|
||||||
/// translate to user-facing copy without parsing nested HTTP details.
|
/// translate to user-facing copy without parsing nested HTTP details.
|
||||||
enum PresignedUploaderError: Error, LocalizedError {
|
enum PresignedUploaderError: Error, LocalizedError {
|
||||||
@@ -33,7 +36,7 @@ enum PresignedUploaderError: Error, LocalizedError {
|
|||||||
default: return "Couldn't start upload (server returned \(status))."
|
default: return "Couldn't start upload (server returned \(status))."
|
||||||
}
|
}
|
||||||
case .uploadFailed(let status, _):
|
case .uploadFailed(let status, _):
|
||||||
return "Upload failed (B2 returned \(status))."
|
return "Upload failed (storage returned \(status))."
|
||||||
case .sessionError(let err):
|
case .sessionError(let err):
|
||||||
return err.localizedDescription
|
return err.localizedDescription
|
||||||
}
|
}
|
||||||
@@ -95,13 +98,12 @@ final class PresignedUploader {
|
|||||||
contentLength: Int64(data.count)
|
contentLength: Int64(data.count)
|
||||||
)
|
)
|
||||||
|
|
||||||
// Step 2: direct POST to B2
|
// Step 2: direct PUT to B2
|
||||||
try await postToStorage(
|
try await putToStorage(
|
||||||
uploadURL: presigned.uploadUrl,
|
uploadURL: presigned.uploadUrl,
|
||||||
fields: presigned.fields,
|
headers: presigned.headers,
|
||||||
data: data,
|
data: data,
|
||||||
contentType: contentType,
|
contentType: contentType
|
||||||
fileName: fileName
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return Int32(presigned.id)
|
return Int32(presigned.id)
|
||||||
@@ -146,7 +148,8 @@ final class PresignedUploader {
|
|||||||
private struct PresignResponse: Decodable {
|
private struct PresignResponse: Decodable {
|
||||||
let id: Int
|
let id: Int
|
||||||
let upload_url: String
|
let upload_url: String
|
||||||
let fields: [String: String]
|
let method: String?
|
||||||
|
let headers: [String: String]
|
||||||
let key: String
|
let key: String
|
||||||
let expires_at: String
|
let expires_at: String
|
||||||
|
|
||||||
@@ -196,64 +199,39 @@ final class PresignedUploader {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Step 2: POST to B2
|
// MARK: - Step 2: PUT to B2
|
||||||
|
//
|
||||||
|
// The presign response includes the exact headers (Content-Type +
|
||||||
|
// Content-Length) that were signed. Send them verbatim — any deviation
|
||||||
|
// invalidates the signature and B2 will reject the upload.
|
||||||
|
//
|
||||||
|
// Content-Length is set automatically by URLSession from httpBody.count,
|
||||||
|
// so we don't manually echo it back; we still send Content-Type because
|
||||||
|
// URLSession will otherwise default it to application/x-www-form-urlencoded.
|
||||||
|
|
||||||
private func postToStorage(
|
private func putToStorage(
|
||||||
uploadURL: String,
|
uploadURL: String,
|
||||||
fields: [String: String],
|
headers: [String: String],
|
||||||
data: Data,
|
data: Data,
|
||||||
contentType: String,
|
contentType: String
|
||||||
fileName: String
|
|
||||||
) async throws {
|
) async throws {
|
||||||
guard let url = URL(string: uploadURL) else {
|
guard let url = URL(string: uploadURL) else {
|
||||||
throw PresignedUploaderError.uploadFailed(status: 0, body: "invalid upload url")
|
throw PresignedUploaderError.uploadFailed(status: 0, body: "invalid upload url")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a multipart/form-data body with all policy fields followed
|
|
||||||
// by a single "file" part (S3 POST policy mandates the file part
|
|
||||||
// come last).
|
|
||||||
let boundary = "Boundary-\(UUID().uuidString)"
|
|
||||||
var body = Data()
|
|
||||||
let crlf = "\r\n"
|
|
||||||
let appendString: (String) -> Void = { s in
|
|
||||||
body.append(s.data(using: .utf8) ?? Data())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stable order: ensure "key" and "Content-Type" appear before the
|
|
||||||
// file part so the policy signature validates. Unspecified order
|
|
||||||
// for the rest — S3 accepts any.
|
|
||||||
let orderedKeys = ["key", "Content-Type", "policy", "x-amz-algorithm",
|
|
||||||
"x-amz-credential", "x-amz-date", "x-amz-signature",
|
|
||||||
"x-amz-meta-uid"]
|
|
||||||
var emitted = Set<String>()
|
|
||||||
for k in orderedKeys {
|
|
||||||
if let v = fields[k] {
|
|
||||||
appendString("--\(boundary)\(crlf)")
|
|
||||||
appendString("Content-Disposition: form-data; name=\"\(k)\"\(crlf)\(crlf)")
|
|
||||||
appendString(v)
|
|
||||||
appendString(crlf)
|
|
||||||
emitted.insert(k)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (k, v) in fields where !emitted.contains(k) {
|
|
||||||
appendString("--\(boundary)\(crlf)")
|
|
||||||
appendString("Content-Disposition: form-data; name=\"\(k)\"\(crlf)\(crlf)")
|
|
||||||
appendString(v)
|
|
||||||
appendString(crlf)
|
|
||||||
}
|
|
||||||
|
|
||||||
// file part — must be last
|
|
||||||
appendString("--\(boundary)\(crlf)")
|
|
||||||
appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\(crlf)")
|
|
||||||
appendString("Content-Type: \(contentType)\(crlf)\(crlf)")
|
|
||||||
body.append(data)
|
|
||||||
appendString(crlf)
|
|
||||||
appendString("--\(boundary)--\(crlf)")
|
|
||||||
|
|
||||||
var req = URLRequest(url: url)
|
var req = URLRequest(url: url)
|
||||||
req.httpMethod = "POST"
|
req.httpMethod = "PUT"
|
||||||
req.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
|
req.httpBody = data
|
||||||
req.httpBody = body
|
|
||||||
|
// Apply server-supplied headers verbatim. Skip Content-Length —
|
||||||
|
// URLSession sets it automatically and will refuse to override it.
|
||||||
|
for (k, v) in headers where k.lowercased() != "content-length" {
|
||||||
|
req.setValue(v, forHTTPHeaderField: k)
|
||||||
|
}
|
||||||
|
// Defensive: ensure Content-Type is set even if the server omits it.
|
||||||
|
if req.value(forHTTPHeaderField: "Content-Type") == nil {
|
||||||
|
req.setValue(contentType, forHTTPHeaderField: "Content-Type")
|
||||||
|
}
|
||||||
|
|
||||||
let (respBody, response): (Data, URLResponse)
|
let (respBody, response): (Data, URLResponse)
|
||||||
do {
|
do {
|
||||||
|
|||||||
@@ -366,7 +366,12 @@ struct OnboardingCreateAccountContent: View {
|
|||||||
}
|
}
|
||||||
.onChange(of: viewModel.isRegistered) { _, isRegistered in
|
.onChange(of: viewModel.isRegistered) { _, isRegistered in
|
||||||
if isRegistered {
|
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)
|
onAccountCreated(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -451,7 +456,13 @@ private struct OrganicOnboardingSecureField: View {
|
|||||||
@Binding var text: String
|
@Binding var text: String
|
||||||
var isFocused: Bool = false
|
var isFocused: Bool = false
|
||||||
var accessibilityIdentifier: String? = nil
|
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 {
|
var body: some View {
|
||||||
HStack(spacing: 14) {
|
HStack(spacing: 14) {
|
||||||
|
|||||||
@@ -120,7 +120,6 @@ struct CompleteTaskView: View {
|
|||||||
.foregroundStyle(.secondary)
|
.foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
.padding(.leading, 12)
|
.padding(.leading, 12)
|
||||||
.keyboardDismissToolbar()
|
|
||||||
.accessibilityIdentifier(AccessibilityIdentifiers.Task.actualCostField)
|
.accessibilityIdentifier(AccessibilityIdentifiers.Task.actualCostField)
|
||||||
} label: {
|
} label: {
|
||||||
Label(L10n.Tasks.actualCost, systemImage: "dollarsign.circle")
|
Label(L10n.Tasks.actualCost, systemImage: "dollarsign.circle")
|
||||||
@@ -142,7 +141,6 @@ struct CompleteTaskView: View {
|
|||||||
TextEditor(text: $notes)
|
TextEditor(text: $notes)
|
||||||
.frame(minHeight: 100)
|
.frame(minHeight: 100)
|
||||||
.scrollContentBackground(.hidden)
|
.scrollContentBackground(.hidden)
|
||||||
.keyboardDismissToolbar()
|
|
||||||
.accessibilityIdentifier(AccessibilityIdentifiers.Task.notesField)
|
.accessibilityIdentifier(AccessibilityIdentifiers.Task.notesField)
|
||||||
}
|
}
|
||||||
} footer: {
|
} footer: {
|
||||||
@@ -289,6 +287,12 @@ struct CompleteTaskView: View {
|
|||||||
.background(WarmGradientBackground())
|
.background(WarmGradientBackground())
|
||||||
.navigationTitle(L10n.Tasks.completeTask)
|
.navigationTitle(L10n.Tasks.completeTask)
|
||||||
.navigationBarTitleDisplayMode(.inline)
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
// ONE keyboard "Done" toolbar at the form root — per-field
|
||||||
|
// `.keyboardDismissToolbar()` modifiers each install a
|
||||||
|
// separate `ToolbarItemGroup(placement: .keyboard)`, and
|
||||||
|
// SwiftUI stacks them on the responder chain so any focused
|
||||||
|
// field renders multiple Done buttons side-by-side (issue #5).
|
||||||
|
.keyboardDismissToolbar()
|
||||||
.toolbar {
|
.toolbar {
|
||||||
ToolbarItem(placement: .cancellationAction) {
|
ToolbarItem(placement: .cancellationAction) {
|
||||||
Button(L10n.Common.cancel) {
|
Button(L10n.Common.cancel) {
|
||||||
|
|||||||
@@ -42,6 +42,12 @@ class TaskViewModel: ObservableObject {
|
|||||||
private let dataManager: DataManagerObservable
|
private let dataManager: DataManagerObservable
|
||||||
|
|
||||||
// MARK: - Initialization
|
// 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.
|
/// - Parameter dataManager: Observable cache the VM subscribes to.
|
||||||
/// Defaults to the shared singleton. Tests inject a fixture-backed
|
/// Defaults to the shared singleton. Tests inject a fixture-backed
|
||||||
/// instance so populated-state snapshots render real data.
|
/// instance so populated-state snapshots render real data.
|
||||||
@@ -50,35 +56,26 @@ class TaskViewModel: ObservableObject {
|
|||||||
|
|
||||||
// Seed from current cache so snapshot tests/previews render
|
// Seed from current cache so snapshot tests/previews render
|
||||||
// populated state without waiting for Combine's async dispatch.
|
// 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
|
self.tasksResponse = dataManager.allTasks
|
||||||
|
|
||||||
// Observe injected DataManagerObservable for all tasks data
|
// Observe injected DataManagerObservable for all tasks data.
|
||||||
dataManager.$allTasks
|
dataManager.$allTasks
|
||||||
.receive(on: DispatchQueue.main)
|
.receive(on: DispatchQueue.main)
|
||||||
.sink { [weak self] allTasks in
|
.sink { [weak self] allTasks in
|
||||||
// Skip DataManager updates during completion animation to prevent
|
guard let self else { return }
|
||||||
// the task from being moved out of its column before the animation finishes
|
guard !self.isAnimatingCompletion else { return }
|
||||||
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)
|
|
||||||
|
|
||||||
// Observe tasks by residence
|
if let allTasks {
|
||||||
dataManager.$tasksByResidence
|
if let resId = self.currentResidenceId {
|
||||||
.receive(on: DispatchQueue.main)
|
self.tasksResponse = self.filterTasks(allTasks, residenceId: resId)
|
||||||
.sink { [weak self] tasksByResidence in
|
} else {
|
||||||
guard self?.isAnimatingCompletion != true else { return }
|
self.tasksResponse = allTasks
|
||||||
// Only update if we're filtering by residence
|
}
|
||||||
if let resId = self?.currentResidenceId,
|
self.isLoadingTasks = false
|
||||||
let tasks = tasksByResidence[resId] {
|
|
||||||
self?.tasksResponse = tasks
|
|
||||||
self?.isLoadingTasks = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.store(in: &cancellables)
|
.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
|
/// Updates a task in the kanban board by moving it to the correct column based on kanban_column
|
||||||
func updateTaskInKanban(_ updatedTask: TaskResponse) {
|
func updateTaskInKanban(_ updatedTask: TaskResponse) {
|
||||||
guard let currentResponse = tasksResponse else { return }
|
guard let currentResponse = tasksResponse else { return }
|
||||||
|
|||||||
Reference in New Issue
Block a user