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 @@ -168,6 +168,7 @@ object ProductAnalytics {
const val CHAT_DISMISS_SNACKBAR = "chat_dismiss_snackbar"
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_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 @@ -238,6 +239,7 @@ object ProductAnalytics {
const val CHAT_DELETE_CANCEL = "chat_delete_cancel"
const val MESSAGE_ACTIONS_DISMISS = "message_actions_dismiss"
const val MESSAGE_ACTIONS_REVERT = "message_actions_revert"
const val MESSAGE_ACTIONS_FORK = "message_actions_fork"
const val MESSAGE_ACTIONS_COPY = "message_actions_copy"
const val CHAT_STEER_PENDING_PROMPT = "chat_steer_pending_prompt"
const val CHAT_QUEUE_PENDING_PROMPT = "chat_queue_pending_prompt"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package dev.opencode.mobile.domain.session

/** Title prefilled in every fork name dialog (Home, Session Chat overflow, message actions, Commands). */
object SessionForkTitle {
const val FALLBACK = "Forked session"

fun suggested(currentTitle: String): String {
val trimmed = currentTitle.trim()
return if (trimmed.isEmpty()) FALLBACK else "Fork of $trimmed"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import dev.opencode.mobile.domain.session.OptimisticSessionCreate
import dev.opencode.mobile.domain.session.Session
import dev.opencode.mobile.domain.session.SessionActivitySnapshot
import dev.opencode.mobile.domain.session.SessionDomainAdapter
import dev.opencode.mobile.domain.session.SessionForkTitle
import dev.opencode.mobile.domain.session.SessionRepository
import dev.opencode.mobile.domain.session.SessionSummary
import dev.opencode.mobile.domain.session.activeSessions
Expand Down Expand Up @@ -1021,10 +1022,7 @@ class MainScreenViewModel
}
}

fun suggestedHomeForkTitle(currentTitle: String): String {
val trimmed = currentTitle.trim()
return if (trimmed.isEmpty()) "Forked session" else "Fork of $trimmed"
}
fun suggestedHomeForkTitle(currentTitle: String): String = SessionForkTitle.suggested(currentTitle)

data class HomeServersChrome(
val title: String = "Sessions",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,17 @@ fun SessionChatScreen(
},
),
)
add(
OpenCodeOverflowMenuEntry(
title = "Fork session",
icon = OpenCodeIcons.CallSplit,
enabled = sessionCreated,
onClick = {
menuExpanded = false
viewModel.openForkSession()
},
),
)
add(
OpenCodeOverflowMenuEntry(
title = "Browse files",
Expand Down Expand Up @@ -1107,6 +1118,7 @@ fun SessionChatScreen(
target = messageActionsTarget,
onDismiss = { messageActionsTarget = null },
onRevertMessage = viewModel::revertMessage,
onForkFromMessage = viewModel::forkFromMessage,
)

SessionChatPendingPromptsSheet(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ class SessionChatViewModel
newSessionModelSelectionResolver = newSessionModelSelectionResolver,
connectionSessionCoordinator = connectionSessionCoordinator,
mcpRepository = mcpRepository,
composerDraftStore = composerDraftStore,
scope = viewModelScope,
)
private val inbox =
Expand Down Expand Up @@ -800,6 +801,34 @@ class SessionChatViewModel
)
}

/** Overflow menu "Fork session": forks the whole session (no message id). */
fun openForkSession() {
if (!hasCreatedSession()) return
forkDraftEditReported = false
logAction(
actionId = ProductAnalytics.Action.CHAT_OVERFLOW_FORK,
screenId = ProductAnalytics.Screen.SESSION_OVERFLOW,
)
commands.openForkDialog(currentTitle = sessionInfo.state.value.sessionTitle)
}

/**
* Message actions "Fork from here": forks history before [messageId] and prefills the
* fork's composer with [messageText] (analytics are logged by the sheet).
*/
fun forkFromMessage(
messageId: String,
messageText: String,
) {
if (!hasCreatedSession()) return
forkDraftEditReported = false
commands.openForkDialog(
currentTitle = sessionInfo.state.value.sessionTitle,
atMessageId = messageId,
messageText = messageText,
)
}

fun updateForkDraft(text: String) {
if (!forkDraftEditReported) {
forkDraftEditReported = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@ package dev.opencode.mobile.ui.sessionchat.region

import dev.opencode.mobile.domain.command.ClientSlashActionCatalog
import dev.opencode.mobile.domain.command.ClientSlashMessageRef
import dev.opencode.mobile.domain.composer.ComposerDraft
import dev.opencode.mobile.domain.composer.ComposerDraftStore
import dev.opencode.mobile.domain.connection.ConnectionSessionCoordinator
import dev.opencode.mobile.domain.diagnostic.DiagnosticLog
import dev.opencode.mobile.domain.diagnostic.DiagnosticLogArea
import dev.opencode.mobile.domain.mcp.McpRepository
import dev.opencode.mobile.domain.mcp.McpServerCatalog
import dev.opencode.mobile.domain.message.Message
import dev.opencode.mobile.domain.message.MessageRole
import dev.opencode.mobile.domain.model.ModelSelectionConnectionIdentity
import dev.opencode.mobile.domain.model.NewSessionModelSelectionResolver
import dev.opencode.mobile.domain.session.CompactionStart
import dev.opencode.mobile.domain.session.OptimisticSessionCreate
import dev.opencode.mobile.domain.session.Session
import dev.opencode.mobile.domain.session.SessionForkTitle
import dev.opencode.mobile.domain.session.SessionRepository
import dev.opencode.mobile.ui.sessionchat.ChildSessionNavigationTarget
import dev.opencode.mobile.ui.sessionchat.PendingTerminalOpen
Expand Down Expand Up @@ -41,6 +46,7 @@ class SessionChatCommands(
private val newSessionModelSelectionResolver: NewSessionModelSelectionResolver,
private val connectionSessionCoordinator: ConnectionSessionCoordinator,
private val mcpRepository: McpRepository,
private val composerDraftStore: ComposerDraftStore,
private val scope: CoroutineScope,
) {
var ioDispatcher: CoroutineDispatcher = Dispatchers.IO
Expand All @@ -54,6 +60,12 @@ class SessionChatCommands(
private var boundWorktree: String? = null
private var currentRevertMessageId: String? = null
private var forkedTarget: ChildSessionNavigationTarget? = null

/** Message the open fork dialog forks from (history strictly before it); null forks at the tip. */
private var forkAtMessageId: String? = null

/** Text of [forkAtMessageId], saved as the new fork's composer draft. */
private var forkComposerPrefill: String? = null
private var lastMessages: List<SessionChatMessageItem> = emptyList()
private var lastHasSelectedComposerModel: Boolean = false
private var lastDomainMessages: List<Message> = emptyList()
Expand Down Expand Up @@ -87,6 +99,8 @@ class SessionChatCommands(
boundWorktree = worktree
currentRevertMessageId = null
forkedTarget = null
forkAtMessageId = null
forkComposerPrefill = null
lastMessages = emptyList()
lastHasSelectedComposerModel = false
lastDomainMessages = emptyList()
Expand Down Expand Up @@ -285,12 +299,24 @@ class SessionChatCommands(
}
}

fun openForkDialog(currentTitle: String) {
/**
* Opens the fork name dialog. [atMessageId] forks from that user message (the server copies
* history strictly before it) and [messageText] becomes the fork's composer draft; null forks
* the whole session.
*/
fun openForkDialog(
currentTitle: String,
atMessageId: String? = null,
messageText: String? = null,
) {
dismissCommands()
if (_state.value.forkSubmitting) return
forkAtMessageId = atMessageId
forkComposerPrefill = if (atMessageId != null) messageText?.takeIf { it.isNotBlank() } else null
_state.update {
it.copy(
forkDialogVisible = true,
forkDraftTitle = currentTitle,
forkDraftTitle = SessionForkTitle.suggested(currentTitle),
forkSubmitting = false,
forkErrorMessage = null,
)
Expand All @@ -302,51 +328,95 @@ class SessionChatCommands(
}

fun cancelForkDialog() {
if (_state.value.forkSubmitting) return
forkAtMessageId = null
forkComposerPrefill = null
_state.update { it.copy(forkDialogVisible = false, forkSubmitting = false, forkErrorMessage = null) }
}

/**
* Forks, then renames the fork. A failed fork keeps the dialog open with the error; a failed
* rename still offers the created fork (under its server title) and reports a snackbar error,
* so a retry never creates a second fork.
*/
fun confirmFork() {
if (_state.value.forkSubmitting) return
val snapshot = _state.value
if (snapshot.forkSubmitting || !snapshot.forkDialogVisible) return
val sessionId = boundSessionId ?: return
val worktree = boundWorktree ?: return
val title = _state.value.forkDraftTitle.trim()
val title = snapshot.forkDraftTitle.trim()
if (title.isEmpty()) {
_state.update { it.copy(forkErrorMessage = "Enter a session title") }
return
}
val atMessageId = forkAtMessageId
val composerPrefill = forkComposerPrefill
_state.update { it.copy(forkSubmitting = true, forkErrorMessage = null) }
scope.launch(ioDispatcher) {
runCatching {
val forked = sessionRepository.forkSession(id = sessionId, atMessageId = null, directory = worktree)
sessionRepository.updateSession(id = forked.id, title = title, directory = worktree)
}.onSuccess { updated ->
logI("fork success sourceSession=$sessionId forkedSession=${updated.id}")
forkedTarget =
ChildSessionNavigationTarget(
sessionId = updated.id,
sessionTitle = updated.title,
worktree = worktree,
)
_state.update {
it.copy(
forkDialogVisible = false,
forkSubmitting = false,
forkResultVisible = true,
forkedSessionTitle = updated.title,
)
}
}.onFailure { error ->
logW("fork failed sourceSession=$sessionId error=${error.message}")
_state.update {
it.copy(
forkSubmitting = false,
forkErrorMessage = error.message ?: "Couldn't fork session.",
)
val forked =
runCatching {
sessionRepository.forkSession(id = sessionId, atMessageId = atMessageId, directory = worktree)
}.getOrElse { error ->
if (error is CancellationException) throw error
logW("fork failed sourceSession=$sessionId error=${error.message}")
_state.update {
it.copy(
forkSubmitting = false,
forkErrorMessage = error.message ?: "Couldn't fork session.",
)
}
return@launch
}
logI("fork success sourceSession=$sessionId forkedSession=${forked.id} fromMessage=${atMessageId != null}")
forkAtMessageId = null
forkComposerPrefill = null
if (composerPrefill != null) {
saveForkComposerDraft(forkedSessionId = forked.id, worktree = worktree, text = composerPrefill)
}
val renamed: Session? =
runCatching {
sessionRepository.updateSession(id = forked.id, title = title, directory = worktree)
}.onFailure { error ->
if (error is CancellationException) throw error
logW("fork rename failed forkedSession=${forked.id} error=${error.message}")
}.getOrNull()
val result = renamed ?: forked
forkedTarget =
ChildSessionNavigationTarget(
sessionId = result.id,
sessionTitle = result.title,
worktree = worktree,
)
_state.update {
it.copy(
forkDialogVisible = false,
forkSubmitting = false,
forkErrorMessage = null,
forkResultVisible = true,
forkedSessionTitle = result.title,
actionErrorMessage = if (renamed == null) FORK_RENAME_FAILURE else it.actionErrorMessage,
actionSuccessMessage = if (renamed == null) null else it.actionSuccessMessage,
)
}
}
}

/** Stores [text] as the fork's composer draft; Session Chat's composer loads it when the fork binds. */
private suspend fun saveForkComposerDraft(
forkedSessionId: String,
worktree: String,
text: String,
) {
val profile = connectionSessionCoordinator.currentProfile() ?: return
val identity = ModelSelectionConnectionIdentity(profile.baseUrl, profile.username)
runCatching {
composerDraftStore.save(identity, worktree, forkedSessionId, ComposerDraft(text = text))
}.onFailure { error ->
if (error is CancellationException) throw error
logW("fork composer draft save failed forkedSession=$forkedSessionId error=${error.message}")
}
}

fun chooseForkOpen() {
val target = forkedTarget
forkedTarget = null
Expand Down Expand Up @@ -582,4 +652,8 @@ class SessionChatCommands(
private fun logW(message: String) {
DiagnosticLog.warning(DiagnosticLogArea.Chat, message)
}

companion object {
const val FORK_RENAME_FAILURE = "Fork created, but it couldn't be renamed."
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ internal fun SessionChatMessageActionsSheet(
target: SessionChatMessageActionsTarget?,
onDismiss: () -> Unit,
onRevertMessage: (String) -> Unit,
onForkFromMessage: (messageId: String, messageText: String) -> Unit,
) {
val context = LocalContext.current

Expand Down Expand Up @@ -49,6 +50,15 @@ internal fun SessionChatMessageActionsSheet(
onDismiss()
},
)
OpenCodeBottomSheetEntry(
title = "Fork from here",
startDecorator = BottomSheetEntryDecorator.Icon(OpenCodeIcons.CallSplit, "Fork from here"),
onClick = {
logMessageActionsAction(ProductAnalytics.Action.MESSAGE_ACTIONS_FORK)
onForkFromMessage(target.id, target.text)
onDismiss()
},
)
}
OpenCodeBottomSheetEntry(
title = "Copy message",
Expand Down
Loading