GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — #752 Create worktrees from the apps (#788) · opencode-mobile/opencode-mobile@4dde2cd

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • android/app/src
    • main/java/dev/opencode/mobile
      • data/remote
        • WorktreesApi.kt
      • domain
        • home
          • HomeProjects.kt
          • HomeProjectsSnapshot.kt
        • worktree
          • DefaultWorktreeRepository.kt
          • WorktreeCreate.kt
          • WorktreeRepository.kt
      • ui
        • main
          • MainScreen.kt
          • MainScreenViewModel.kt
          • SessionListHomeChrome.kt
        • sessionchat
          • SessionChatScreen.kt
          • SessionChatViewModel.kt
          • region
            • SessionChatWorktreeMove.kt
        • worktree
          • NewWorktreeAvailability.kt
          • WorktreeCreateForm.kt
          • WorktreeCreateFormContent.kt
    • test/java/dev/opencode/mobile
      • data/remote
        • WorktreesApiTest.kt
      • domain/worktree
        • DefaultWorktreeRepositoryTest.kt
      • ui
        • main
          • MainScreenViewModelTest.kt
          • SessionListHomeChromeTest.kt
        • sessionchat
          • SessionChatViewModelTest.kt
          • region
            • SessionChatWorktreeMoveTest.kt
        • worktree
          • NewWorktreeAvailabilityTest.kt
          • WorktreeCreateFormTest.kt
  • ios/OpenCode Mobile
    • OpenCode MobileTests
      • Data/Remote
        • WorktreesAPIClientCreateTests.swift
      • Domain/Session
        • SessionMoveTests.swift
      • UI
        • Main
          • HomeWorktreeMarksTests.swift
          • ProjectListHomeViewModelTests.swift
          • SessionListHomeChromeTests.swift
        • SessionChat
          • SessionChatViewModelTests.swift
        • Worktree
          • WorktreeCreateModelTests.swift
    • OpenCode Mobile
      • Data/Remote
        • WorktreesAPIClient.swift
      • Domain
        • Session
          • ServerErrorMessage.swift
        • Worktree
          • DefaultWorktreeRepository.swift
          • WorktreeCreateCopy.swift
          • WorktreeRepository.swift
      • UI
        • Main
          • HomeProjectsEnvironment.swift
          • ProjectListHomeView.swift
          • ProjectListHomeViewModel.swift
          • SessionListHomeChrome.swift
        • SessionChat
          • SessionChatMoveToWorktree.swift
          • SessionChatView.swift
          • SessionChatViewModel.swift
        • Worktree
          • WorktreeCreateForm.swift
          • WorktreeCreateModel.swift

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Dismiss banner
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎android/app/src/main/java/dev/opencode/mobile/data/remote/WorktreesApi.kt‎

Copy file name to clipboardExpand all lines: android/app/src/main/java/dev/opencode/mobile/data/remote/WorktreesApi.kt
+114Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,26 @@ package dev.opencode.mobile.data.remote
22

33
import dev.opencode.mobile.network.OpencodeHttpClient
44
import dev.opencode.mobile.network.applyDirectory
5+
import dev.opencode.mobile.network.applyLocationDirectory
56
import io.ktor.client.HttpClient
67
import io.ktor.client.call.body
78
import io.ktor.client.request.get
89
import io.ktor.client.request.parameter
910
import io.ktor.client.request.post
1011
import io.ktor.client.request.setBody
12+
import io.ktor.client.statement.HttpResponse
1113
import io.ktor.client.statement.bodyAsText
1214
import io.ktor.http.ContentType
1315
import io.ktor.http.contentType
1416
import io.ktor.http.isSuccess
1517
import kotlinx.serialization.Serializable
18+
import kotlinx.serialization.json.Json
19+
import kotlinx.serialization.json.JsonArray
20+
import kotlinx.serialization.json.JsonElement
21+
import kotlinx.serialization.json.JsonObject
22+
import kotlinx.serialization.json.JsonPrimitive
1623
import kotlinx.serialization.json.buildJsonObject
24+
import kotlinx.serialization.json.contentOrNull
1725
import kotlinx.serialization.json.put
1826

1927
@Serializable
@@ -35,13 +43,53 @@ sealed class V1WorktreeHttp {
3543
) : V1WorktreeHttp()
3644
}
3745

46+
/** A worktree route answered outside 2xx; [body] is the raw error body. */
47+
class WorktreeHttpException(
48+
val statusCode: Int,
49+
val body: String,
50+
) : Exception("worktree request failed with status $statusCode")
51+
52+
/** V1 `POST /experimental/worktree` answer; the server may have changed the name (slug, suffix). */
53+
data class V1CreatedWorktree(
54+
val name: String,
55+
val branch: String?,
56+
val directory: String,
57+
)
58+
59+
@Serializable
60+
internal data class V1CreatedWorktreeDto(
61+
val name: String = "",
62+
val branch: String? = null,
63+
val directory: String,
64+
)
65+
3866
interface WorktreeRemote {
3967
suspend fun listV2(projectId: String): List<String>
4068

4169
suspend fun refreshV2(projectId: String)
4270

4371
/** The sandboxes (extra git worktrees) of [directory]'s project; never the main checkout. */
4472
suspend fun listV1(directory: String): V1WorktreeHttp
73+
74+
/**
75+
* V2 `POST /api/worktree` with `projectID`, `from`, `name`, and `branch` only when given.
76+
* Returns the new checkout's directory. Throws [WorktreeHttpException] outside 2xx.
77+
*/
78+
suspend fun createV2(
79+
projectId: String,
80+
from: String,
81+
name: String,
82+
branch: String?,
83+
): String
84+
85+
/** V1 `POST /experimental/worktree?directory=` with `{"name"}`. Throws [WorktreeHttpException] outside 2xx. */
86+
suspend fun createV1(
87+
directory: String,
88+
name: String,
89+
): V1CreatedWorktree
90+
91+
/** V2 `GET /api/vcs/branch` at [directory]: local and remote branch names. */
92+
suspend fun branchesV2(directory: String): List<String>
4593
}
4694

4795
class WorktreesApi private constructor(
@@ -82,7 +130,73 @@ class WorktreesApi private constructor(
82130
}
83131
}
84132

133+
override suspend fun createV2(
134+
projectId: String,
135+
from: String,
136+
name: String,
137+
branch: String?,
138+
): String {
139+
val response =
140+
httpClient.get().post("api/worktree") {
141+
contentType(ContentType.Application.Json)
142+
setBody(
143+
buildJsonObject {
144+
put("projectID", projectId)
145+
put("from", from)
146+
put("name", name)
147+
branch?.let { put("branch", it) }
148+
}.toString(),
149+
)
150+
}
151+
return lenientJson.decodeFromString<WorktreeDirectoryDto>(response.successText()).directory
152+
}
153+
154+
override suspend fun createV1(
155+
directory: String,
156+
name: String,
157+
): V1CreatedWorktree {
158+
val response =
159+
httpClient.get().post("experimental/worktree") {
160+
applyDirectory(directory)
161+
contentType(ContentType.Application.Json)
162+
setBody(buildJsonObject { put("name", name) }.toString())
163+
}
164+
val dto = lenientJson.decodeFromString<V1CreatedWorktreeDto>(response.successText())
165+
return V1CreatedWorktree(name = dto.name, branch = dto.branch?.takeIf { it.isNotBlank() }, directory = dto.directory)
166+
}
167+
168+
override suspend fun branchesV2(directory: String): List<String> {
169+
val response =
170+
httpClient.get().get("api/vcs/branch") {
171+
applyLocationDirectory(directory)
172+
}
173+
val root = lenientJson.parseToJsonElement(response.successText())
174+
// A location response (`{"location":…,"data":[…]}`), or a bare array.
175+
val list =
176+
when (root) {
177+
is JsonArray -> root
178+
is JsonObject -> root["data"] as? JsonArray
179+
else -> null
180+
} ?: error("unrecognized branch list")
181+
return list.mapNotNull(JsonElement::branchName).distinct()
182+
}
183+
184+
private suspend fun HttpResponse.successText(): String {
185+
val text = bodyAsText()
186+
if (!status.isSuccess()) throw WorktreeHttpException(status.value, text)
187+
return text
188+
}
189+
85190
private fun interface ClientProvider {
86191
fun get(): HttpClient
87192
}
88193
}
194+
195+
private val lenientJson = Json { ignoreUnknownKeys = true }
196+
197+
private fun JsonElement.branchName(): String? =
198+
(this as? JsonPrimitive)
199+
?.takeIf { it.isString }
200+
?.contentOrNull
201+
?.trim()
202+
?.takeIf { it.isNotEmpty() }
Collapse file

‎android/app/src/main/java/dev/opencode/mobile/domain/home/HomeProjects.kt‎

Copy file name to clipboardExpand all lines: android/app/src/main/java/dev/opencode/mobile/domain/home/HomeProjects.kt
+6Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,11 @@ data class HomeProject(
5050
val isRepository: Boolean,
5151
/** Main checkout first, then by folder name. */
5252
val worktrees: List<HomeWorktree>,
53+
/**
54+
* The server reports version control for the path even when the project does not merge
55+
* (a git repository without a commit resolves to `global`).
56+
*/
57+
val hasVcs: Boolean = isRepository,
5358
) {
5459
/** Location for project-level requests. */
5560
val primaryPath: String
@@ -112,6 +117,7 @@ object HomeProjectGrouping {
112117
memberPaths = members,
113118
isRepository = isRepository,
114119
worktrees = worktrees,
120+
hasVcs = isRepository || resolution?.isRepository == true,
115121
)
116122
}
117123
}
Collapse file

‎android/app/src/main/java/dev/opencode/mobile/domain/home/HomeProjectsSnapshot.kt‎

Copy file name to clipboardExpand all lines: android/app/src/main/java/dev/opencode/mobile/domain/home/HomeProjectsSnapshot.kt
+13Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package dev.opencode.mobile.domain.home
22

33
import dev.opencode.mobile.domain.filesystem.ServerPathPolicy
4+
import kotlinx.coroutines.flow.MutableSharedFlow
45
import kotlinx.coroutines.flow.MutableStateFlow
6+
import kotlinx.coroutines.flow.SharedFlow
57
import kotlinx.coroutines.flow.StateFlow
8+
import kotlinx.coroutines.flow.asSharedFlow
69
import kotlinx.coroutines.flow.asStateFlow
710
import javax.inject.Inject
811
import javax.inject.Singleton
@@ -19,10 +22,20 @@ class HomeProjectsSnapshot
1922
private val _projects = MutableStateFlow<List<HomeProject>>(emptyList())
2023
val projects: StateFlow<List<HomeProject>> = _projects.asStateFlow()
2124

25+
private val _worktreeRefreshRequests = MutableSharedFlow<String>(extraBufferCapacity = 8)
26+
27+
/** Directories whose project's worktrees changed elsewhere (a checkout created in Session Chat). */
28+
val worktreeRefreshRequests: SharedFlow<String> = _worktreeRefreshRequests.asSharedFlow()
29+
2230
fun publish(projects: List<HomeProject>) {
2331
_projects.value = projects
2432
}
2533

34+
/** Asks Home to list the worktrees of [directory]'s project again. */
35+
fun requestWorktreeRefresh(directory: String) {
36+
_worktreeRefreshRequests.tryEmit(directory)
37+
}
38+
2639
/** The project whose worktrees (or added paths) include [directory]. */
2740
fun projectContaining(directory: String?): HomeProject? {
2841
val canonical = directory?.trim()?.takeIf { it.isNotEmpty() }?.let(ServerPathPolicy::canonical) ?: return null
Collapse file

‎android/app/src/main/java/dev/opencode/mobile/domain/worktree/DefaultWorktreeRepository.kt‎

Copy file name to clipboardExpand all lines: android/app/src/main/java/dev/opencode/mobile/domain/worktree/DefaultWorktreeRepository.kt
+86Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
package dev.opencode.mobile.domain.worktree
22

33
import dev.opencode.mobile.data.remote.V1WorktreeHttp
4+
import dev.opencode.mobile.data.remote.WorktreeHttpException
45
import dev.opencode.mobile.data.remote.WorktreeRemote
56
import dev.opencode.mobile.domain.connection.ServerProtocol
7+
import dev.opencode.mobile.domain.filesystem.ServerPathPolicy
8+
import dev.opencode.mobile.domain.session.ServerErrorMessage
69
import dev.opencode.mobile.network.ActiveConnectionManager
710
import kotlinx.coroutines.CancellationException
11+
import kotlinx.coroutines.flow.MutableStateFlow
12+
import kotlinx.coroutines.flow.StateFlow
13+
import kotlinx.coroutines.flow.asStateFlow
814
import javax.inject.Inject
915

1016
class DefaultWorktreeRepository(
@@ -22,6 +28,8 @@ class DefaultWorktreeRepository(
2228

2329
private var connectionKey: String? = null
2430
private var v1StoppedKey: String? = null
31+
private val _canCreate = MutableStateFlow(true)
32+
override val canCreate: StateFlow<Boolean> = _canCreate.asStateFlow()
2533

2634
override suspend fun load(
2735
addedPath: String,
@@ -67,15 +75,84 @@ class DefaultWorktreeRepository(
6775
override fun onDisconnected() {
6876
connectionKey = null
6977
v1StoppedKey = null
78+
_canCreate.value = true
7079
}
7180

7281
override fun onConnection(key: String) {
7382
if (connectionKey != key) {
7483
v1StoppedKey = null
7584
connectionKey = key
85+
_canCreate.value = true
7686
}
7787
}
7888

89+
override suspend fun create(request: CreateWorktreeRequest): CreatedWorktree =
90+
when (protocol()) {
91+
ServerProtocol.V2 -> createV2(request)
92+
ServerProtocol.V1 -> createV1(request)
93+
}
94+
95+
override suspend fun baseBranches(directory: String): List<String> =
96+
when (protocol()) {
97+
ServerProtocol.V2 -> remote.branchesV2(directory)
98+
ServerProtocol.V1 -> emptyList()
99+
}
100+
101+
private suspend fun createV2(request: CreateWorktreeRequest): CreatedWorktree {
102+
val projectId = request.projectId?.trim()?.takeIf { it.isNotEmpty() } ?: throw WorktreeCreateError(WorktreeCreateCopy.NOT_GIT)
103+
val directory =
104+
createCall(notFoundMeansUnsupported = false) {
105+
remote.createV2(
106+
projectId = projectId,
107+
from = request.sourceDirectory,
108+
name = request.name,
109+
branch = request.baseRef?.takeIf { it.isNotBlank() },
110+
)
111+
}
112+
val canonical = ServerPathPolicy.canonical(directory.trim())
113+
return CreatedWorktree(
114+
directory = canonical,
115+
name = ServerPathPolicy.name(canonical).ifBlank { request.name },
116+
branch = null,
117+
)
118+
}
119+
120+
private suspend fun createV1(request: CreateWorktreeRequest): CreatedWorktree {
121+
val created =
122+
try {
123+
createCall(notFoundMeansUnsupported = true) { remote.createV1(request.sourceDirectory, request.name) }
124+
} catch (_: V1CreateNotFound) {
125+
_canCreate.value = false
126+
throw WorktreeCreateError(WorktreeCreateCopy.UNSUPPORTED)
127+
}
128+
val canonical = ServerPathPolicy.canonical(created.directory.trim())
129+
return CreatedWorktree(
130+
directory = canonical,
131+
name = created.name.trim().ifEmpty { ServerPathPolicy.name(canonical).ifBlank { request.name } },
132+
branch = created.branch?.trim()?.takeIf { it.isNotEmpty() },
133+
)
134+
}
135+
136+
/** Runs a create call and turns its failure into [WorktreeCreateError] (a v1 404 into [V1CreateNotFound]). */
137+
private suspend fun <T> createCall(
138+
notFoundMeansUnsupported: Boolean,
139+
call: suspend () -> T,
140+
): T =
141+
try {
142+
call()
143+
} catch (cancellation: CancellationException) {
144+
throw cancellation
145+
} catch (error: WorktreeCreateError) {
146+
throw error
147+
} catch (error: WorktreeHttpException) {
148+
if (error.statusCode == 404 && notFoundMeansUnsupported) throw V1CreateNotFound()
149+
throw WorktreeCreateError(httpErrorMessage(error.statusCode, error.body))
150+
} catch (error: Exception) {
151+
throw WorktreeCreateError(error.message?.trim()?.takeIf { it.isNotEmpty() } ?: "Unknown error")
152+
}
153+
154+
private class V1CreateNotFound : Exception()
155+
79156
private suspend fun loadV2(projectId: String?): WorktreeLoad {
80157
if (projectId.isNullOrBlank()) return WorktreeLoad.Unloaded
81158
return try {
@@ -120,3 +197,12 @@ class DefaultWorktreeRepository(
120197
V1WorktreeHttp.Failed(-1)
121198
}
122199
}
200+
201+
/** The server's own message, else the trimmed raw body, else the HTTP status. */
202+
internal fun httpErrorMessage(
203+
statusCode: Int,
204+
body: String,
205+
): String =
206+
ServerErrorMessage.userFacing(body)
207+
?: body.trim().takeIf { it.isNotEmpty() && !it.startsWith("{") && !it.startsWith("[") && it.length <= 200 && !it.contains('\n') }
208+
?: WorktreeCreateCopy.requestFailed(statusCode)
Collapse file

‎android/app/src/main/java/dev/opencode/mobile/domain/worktree/WorktreeCreate.kt‎

Copy file name to clipboard
+67Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package dev.opencode.mobile.domain.worktree
2+
3+
/** A new checkout of a project. V1 ignores [projectId] and [baseRef]; V2 needs [projectId]. */
4+
data class CreateWorktreeRequest(
5+
val projectId: String?,
6+
/** The checkout the new one is made from (v1: the project checkout the server is asked in). */
7+
val sourceDirectory: String,
8+
val name: String,
9+
/** V2 start ref; null starts from [sourceDirectory]'s HEAD. */
10+
val baseRef: String?,
11+
)
12+
13+
data class CreatedWorktree(
14+
/** Canonical directory of the new checkout. */
15+
val directory: String,
16+
/** The name the server used, which may differ from the requested one. */
17+
val name: String,
18+
/** V1 `opencode/<name>`; null for a detached v2 checkout. */
19+
val branch: String?,
20+
)
21+
22+
/** Create failed; [message] is the server's own text when it gave one. */
23+
class WorktreeCreateError(
24+
override val message: String,
25+
) : Exception(message)
26+
27+
/** Copy of New worktree (Run in, Move to worktree, and the form); identical on iOS. */
28+
object WorktreeCreateCopy {
29+
const val NEW_WORKTREE_ROW = "New worktree…"
30+
const val RUN_IN_ROW_SUBTITLE = "Create a checkout and start there"
31+
const val MOVE_ROW_SUBTITLE = "Create a checkout and move there"
32+
const val NEEDS_V2 = "Needs an opencode v2 server"
33+
const val TURN_ON_WORKTREES = "Turn on Worktrees in Settings"
34+
const val NOT_GIT = "Needs a git repository"
35+
const val NO_COMMIT = "Needs a git repository with a commit"
36+
const val UNSUPPORTED = "This server can't create worktrees"
37+
const val FORM_TITLE = "New worktree"
38+
const val NAME_LABEL = "Name"
39+
const val BRANCH_LABEL = "Branch"
40+
const val BASE_LABEL = "Create from"
41+
const val BACK = "Back"
42+
const val V1_BRANCH_NOTE = "opencode v1 names it after the worktree"
43+
const val V2_NO_BRANCH = "No branch (detached)"
44+
const val V2_BRANCH_NOTE = "opencode v2 checkouts have no branch"
45+
const val CURRENT_CHECKOUT = "Current checkout"
46+
const val V1_BASE_NOTE = "opencode v1 uses the current checkout"
47+
const val BASE_PICK_HINT = "Tap to pick a branch"
48+
const val CURRENT_SUFFIX = " (current)"
49+
const val BASE_LOADING = "Loading branches…"
50+
const val BASE_FAILED = "Couldn't load branches"
51+
const val NAME_EMPTY = "Enter a name"
52+
const val NAME_CHARS = "Use letters, numbers, dots, dashes or underscores"
53+
const val NAME_LONG = "Use at most 64 characters"
54+
const val SUBMIT_RUN_IN = "Create and start"
55+
const val SUBMIT_MOVE = "Create and move"
56+
const val SUBMITTING = "Creating…"
57+
58+
fun failed(message: String): String = "Couldn't create the worktree: $message"
59+
60+
fun requestFailed(statusCode: Int): String = "Request failed (HTTP $statusCode)"
61+
62+
/** V1 branch: `opencode/<name>`, or `opencode/…` while the name is empty. */
63+
fun v1Branch(name: String): String = "opencode/" + name.trim().ifEmpty { "…" }
64+
65+
/** The default base: the source checkout's branch marked current, else [CURRENT_CHECKOUT]. */
66+
fun defaultBase(sourceBranch: String?): String = sourceBranch?.let { it + CURRENT_SUFFIX } ?: CURRENT_CHECKOUT
67+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.