Skip to content
Merged
2 changes: 2 additions & 0 deletions android/app/src/main/java/dev/opencode/mobile/Navigation.kt
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,8 @@ fun MainNavigation() {
HomeDisplayPreferences.hideUserDirectoryPrefix,
onHideUserDirectoryPrefixChange =
settingsViewModel::setHideUserDirectoryPrefix,
showsWorktrees = HomeDisplayPreferences.showsWorktrees,
onShowsWorktreesChange = settingsViewModel::setShowsWorktrees,
recentWindowHours = HomeDisplayPreferences.recentWindowHours,
onRecentWindowHoursChange =
settingsViewModel::setRecentWindowHours,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import dev.opencode.mobile.data.remote.dto.V2InboxDeliveryRequestDto
import dev.opencode.mobile.data.remote.dto.V2InboxItemDto
import dev.opencode.mobile.data.remote.dto.V2LocationDto
import dev.opencode.mobile.data.remote.dto.V2LocationInfoDto
import dev.opencode.mobile.data.remote.dto.V2MoveSessionRequestDto
import dev.opencode.mobile.data.remote.dto.V2PermissionReplyRequestDto
import dev.opencode.mobile.data.remote.dto.V2PermissionRequestDto
import dev.opencode.mobile.data.remote.dto.V2RenameSessionRequestDto
Expand Down Expand Up @@ -548,6 +549,20 @@ class SessionsApi private constructor(
}
}.decodeV2Session()

/**
* `POST /api/session/{id}/move`: moves the session to [directory] at the next delivery
* boundary. 204 with no body; 400 / 404 carry the server's message.
*/
suspend fun moveSessionV2(
id: String,
directory: String,
): Boolean =
httpClient
.get()
.post("api/session/$id/move") {
setJsonBody(json, V2MoveSessionRequestDto(directory = directory))
}.ensureSuccess()

suspend fun compactSessionV2(id: String): Boolean =
httpClient
.get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@ data class V2ForkSessionRequestDto(
val before: String? = null,
)

/** `POST /api/session/{id}/move`: the destination directory only; the server's default delivery (steer) applies. */
@Serializable
data class V2MoveSessionRequestDto(
val directory: String,
)

@Serializable
data class V2PermissionRequestDto(
val id: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ data class ServerCapabilities(
val supportsFollowUpDelivery: Boolean,
/** Server tracks per-session read state (`time.idle`/`time.viewed`, `session.viewed`). */
val supportsSessionViewed: Boolean = false,
/** Server moves a session to another worktree (`POST /api/session/{id}/move`, v2). */
val supportsSessionMove: Boolean = false,
) {
companion object {
fun forProtocol(
Expand All @@ -53,6 +55,7 @@ data class ServerCapabilities(
supportsSessionArchive = v2Features.sessionArchive,
supportsFollowUpDelivery = true,
supportsSessionViewed = true,
supportsSessionMove = true,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ class EventDomainAdapter(
"session.next.moved",
"session.moved",
->
listOf(event("session.updated", properties)) +
listOf(event("session.updated", properties), event(SESSION_MOVED_EVENT, properties)) +
noticeEvents(V2TimelineNotices.moved(properties), properties, envelopeId)
"session.next.agent.switched",
"session.agent.selected",
Expand Down Expand Up @@ -1390,6 +1390,9 @@ class EventDomainAdapter(
/** v2 read acknowledgement broadcast after `POST /api/session/{id}/view`. */
const val SESSION_VIEWED_EVENT = "session.viewed"

/** v2 `session.moved`: `location.directory` is where the session runs now. */
const val SESSION_MOVED_EVENT = "session.moved"

/** Client-only projection of a v2 agent/model switch for the message store. */
const val MESSAGE_CONTEXT_EVENT = "message.context"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,25 @@ fun OpencodeEvent.namedProjectId(): String? {
fun string(key: String) = (properties[key] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }
return string("projectID") ?: string("projectId")
}

/** A session now runs in [directory] (v2 `session.moved`). */
data class SessionMovedUpdate(
val sessionId: String,
val directory: String,
)

/** The move this event reports, or null for any other event. */
fun OpencodeEvent.sessionMoved(): SessionMovedUpdate? {
if (type != EventDomainAdapter.SESSION_MOVED_EVENT) return null
val properties = rawProperties ?: return null
val sessionId =
sessionId
?: (properties["sessionID"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }
?: return null
val directory =
((properties["location"] as? JsonObject)?.get("directory") as? JsonPrimitive)
?.contentOrNull
?.takeIf { it.isNotBlank() }
?: return null
return SessionMovedUpdate(sessionId = sessionId, directory = directory)
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ data class HomeProject(
val hasManyWorktrees: Boolean
get() = worktrees.size > 1

/** Where a tapped New session starts: the main checkout, else the primary added path. */
val mainCheckoutDirectory: String
get() = worktrees.firstOrNull { it.isMain }?.directory ?: primaryPath

fun worktree(directory: String?): HomeWorktree? {
val canonical = directory?.trim()?.takeIf { it.isNotEmpty() }?.let(ServerPathPolicy::canonical) ?: return null
return worktrees.firstOrNull { it.directory == canonical }
Expand Down Expand Up @@ -183,11 +187,13 @@ sealed class HomeScope {
/**
* Reads a scope id against the current projects. An added path (an older scope, or a
* just-added folder) maps to the project it belongs to, and so does a worktree of a
* project that no longer lists more than one. Null when nothing matches.
* project that no longer lists more than one, or any worktree while [worktreesEnabled]
* is off. Null when nothing matches.
*/
fun resolve(
id: String,
projects: List<HomeProject>,
worktreesEnabled: Boolean = true,
): HomeScope? {
if (id == ALL_ID) return All
projects.firstOrNull { it.key == id }?.let { return Project(it.key) }
Expand All @@ -200,7 +206,7 @@ sealed class HomeScope {
projects.firstOrNull { it.key == projectKey && it.worktree(directory) != null }
?: projects.firstOrNull { it.worktree(directory) != null }
?: return null
return if (project.hasManyWorktrees) Worktree(project.key, directory) else Project(project.key)
return if (worktreesEnabled && project.hasManyWorktrees) Worktree(project.key, directory) else Project(project.key)
}
val canonical = ServerPathPolicy.canonical(id.trim())
projects
Expand All @@ -220,14 +226,16 @@ object HomeSessionLocation {
/**
* Row subtitle parts for a session of a repository project: the project name (All scope
* only), the branch, and the worktree folder when it is not the main checkout or the branch
* is unknown. Null for a non-repository project, which keeps its path subtitle.
* is unknown. Null for a non-repository project, which keeps its path subtitle, and for
* every project while [worktreesEnabled] is off.
*/
fun parts(
project: HomeProject,
sessionDirectory: String?,
includeProjectName: Boolean,
worktreesEnabled: Boolean = true,
): List<Part>? {
if (!project.isRepository) return null
if (!worktreesEnabled || !project.isRepository) return null
val directory =
sessionDirectory?.trim()?.takeIf { it.isNotEmpty() }?.let(ServerPathPolicy::canonical)
?: ServerPathPolicy.canonical(project.primaryPath)
Expand All @@ -248,6 +256,13 @@ object HomeSessionLocation {
object HomeWorktreeCopy {
const val MAIN_CHECKOUT = "main checkout"
const val RUN_IN = "Run in"
const val OTHER_PROJECTS = "Other projects"
const val SHOW_FEWER = "Show fewer"
const val EDIT = "Edit"
const val DONE = "Done"
const val REORDER_NOTE = "Drag to reorder. Worktrees stay with their project."

fun showAll(count: Int): String = "Show all $count"

fun worktreeCount(count: Int): String = "$count worktrees"

Expand All @@ -267,3 +282,67 @@ object HomeWorktreeCopy {
return if (worktree.isMain) branch else "$branch${HomeSessionLocation.SEPARATOR}${worktree.folderName}"
}
}

/**
* Expand and edit state of the project picker: at most one project shows its worktrees, a
* project with more than [COLLAPSED_WORKTREE_LIMIT] shows the rest on request, and Edit
* collapses everything while projects reorder.
*/
data class HomeProjectPickerState(
val expandedProjectKey: String? = null,
val showAllProjectKeys: Set<String> = emptySet(),
val isEditing: Boolean = false,
) {
/** Opens [key] and closes any other; the open one closes. */
fun toggleExpanded(key: String): HomeProjectPickerState = copy(expandedProjectKey = if (expandedProjectKey == key) null else key)

fun toggleShowAll(key: String): HomeProjectPickerState =
copy(showAllProjectKeys = if (key in showAllProjectKeys) showAllProjectKeys - key else showAllProjectKeys + key)

/** Edit starts and ends collapsed. */
fun setEditing(editing: Boolean): HomeProjectPickerState =
HomeProjectPickerState(expandedProjectKey = null, showAllProjectKeys = emptySet(), isEditing = editing)

fun isExpanded(key: String): Boolean = !isEditing && expandedProjectKey == key

/** Worktrees listed under project [key] while it is expanded: all, or the first few. */
fun <T> visibleWorktrees(
key: String,
worktrees: List<T>,
): List<T> =
if (worktrees.size <= COLLAPSED_WORKTREE_LIMIT || key in showAllProjectKeys) {
worktrees
} else {
worktrees.take(COLLAPSED_WORKTREE_LIMIT)
}

/** "Show all N" / "Show fewer" under expanded project [key] with more than the limit; null otherwise. */
fun showAllLabel(
key: String,
worktreeCount: Int,
): String? {
if (worktreeCount <= COLLAPSED_WORKTREE_LIMIT) return null
return if (key in showAllProjectKeys) HomeWorktreeCopy.SHOW_FEWER else HomeWorktreeCopy.showAll(worktreeCount)
}

companion object {
const val COLLAPSED_WORKTREE_LIMIT = 5

/**
* State each time the picker opens: a worktree scope starts with its project expanded,
* showing all when that worktree is past the first few. Anything else starts collapsed.
*/
fun initial(
selectedScope: HomeScope?,
projects: List<HomeProject>,
): HomeProjectPickerState {
val worktreeScope = selectedScope as? HomeScope.Worktree ?: return HomeProjectPickerState()
val project = projects.firstOrNull { it.key == worktreeScope.projectKey } ?: return HomeProjectPickerState()
val index = project.worktrees.indexOfFirst { it.directory == ServerPathPolicy.canonical(worktreeScope.directory) }
return HomeProjectPickerState(
expandedProjectKey = project.key,
showAllProjectKeys = if (index >= COLLAPSED_WORKTREE_LIMIT) setOf(project.key) else emptySet(),
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package dev.opencode.mobile.domain.home

import dev.opencode.mobile.domain.filesystem.ServerPathPolicy
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
import javax.inject.Singleton

/**
* The Home projects (with their worktrees in Home order) as Home last grouped them, so other
* screens can name a session's project and worktrees without regrouping. Home publishes;
* readers treat an empty list as unknown.
*/
@Singleton
class HomeProjectsSnapshot
@Inject
constructor() {
private val _projects = MutableStateFlow<List<HomeProject>>(emptyList())
val projects: StateFlow<List<HomeProject>> = _projects.asStateFlow()

fun publish(projects: List<HomeProject>) {
_projects.value = projects
}

/** The project whose worktrees (or added paths) include [directory]. */
fun projectContaining(directory: String?): HomeProject? {
val canonical = directory?.trim()?.takeIf { it.isNotEmpty() }?.let(ServerPathPolicy::canonical) ?: return null
return _projects.value.firstOrNull { it.worktree(canonical) != null }
?: _projects.value.firstOrNull { it.contains(canonical) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ object ProductAnalytics {
const val CHAT_OVERFLOW_RENAME = "chat_overflow_rename"
const val CHAT_OVERFLOW_REVIEW_CHANGES = "chat_overflow_review_changes"
const val CHAT_OVERFLOW_FORK = "chat_overflow_fork"
const val CHAT_OVERFLOW_MOVE_TO_WORKTREE = "chat_overflow_move_to_worktree"
const val CHAT_OVERFLOW_BROWSE_FILES = "chat_overflow_browse_files"
const val CHAT_OVERFLOW_SESSION_CONTEXT = "chat_overflow_session_context"
const val CHAT_OVERFLOW_COPY_SESSION_ID = "chat_overflow_copy_session_id"
Expand Down Expand Up @@ -302,6 +303,7 @@ object ProductAnalytics {
const val SETTINGS_OPEN_THEME_PICKER = "settings_open_theme_picker"
const val SETTINGS_OPEN_SYNTAX_PICKER = "settings_open_syntax_picker"
const val SETTINGS_TOGGLE_HIDE_USER_DIRECTORY = "settings_toggle_hide_user_directory"
const val SETTINGS_TOGGLE_WORKTREES = "settings_toggle_worktrees"
const val SETTINGS_OPEN_RECENT_WINDOW_PICKER = "settings_open_recent_window_picker"
const val SETTINGS_TOGGLE_COLLAPSE_CONSECUTIVE_TOOL_CALLS = "settings_toggle_collapse_consecutive_tool_calls"
const val SETTINGS_TOGGLE_CHIP_TIMELINE = "settings_toggle_chip_timeline"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ object HomeDisplayPreferences {
private const val KEY_RECENT_WINDOW_HOURS = "recent_window_hours"
private const val KEY_LAST_HOME_HIDDEN_AT_EPOCH_MS = "last_home_hidden_at_epoch_ms"
private const val KEY_SESSION_LIST_PROJECT_PICKER_ENABLED = "session_list_project_picker_enabled"
private const val KEY_SHOWS_WORKTREES = "shows_worktrees"

/** When true, replace remote `/Users/…` or `/home/…` with `~` in path labels. */
var hideUserDirectoryPrefix: Boolean by mutableStateOf(true)
Expand All @@ -22,6 +23,13 @@ object HomeDisplayPreferences {
var recentWindowHours: Int by mutableIntStateOf(HomeSessionLadder.DEFAULT_WINDOW_HOURS)
private set

/**
* When true, Home shows each project's worktrees and branches, and holding New session can
* pick a worktree. Off changes presentation only: sessions of every worktree stay listed.
*/
var showsWorktrees: Boolean by mutableStateOf(true)
private set

private var appContext: Context? = null

fun initialize(context: Context) {
Expand All @@ -37,6 +45,12 @@ object HomeDisplayPreferences {
HomeSessionLadder.sanitizeWindowHours(
prefs.getInt(KEY_RECENT_WINDOW_HOURS, HomeSessionLadder.DEFAULT_WINDOW_HOURS),
)
showsWorktrees = prefs.getBoolean(KEY_SHOWS_WORKTREES, true)
}

fun updateShowsWorktrees(value: Boolean) {
showsWorktrees = value
prefs()?.edit()?.putBoolean(KEY_SHOWS_WORKTREES, value)?.apply()
}

fun updateHideUserDirectoryPrefix(value: Boolean) {
Expand Down Expand Up @@ -74,8 +88,10 @@ object HomeDisplayPreferences {
?.remove(KEY_RECENT_WINDOW_HOURS)
?.remove(KEY_LAST_HOME_HIDDEN_AT_EPOCH_MS)
?.remove(KEY_SESSION_LIST_PROJECT_PICKER_ENABLED)
?.remove(KEY_SHOWS_WORKTREES)
?.apply()
hideUserDirectoryPrefix = true
showsWorktrees = true
recentWindowHours = HomeSessionLadder.DEFAULT_WINDOW_HOURS
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ class DefaultSessionRepository
runCatching { remote.forkSession(id, atMessageId, directory) }
.getOrElse { throw adapter.mapError(it) }

override suspend fun moveSession(
id: String,
directory: String,
) = runCatching { remote.moveSession(id, directory) }
.getOrElse { throw adapter.mapError(it) }

override suspend fun abortSession(
id: String,
directory: String?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ internal class ProtocolSelectedSessionRemote(
directory: String?,
): Session = selected().forkSession(id, atMessageId, directory)

override suspend fun moveSession(
id: String,
directory: String,
) = selected().moveSession(id, directory)

override suspend fun abortSession(
id: String,
directory: String?,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ interface SessionRepository {
directory: String? = null,
): Session

/**
* Moves session [id] to the worktree [directory]. v2 only: callers gate on
* `supportsSessionMove`; other servers throw.
*/
suspend fun moveSession(
id: String,
directory: String,
): Unit = throw SessionError.Http(404, SESSION_MOVE_UNAVAILABLE)

suspend fun abortSession(
id: String,
directory: String? = null,
Expand Down Expand Up @@ -212,3 +221,5 @@ enum class CompactionStart {
/** The server only enqueued compaction; it completes later, live. */
Enqueued,
}

internal const val SESSION_MOVE_UNAVAILABLE = "session move is not available"
Loading