Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import dev.opencode.mobile.data.remote.dto.V2FormReplyRequestDto
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.V2PermissionReplyRequestDto
import dev.opencode.mobile.data.remote.dto.V2PermissionRequestDto
import dev.opencode.mobile.data.remote.dto.V2RenameSessionRequestDto
Expand Down Expand Up @@ -427,9 +428,21 @@ class SessionsApi private constructor(

// --- V2 home / session CRUD ---

suspend fun locationForSessionList(directory: String): V2LocationInfoDto =
httpClient
.get()
.get("api/location") {
applyLocationDirectory(directory)
}.body()

/**
* [projectId] lists every worktree of that project. Passing [directory] as well would
* hide those worktree sessions, so a project list omits the directory query.
*/
suspend fun listSessionsV2(
directory: String? = null,
parentId: String? = null,
projectId: String? = null,
): List<V2SessionDto> {
val sessions = mutableListOf<V2SessionDto>()
var cursor: String? = null
Expand All @@ -439,7 +452,11 @@ class SessionsApi private constructor(
httpClient
.get()
.get("api/session") {
applyDirectory(directory)
if (projectId != null) {
parameter("project", projectId)
} else {
applyDirectory(directory)
}
parentId?.let { parameter("parentID", it) }
cursor?.let { parameter("cursor", it) }
}.body<ApiListEnvelope<V2SessionDto>>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ class SessionDomainAdapter {
isReady = isReady,
statusStale = statusStale,
unreadOutcome = unreadOutcome,
directory = session.directory,
)

fun toSessionStatus(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ data class SessionSummary(
val statusStale: Boolean = false,
/** v2 only: outcome of an unread finished run; null when read, running, or on v1. */
val unreadOutcome: SessionIdleOutcome? = null,
/** Directory the session runs in. Null when the row should use the added project path. */
val directory: String? = null,
)

data class SessionStatus(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dev.opencode.mobile.domain.session

import dev.opencode.mobile.data.remote.SessionsApi
import dev.opencode.mobile.data.remote.dto.V2FormReplyRequestDto
import dev.opencode.mobile.data.remote.dto.V2LocationInfoDto
import dev.opencode.mobile.data.remote.dto.V2PermissionReplyRequestDto

internal class V2SessionRemote(
Expand All @@ -14,7 +15,17 @@ internal class V2SessionRemote(
override suspend fun listPendingQuestions(directory: String?): List<QuestionRequest> =
api.listPendingFormsV2(directory).map(adapter::toQuestionRequest)

override suspend fun listSessions(directory: String?): List<Session> = api.listSessionsV2(directory).map(adapter::toSession)
override suspend fun listSessions(directory: String?): List<Session> {
val projectId =
directory?.let { path ->
runCatching { listableProjectId(api.locationForSessionList(path)) }.getOrNull()
}
return api
.listSessionsV2(
directory = if (projectId == null) directory else null,
projectId = projectId,
).map(adapter::toSession)
}

override suspend fun createSession(
parentId: String?,
Expand Down Expand Up @@ -216,3 +227,13 @@ internal class V2SessionRemote(
api.viewSessionV2(sessionId, idleAtEpochMs)
}
}

/** Project id to list, or null when the directory should stay a directory-scoped list. */
internal fun listableProjectId(location: V2LocationInfoDto): String? {
val project = location.project ?: return null
val id = project.id?.takeIf { it.isNotBlank() } ?: return null
val root = project.canonical ?: project.directory
// Non-git directories resolve to the global "/" project, which is not this folder's sessions.
if (root.isNullOrBlank() || root == "/") return null
return id
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ data class SessionListSession(
val retryAttempt: Int? = null,
/** Cached activity that has not been confirmed by REST yet. */
val statusStale: Boolean = false,
/**
* Directory the session runs in. [worktree] stays the added project path so project
* filters and counts keep grouping worktree sessions with that project.
*/
val directory: String = worktree,
)

data class SessionListFilterTab(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ fun MainScreen(
viewModel.onSessionLongPress(
sessionId = session.id,
title = session.title,
worktree = session.worktree,
worktree = session.directory,
)
},
onDismissSheet = viewModel::dismissSessionActionsSheet,
Expand Down Expand Up @@ -778,7 +778,7 @@ private fun HomeProjectsContent(
SessionOpenTarget(
sessionId = session.id,
title = session.title,
worktree = session.worktree,
worktree = session.directory,
),
)
}
Expand Down Expand Up @@ -963,6 +963,7 @@ internal fun List<ProjectSectionUi>.toCrossProjectSessionListSessions(): List<Se
letter = section.letter,
letterAccent = section.letterAccent,
subtitle = section.pathSubtitle,
directory = session.directory?.takeIf { it.isNotEmpty() } ?: section.worktree,
status = session.toSessionListStatus(),
caption = session.updatedAtEpochMs?.let(RelativeTimeFormatting::format).orEmpty(),
updatedAtEpochMs = session.updatedAtEpochMs,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,43 +56,62 @@ class SessionProtocolRepositoryTest {
}

@Test
fun v2ListSessions_unwrapsEnvelopeAndKeepsDirectoryQuery() =
fun v2ListSessions_includesWorktreeSessionsOfTheSameProject() =
runTest {
val requests = mutableListOf<HttpRequestData>()
val client =
testClient { request ->
requests += request
respondJson(
"""
{
"data":[{
"id":"ses_2",
"title":"Two",
"projectID":"proj",
"cost":0,
"tokens":{"input":1,"output":2,"reasoning":0,"cache":{"read":0,"write":0}},
"time":{"created":1,"updated":2},
"location":{"directory":"/repo"}
}],
"cursor":{"previous":null,"next":null}
}
""".trimIndent(),
)
val path = request.url.encodedPath
when {
path.endsWith("/api/location") ->
respondJson(
"""{"directory":"/repo","project":{"id":"proj","directory":"/repo","canonical":"/repo"}}""",
)
else ->
respondJson(
"""
{
"data":[
{
"id":"ses_worktree",
"title":"Add project sheet prototype",
"projectID":"proj",
"cost":0,
"tokens":{"input":0,"output":0,"reasoning":0,"cache":{"read":0,"write":0}},
"time":{"created":3,"updated":9},
"location":{"directory":"/worktrees/add-project-browse"}
},
{
"id":"ses_root",
"title":"Two",
"projectID":"proj",
"cost":0,
"tokens":{"input":1,"output":2,"reasoning":0,"cache":{"read":0,"write":0}},
"time":{"created":1,"updated":2},
"location":{"directory":"/repo"}
}
],
"cursor":{"previous":null,"next":null}
}
""".trimIndent(),
)
}
}
val manager = manager(ServerProtocol.V2)
val repository = DefaultSessionRepository(SessionsApi(client, json), SessionDomainAdapter(), activeConnectionManager = manager)
val repository =
DefaultSessionRepository(
SessionsApi(client, json),
SessionDomainAdapter(),
activeConnectionManager = manager(ServerProtocol.V2),
)

val sessions = repository.listSessions("/repo")

assertEquals("ses_2", sessions.single().id)
assertEquals("/repo", sessions.single().directory)
assertEquals("/repo", requests.single().url.parameters["directory"])
assertTrue(
requests
.single()
.url.encodedPath
.contains("/api/session"),
)
assertEquals(listOf("ses_worktree", "ses_root"), sessions.map { it.id })
assertEquals("/worktrees/add-project-browse", sessions.first().directory)
val listed = requests.first { it.url.encodedPath.contains("/api/session") }
assertEquals("proj", listed.url.parameters["project"])
assertNull(listed.url.parameters["directory"])
}

@Test
Expand Down Expand Up @@ -343,7 +362,13 @@ class SessionProtocolRepositoryTest {
val client =
testClient { request ->
requests += request
respondJson(pages.removeFirst())
if (request.url.encodedPath.endsWith("/api/location")) {
respondJson(
"""{"directory":"/repo","project":{"id":"p","directory":"/repo","canonical":"/repo"}}""",
)
} else {
respondJson(pages.removeFirst())
}
}
val repository =
DefaultSessionRepository(
Expand All @@ -354,10 +379,12 @@ class SessionProtocolRepositoryTest {

val sessions = repository.listSessions("/repo")

val listed = requests.filter { it.url.encodedPath.contains("/api/session") }
assertEquals(listOf("ses_a", "ses_b"), sessions.map { it.id })
assertEquals(2, requests.size)
assertEquals(null, requests[0].url.parameters["cursor"])
assertEquals("page-2", requests[1].url.parameters["cursor"])
assertEquals(2, listed.size)
assertEquals(null, listed[0].url.parameters["cursor"])
assertEquals("page-2", listed[1].url.parameters["cursor"])
assertEquals("p", listed[0].url.parameters["project"])
}

@Test
Expand All @@ -384,10 +411,7 @@ class SessionProtocolRepositoryTest {
assertEquals("ses_2", sessions.single().id)
assertEquals(ServerProtocol.V2, manager.currentProtocol())
assertTrue(
requests
.single()
.url.encodedPath
.contains("/api/session"),
requests.any { it.url.encodedPath.contains("/api/session") },
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,25 @@ class CrossProjectSessionListSessionsTest {
assertEquals(30L, newerFirst.single().updatedAtEpochMs)
}

@Test
fun worktreeSession_staysInAddedProjectButOpensItsOwnDirectory() {
val sessions =
listOf(
section(
worktree = "/repo",
session(
id = "ses_worktree",
title = "Add project sheet prototype",
updatedAtEpochMs = 20L,
directory = "/worktrees/add-project-browse",
),
),
).toCrossProjectSessionListSessions()

assertEquals("/repo", sessions.single().worktree)
assertEquals("/worktrees/add-project-browse", sessions.single().directory)
}

@Test
fun projectCounts_followTheWinningWorktree() {
val sections =
Expand Down Expand Up @@ -132,10 +151,12 @@ class CrossProjectSessionListSessionsTest {
id: String,
title: String,
updatedAtEpochMs: Long?,
directory: String? = null,
): SessionSummary =
SessionSummary(
id = id,
title = title,
updatedAtEpochMs = updatedAtEpochMs,
directory = directory,
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ struct SessionListSession: Identifiable, Hashable {
let statusIsStale: Bool
let caption: String
let updatedAtEpochMs: Int64?
/// Directory the session runs in. `worktree` stays the added project path for filters and counts.
let directory: String

init(
id: String,
Expand All @@ -80,7 +82,8 @@ struct SessionListSession: Identifiable, Hashable {
status: SessionListStatus,
statusIsStale: Bool = false,
caption: String,
updatedAtEpochMs: Int64? = nil
updatedAtEpochMs: Int64? = nil,
directory: String? = nil
) {
self.id = id
self.title = title
Expand All @@ -92,6 +95,7 @@ struct SessionListSession: Identifiable, Hashable {
self.statusIsStale = statusIsStale
self.caption = caption
self.updatedAtEpochMs = updatedAtEpochMs
self.directory = directory ?? worktree
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,16 @@ nonisolated struct SessionsAPIClient: Sendable {

// MARK: - V2 home / session CRUD

func listSessionsV2(directory: String? = nil, parentID: String? = nil) async throws -> [V2SessionDTO] {
func locationForSessionList(directory: String) async throws -> V2LocationInfoDTO {
try await get(path: "api/location", locationDirectory: directory)
}

/// `projectID` lists every worktree of that project. Passing `directory` as well would hide those sessions.
func listSessionsV2(
directory: String? = nil,
parentID: String? = nil,
projectID: String? = nil
) async throws -> [V2SessionDTO] {
var sessions: [V2SessionDTO] = []
var cursor: String?
var pages = 0
Expand All @@ -267,12 +276,15 @@ nonisolated struct SessionsAPIClient: Sendable {
if let parentID {
query["parentID"] = parentID
}
if let projectID {
query["project"] = projectID
}
if let cursor {
query["cursor"] = cursor
}
let envelope: APIListEnvelope<V2SessionDTO> = try await get(
path: "api/session",
directory: directory,
directory: projectID == nil ? directory : nil,
query: query
)
sessions.append(contentsOf: envelope.data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ nonisolated struct SessionDomainAdapter: Sendable {
isReady: isReady,
unreadOutcome: unreadOutcome,
statusIsStale: statusIsStale,
parentID: session.parentID
parentID: session.parentID,
directory: session.directory
)
}

Expand Down
Loading