Skip to content

Commit 6a4e4e1

Browse files
authored
Let the app workspace be reset from the workspace screens (#113)
Refs #106
1 parent 28ceacb commit 6a4e4e1

29 files changed

Lines changed: 362 additions & 8 deletions

‎app/src/main/java/com/androidharness/app/data/db/Database.kt‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,32 @@ interface HarnessDao {
375375
deleteProject(project)
376376
}
377377

378+
/**
379+
* Deletes the app workspace's chats but keeps its row: the workspace itself is the
380+
* permanent default, so "reset" only empties it. Its folder is cleared separately.
381+
*/
382+
@androidx.room.Transaction
383+
suspend fun deleteAppWorkspaceChats(projectId: String, expectedChatIds: Set<String>) {
384+
val project = requireNotNull(project(projectId)) { "This workspace is no longer available." }
385+
check(project.kind == "APP") { "Only the app workspace can be reset this way." }
386+
val chats = projectSessions(projectId)
387+
check(chats.all { it.projectId == projectId }) {
388+
"Chats in another project still use this workspace. Remove its access from those chats before resetting it."
389+
}
390+
check(chats.map { it.id }.toSet() == expectedChatIds) {
391+
"The workspace's chats changed. Close this dialog and review the reset again."
392+
}
393+
chats.forEach { chat ->
394+
deleteSavedAnswers(chat.id)
395+
deleteMessages(chat.id)
396+
deleteCheckpoints(chat.id)
397+
deleteUsageEvents(chat.id)
398+
deleteFileEdits(chat.id)
399+
deleteSessionFileChanges(chat.id)
400+
deleteSession(chat)
401+
}
402+
}
403+
378404
@Insert
379405
suspend fun insertSession(session: SessionEntity)
380406

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.androidharness.app.ui.projects
2+
3+
import androidx.compose.foundation.layout.Arrangement
4+
import androidx.compose.foundation.layout.Column
5+
import androidx.compose.foundation.rememberScrollState
6+
import androidx.compose.foundation.verticalScroll
7+
import androidx.compose.material.icons.Icons
8+
import androidx.compose.material.icons.outlined.RestartAlt
9+
import androidx.compose.material3.AlertDialog
10+
import androidx.compose.material3.ButtonDefaults
11+
import androidx.compose.material3.Icon
12+
import androidx.compose.material3.MaterialTheme
13+
import androidx.compose.material3.Text
14+
import androidx.compose.runtime.Composable
15+
import androidx.compose.runtime.LaunchedEffect
16+
import androidx.compose.runtime.getValue
17+
import androidx.compose.runtime.mutableStateOf
18+
import androidx.compose.runtime.remember
19+
import androidx.compose.runtime.rememberCoroutineScope
20+
import androidx.compose.runtime.setValue
21+
import androidx.compose.ui.Modifier
22+
import androidx.compose.ui.platform.LocalContext
23+
import androidx.compose.ui.unit.dp
24+
import com.androidharness.app.AppContainer
25+
import com.androidharness.app.R
26+
import com.androidharness.app.data.db.ProjectEntity
27+
import com.androidharness.app.ui.common.TextButton
28+
import com.androidharness.app.ui.settings.storageSize
29+
import com.androidharness.app.workspace.AppWorkspaceResetPreview
30+
import kotlinx.coroutines.CancellationException
31+
import kotlinx.coroutines.launch
32+
33+
/**
34+
* Empties the permanent app workspace (issue #106). Unlike [ProjectDeletionDialog] the
35+
* workspace row survives, because new chats always need a default workspace.
36+
*/
37+
@Composable
38+
internal fun AppWorkspaceResetDialog(
39+
container: AppContainer,
40+
project: ProjectEntity,
41+
onDismiss: () -> Unit,
42+
onReset: (Set<String>) -> Unit,
43+
) {
44+
val uiContext = LocalContext.current
45+
var preview by remember(project.id) { mutableStateOf<AppWorkspaceResetPreview?>(null) }
46+
var error by remember(project.id) { mutableStateOf<String?>(null) }
47+
var resetting by remember(project.id) { mutableStateOf(false) }
48+
val scope = rememberCoroutineScope()
49+
LaunchedEffect(project.id) {
50+
try { preview = container.projectDeletion.previewAppWorkspace(project.id) }
51+
catch (e: CancellationException) { throw e }
52+
catch (e: Exception) { error = e.message ?: uiContext.getString(R.string.wp_workspace_delete_review_failed) }
53+
}
54+
AlertDialog(
55+
onDismissRequest = { if (!resetting) onDismiss() },
56+
icon = { Icon(Icons.Outlined.RestartAlt, null) },
57+
title = { Text(uiContext.getString(R.string.wp_app_workspace_reset_title)) },
58+
text = {
59+
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(12.dp)) {
60+
Text(project.name, style = MaterialTheme.typography.titleSmall)
61+
val review = preview
62+
if (review == null && error == null) Text(uiContext.getString(R.string.wp_workspace_delete_checking))
63+
if (review != null) {
64+
val chats = "${review.chatIds.size} saved ${if (review.chatIds.size == 1) "chat" else "chats"}"
65+
val automations = "${review.automationIds.size} ${if (review.automationIds.size == 1) "automation" else "automations"}"
66+
Text(uiContext.getString(R.string.wp_app_workspace_reset_body, chats, automations, storageSize(review.folderBytes)))
67+
review.blocker?.let { Text(it, color = MaterialTheme.colorScheme.error) }
68+
}
69+
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
70+
}
71+
},
72+
confirmButton = {
73+
TextButton(
74+
enabled = !resetting && error == null && preview?.blocker == null && preview != null,
75+
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error),
76+
onClick = {
77+
val review = preview ?: return@TextButton
78+
resetting = true
79+
scope.launch {
80+
try { container.projectDeletion.resetAppWorkspace(review); onReset(review.chatIds) }
81+
catch (e: CancellationException) { throw e }
82+
catch (e: Exception) { error = e.message ?: uiContext.getString(R.string.ui_could_not_delete_this_project) }
83+
finally { resetting = false }
84+
}
85+
},
86+
) {
87+
Text(if (resetting) uiContext.getString(R.string.ui_deleting)
88+
else uiContext.getString(R.string.wp_app_workspace_reset_confirm))
89+
}
90+
},
91+
dismissButton = { TextButton(enabled = !resetting, onClick = onDismiss) { Text(uiContext.getString(R.string.ui_keep_project)) } },
92+
)
93+
}

‎app/src/main/java/com/androidharness/app/ui/projects/ProjectsScreen.kt‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ fun ProjectsScreen(container: AppContainer, onBack: () -> Unit, onOpenProject: (
7171
var adding by rememberSaveable { mutableStateOf(false) }
7272
var error by remember { mutableStateOf<String?>(null) }
7373
var deleting by remember { mutableStateOf<ProjectEntity?>(null) }
74+
var resetting by remember { mutableStateOf<ProjectEntity?>(null) }
7475
val scope = rememberCoroutineScope()
7576
fun finishAdd(id: String?) {
7677
adding = false
@@ -93,16 +94,22 @@ fun ProjectsScreen(container: AppContainer, onBack: () -> Unit, onOpenProject: (
9394
var menu by remember { mutableStateOf(false) }
9495
ExpressiveListRow(index, projects.size, project.name,
9596
subtitle = "${container.workspace.describe(project).kindLabel} · $count ${if (count == 1) "chat" else "chats"}",
96-
onClick = { onOpenProject(project.id) }, onLongClick = { if (project.kind != com.androidharness.app.workspace.WorkspaceManager.KIND_APP) menu = true },
97+
onClick = { onOpenProject(project.id) }, onLongClick = { menu = true },
9798
modifier = Modifier.animateItem(fadeInSpec = expressiveEffectsSpec(), placementSpec = expressiveSpatialSpec(), fadeOutSpec = expressiveEffectsSpec()),
9899
leading = { ExpressiveIconBadge(workspaceKindIcon(project.kind)) },
99100
trailing = {
100-
if (project.kind != com.androidharness.app.workspace.WorkspaceManager.KIND_APP) Box {
101+
Box {
101102
ExpressiveIconButton(onClick = { menu = true }) { Icon(Icons.Outlined.MoreVert, uiContext.getString(R.string.wp_actions_for_workspace, project.name)) }
102103
ExpressiveDropdownMenu(menu, { menu = false }) {
103-
ExpressiveDropdownMenuItem(text = { Text(uiContext.getString(R.string.wp_workspace_delete), color = MaterialTheme.colorScheme.error) },
104-
leadingIcon = { Icon(Icons.Outlined.DeleteOutline, null, tint = MaterialTheme.colorScheme.error) },
105-
onClick = { menu = false; deleting = project })
104+
if (project.kind == com.androidharness.app.workspace.WorkspaceManager.KIND_APP) {
105+
ExpressiveDropdownMenuItem(text = { Text(uiContext.getString(R.string.wp_app_workspace_reset), color = MaterialTheme.colorScheme.error) },
106+
leadingIcon = { Icon(Icons.Outlined.RestartAlt, null, tint = MaterialTheme.colorScheme.error) },
107+
onClick = { menu = false; resetting = project })
108+
} else {
109+
ExpressiveDropdownMenuItem(text = { Text(uiContext.getString(R.string.wp_workspace_delete), color = MaterialTheme.colorScheme.error) },
110+
leadingIcon = { Icon(Icons.Outlined.DeleteOutline, null, tint = MaterialTheme.colorScheme.error) },
111+
onClick = { menu = false; deleting = project })
112+
}
106113
}
107114
}
108115
})
@@ -121,6 +128,8 @@ fun ProjectsScreen(container: AppContainer, onBack: () -> Unit, onOpenProject: (
121128
onPickSaf = { adding = false; picker.launch(null) }, onSelected = { finishAdd(it) }, activateWorkspace = false)
122129
deleting?.let { project -> ProjectDeletionDialog(container, project,
123130
onDismiss = { deleting = null }, onDeleted = { deleting = null; onProjectDeleted() }) }
131+
resetting?.let { project -> AppWorkspaceResetDialog(container, project,
132+
onDismiss = { resetting = null }, onReset = { resetting = null; onProjectDeleted() }) }
124133
}
125134

126135
@Composable
@@ -158,6 +167,7 @@ fun ProjectScreen(
158167
var showRepository by rememberSaveable(projectId) { mutableStateOf(false) }
159168
var showDetails by rememberSaveable(projectId) { mutableStateOf(false) }
160169
var deletingProject by remember(projectId) { mutableStateOf<ProjectEntity?>(null) }
170+
var resettingProject by remember(projectId) { mutableStateOf<ProjectEntity?>(null) }
161171
var repository by remember(projectId) { mutableStateOf<String?>(null) }
162172
val environment by container.linuxEnv.state.collectAsStateWithLifecycle()
163173
var refresh by remember(projectId) { mutableIntStateOf(0) }
@@ -331,9 +341,12 @@ fun ProjectScreen(
331341
if (showRepository && project != null) GitHubWorkspaceDialog(container, project.id, project.name,
332342
onOpenSettings = onOpenSettings, onDismiss = { showRepository = false })
333343
if (showDetails && project != null) ProjectDetailsDialog(container, project, onDismiss = { showDetails = false },
334-
onDelete = { showDetails = false; deletingProject = project })
344+
onDelete = { showDetails = false; deletingProject = project },
345+
onResetApp = { showDetails = false; resettingProject = project })
335346
deletingProject?.let { target -> ProjectDeletionDialog(container, target,
336347
onDismiss = { deletingProject = null }, onDeleted = { deletingProject = null; onProjectDeleted() }) }
348+
resettingProject?.let { target -> AppWorkspaceResetDialog(container, target,
349+
onDismiss = { resettingProject = null }, onReset = { resettingProject = null; onProjectDeleted() }) }
337350
}
338351

339352
private fun AutomationTask.projectStatus(): String = when {
@@ -352,7 +365,7 @@ internal fun ProjectRow(title: String, subtitle: String? = null, icon: ImageVect
352365
}
353366

354367
@Composable
355-
private fun ProjectDetailsDialog(container: AppContainer, project: ProjectEntity, onDismiss: () -> Unit, onDelete: () -> Unit) {
368+
private fun ProjectDetailsDialog(container: AppContainer, project: ProjectEntity, onDismiss: () -> Unit, onDelete: () -> Unit, onResetApp: () -> Unit) {
356369
val uiContext = androidx.compose.ui.platform.LocalContext.current
357370
var name by rememberSaveable(project.id) { mutableStateOf(project.name) }
358371
var error by remember { mutableStateOf<String?>(null) }
@@ -372,7 +385,14 @@ private fun ProjectDetailsDialog(container: AppContainer, project: ProjectEntity
372385
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)) {
373386
Icon(Icons.Outlined.DeleteOutline, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(uiContext.getString(R.string.wp_workspace_delete))
374387
}
375-
} else Text(uiContext.getString(R.string.ui_the_app_workspace_cannot_be_deleted), style = MaterialTheme.typography.bodySmall)
388+
} else {
389+
HorizontalDivider()
390+
TextButton(onClick = onResetApp, enabled = !saving,
391+
colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)) {
392+
Icon(Icons.Outlined.RestartAlt, null, Modifier.size(18.dp)); Spacer(Modifier.width(8.dp))
393+
Text(uiContext.getString(R.string.wp_app_workspace_reset))
394+
}
395+
}
376396
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
377397
}
378398
}, confirmButton = {
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.androidharness.app.workspace
2+
3+
import java.io.File
4+
5+
/**
6+
* File operations behind "Reset app workspace" (issue #106). The app workspace is the
7+
* permanent default, so it cannot be deleted like other workspaces; resetting empties it
8+
* instead. Kept free of Android APIs so it is unit-testable.
9+
*/
10+
internal object AppWorkspaceReset {
11+
/** Deletes every child of [root] and recreates the empty folder. */
12+
fun clear(root: File) {
13+
root.listFiles()?.forEach { it.deleteRecursively() }
14+
root.mkdirs()
15+
}
16+
17+
/** Bytes held by the files under [root]; a missing folder counts as zero. */
18+
fun bytes(root: File): Long =
19+
if (!root.exists()) 0L else root.walkTopDown().filter { it.isFile }.sumOf { it.length() }
20+
}

‎app/src/main/java/com/androidharness/app/workspace/ProjectDeletion.kt‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ data class ProjectDeletionPreview(
1414
val blocker: String?,
1515
)
1616

17+
/** Review for emptying the permanent app workspace; the row itself always stays. */
18+
data class AppWorkspaceResetPreview(
19+
val project: ProjectEntity,
20+
val chatIds: Set<String>,
21+
val automationIds: Set<String>,
22+
val folderBytes: Long,
23+
val blocker: String?,
24+
)
25+
1726
class ProjectDeletion(private val c: AppContainer) {
1827
suspend fun preview(projectId: String): ProjectDeletionPreview {
1928
val project = requireNotNull(c.workspace.projects.first().firstOrNull { it.id == projectId }) {
@@ -54,4 +63,50 @@ class ProjectDeletion(private val c: AppContainer) {
5463
}
5564
}
5665
}
66+
67+
/**
68+
* Review for "reset app workspace" (issue #106). [preview] keeps refusing the app
69+
* workspace, because the app always needs one; this path empties it instead.
70+
*/
71+
suspend fun previewAppWorkspace(projectId: String): AppWorkspaceResetPreview {
72+
val project = requireNotNull(c.workspace.projects.first().firstOrNull { it.id == projectId }) {
73+
"This workspace is no longer available."
74+
}
75+
require(project.kind == WorkspaceManager.KIND_APP) { "Only the app workspace can be reset." }
76+
val related = c.workspace.projectChats(projectId)
77+
val owned = related.filter { it.projectId == projectId }.map { it.id }.toSet()
78+
val shared = related.filter { it.projectId != projectId }
79+
val automations = c.automation.repository.tasks.value.filter {
80+
it.projectId == projectId || it.targetSessionId in owned || it.activeRun?.sessionId in owned
81+
}.map { it.id }.toSet()
82+
val blocker = when {
83+
shared.isNotEmpty() ->
84+
"Other chats also use the app workspace: ${shared.joinToString { it.title }}. Remove this workspace from those chats before resetting it."
85+
related.any { c.runManager.isRunning(it.id) || c.runManager.hasPendingFollowUp(it.id) } ->
86+
"Stop running tasks in this workspace before resetting it."
87+
else -> null
88+
}
89+
val bytes = withContext(Dispatchers.IO) { c.workspace.appWorkspaceBytes() }
90+
return AppWorkspaceResetPreview(project, owned, automations, bytes, blocker)
91+
}
92+
93+
/** Empties the app workspace once its chats and automations can be removed. */
94+
suspend fun resetAppWorkspace(reviewed: AppWorkspaceResetPreview) = withContext(Dispatchers.IO) {
95+
c.automation.withIdleAutomations {
96+
c.runManager.withIdleProject(reviewed.project.id) {
97+
val current = previewAppWorkspace(reviewed.project.id)
98+
check(current.blocker == null) { current.blocker.orEmpty() }
99+
check(current.chatIds == reviewed.chatIds && current.automationIds == reviewed.automationIds) {
100+
"This workspace changed. Close this dialog and review the reset again."
101+
}
102+
// Complete cleanup even if navigation disposes the confirmation dialog.
103+
withContext(NonCancellable) {
104+
c.workspace.resetAppWorkspace(current.project.id, current.chatIds)
105+
current.automationIds.forEach(c.automation::delete)
106+
c.automation.repository.detachDeletedChats(current.chatIds)
107+
c.settings.removeProjectReferences(current.project.id, current.chatIds)
108+
}
109+
}
110+
}
111+
}
57112
}

‎app/src/main/java/com/androidharness/app/workspace/WorkspaceManager.kt‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,21 @@ class WorkspaceManager(
331331
releaseProjectResources(project)
332332
}
333333

334+
/**
335+
* Empties the app workspace (issue #106): its chats and every file under the
336+
* app-private folder, which is the closest thing to deleting it. The row stays
337+
* because every chat needs a default workspace to fall back on.
338+
*/
339+
suspend fun resetAppWorkspace(projectId: String, expectedChatIds: Set<String>) {
340+
val project = requireNotNull(dao.project(projectId)) { "This workspace is no longer available." }
341+
require(project.kind == KIND_APP) { "Only the app workspace can be reset." }
342+
dao.deleteAppWorkspaceChats(projectId, expectedChatIds)
343+
AppWorkspaceReset.clear(appPrivateRoot)
344+
}
345+
346+
/** Size of the app workspace folder, shown before a reset. */
347+
fun appWorkspaceBytes(): Long = AppWorkspaceReset.bytes(appPrivateRoot)
348+
334349
private suspend fun releaseProjectResources(project: ProjectEntity) {
335350
if (project.kind == KIND_SSH) {
336351
val id = runCatching { kotlinx.serialization.json.Json.decodeFromString<SshLocation>(requireNotNull(project.uri)).connectionId }.getOrNull()

‎app/src/main/res/values-ar/workspace_project_strings.xml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,8 @@
9393
<string name="wp_workspace_delete_checking">Checking workspace…</string>
9494
<string name="wp_workspace_delete_review_failed">Could not review this workspace</string>
9595
<string name="wp_workspace_delete_body">Removes this workspace, %1$s and %2$s from the app. Conversation history and undo history for these chats will be deleted. This cannot be undone.</string>
96+
<string name="wp_app_workspace_reset">إعادة تعيين مساحة عمل التطبيق…</string>
97+
<string name="wp_app_workspace_reset_title">هل تريد إعادة تعيين مساحة عمل التطبيق؟</string>
98+
<string name="wp_app_workspace_reset_body">يحذف %1$s و%2$s وكل الملفات في مجلد مساحة عمل التطبيق على هذا الجهاز (بإجمالي %3$s)، بما في ذلك ذاكرة المشروع وسجل التراجع. تبقى مساحة العمل كافتراضي فارغ. لا يمكن التراجع عن هذا الإجراء.</string>
99+
<string name="wp_app_workspace_reset_confirm">إعادة تعيين مساحة العمل</string>
96100
</resources>

0 commit comments

Comments
 (0)