mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-23 04:37:09 +00:00
merge: B-M4c Android files/git browser + file viewer
This commit is contained in:
@@ -31,6 +31,12 @@ import app.hapi.companion.feature.chat.ChatViewModel
|
||||
import app.hapi.companion.feature.chat.composer.DictationController
|
||||
import app.hapi.companion.feature.chat.composer.HapiDictationApi
|
||||
import app.hapi.companion.feature.chat.composer.MediaRecorderDictation
|
||||
import app.hapi.companion.feature.files.ApiFilesGateway
|
||||
import app.hapi.companion.feature.files.FileViewerScreen
|
||||
import app.hapi.companion.feature.files.FileViewerViewModel
|
||||
import app.hapi.companion.feature.files.FilesScreen
|
||||
import app.hapi.companion.feature.files.FilesViewModel
|
||||
import app.hapi.companion.feature.files.ViewerMode
|
||||
import app.hapi.companion.feature.home.HomeScreen
|
||||
import app.hapi.companion.feature.newsession.ApiNewSessionGateway
|
||||
import app.hapi.companion.feature.newsession.NewSessionPrefs
|
||||
@@ -43,6 +49,7 @@ import app.hapi.companion.feature.pairing.PairingViewModel
|
||||
import app.hapi.companion.feature.pairing.QrScanScreen
|
||||
import app.hapi.companion.feature.sessions.SessionListViewModel
|
||||
import app.hapi.data.auth.AuthTerminalReason
|
||||
import java.util.Base64
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
@@ -57,6 +64,41 @@ object Routes {
|
||||
|
||||
fun chat(sessionId: String) = "chat/$sessionId"
|
||||
|
||||
/** Session files browser (B-M4c): Changes / Browse / Search tabs. */
|
||||
const val FILES = "chat/{sessionId}/files"
|
||||
|
||||
fun files(sessionId: String) = "chat/$sessionId/files"
|
||||
|
||||
/**
|
||||
* File viewer (B-M4c). `path` is base64url (no padding) so slashes and
|
||||
* specials survive the route pattern — the web twin does the same
|
||||
* (`encodeBase64` in `files.tsx`). `staged` picks the diff side, `mode`
|
||||
* (`diff`/`file`) the initial mode, `line` a citation line hint.
|
||||
*/
|
||||
const val FILE_VIEWER = "chat/{sessionId}/file?path={path}&staged={staged}&mode={mode}&line={line}"
|
||||
|
||||
fun fileViewer(
|
||||
sessionId: String,
|
||||
path: String,
|
||||
staged: Boolean? = null,
|
||||
mode: String? = null,
|
||||
line: Int? = null,
|
||||
): String = buildString {
|
||||
append("chat/").append(sessionId).append("/file?path=").append(encodeFilePath(path))
|
||||
staged?.let { append("&staged=").append(it) }
|
||||
mode?.let { append("&mode=").append(it) }
|
||||
line?.let { append("&line=").append(it) }
|
||||
}
|
||||
|
||||
fun encodeFilePath(path: String): String =
|
||||
Base64.getUrlEncoder().withoutPadding().encodeToString(path.toByteArray(Charsets.UTF_8))
|
||||
|
||||
fun decodeFilePath(encoded: String): String? = try {
|
||||
String(Base64.getUrlDecoder().decode(encoded), Charsets.UTF_8)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
null
|
||||
}
|
||||
|
||||
/** New-session form (B-M3d); optional machine preselect. */
|
||||
const val NEW_SESSION = "newSession?machineId={machineId}"
|
||||
|
||||
@@ -124,7 +166,9 @@ fun HapiNavigation() {
|
||||
if (!onPairing) {
|
||||
navController.navigateClearingBackStack(Routes.PAIRING)
|
||||
}
|
||||
} else if (navController.currentDestination?.route == Routes.CHAT) {
|
||||
} else if (
|
||||
navController.currentDestination?.route in setOf(Routes.CHAT, Routes.FILES, Routes.FILE_VIEWER)
|
||||
) {
|
||||
navController.popBackStack(Routes.HOME, inclusive = false)
|
||||
}
|
||||
}
|
||||
@@ -177,6 +221,80 @@ fun HapiNavigation() {
|
||||
}
|
||||
},
|
||||
dictation = holder.dictation,
|
||||
onOpenFiles = { navController.navigate(Routes.files(sessionId)) },
|
||||
onOpenFile = { path, line ->
|
||||
// Chat citations open full mode; the cited line renders as
|
||||
// a hint chip (no per-line highlight — B-M4c trade-off).
|
||||
navController.navigate(Routes.fileViewer(sessionId, path, mode = "file", line = line))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable(
|
||||
route = Routes.FILES,
|
||||
arguments = listOf(navArgument("sessionId") { type = NavType.StringType }),
|
||||
) { entry ->
|
||||
val sessionId = entry.arguments?.getString("sessionId") ?: return@composable
|
||||
val hubGraph = activeHubGraph ?: return@composable
|
||||
val holder = viewModel<FilesViewModelHolder>(
|
||||
key = "files:${hubGraph.hubUrl}:$sessionId",
|
||||
factory = viewModelFactory { FilesViewModelHolder(hubGraph, sessionId) },
|
||||
)
|
||||
FilesScreen(
|
||||
viewModel = holder.viewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
onOpenFile = { path, staged ->
|
||||
navController.navigate(Routes.fileViewer(sessionId, path, staged = staged))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
composable(
|
||||
route = Routes.FILE_VIEWER,
|
||||
arguments = listOf(
|
||||
navArgument("sessionId") { type = NavType.StringType },
|
||||
navArgument("path") {
|
||||
type = NavType.StringType
|
||||
nullable = true
|
||||
defaultValue = null
|
||||
},
|
||||
navArgument("staged") {
|
||||
type = NavType.StringType
|
||||
nullable = true
|
||||
defaultValue = null
|
||||
},
|
||||
navArgument("mode") {
|
||||
type = NavType.StringType
|
||||
nullable = true
|
||||
defaultValue = null
|
||||
},
|
||||
navArgument("line") {
|
||||
type = NavType.StringType
|
||||
nullable = true
|
||||
defaultValue = null
|
||||
},
|
||||
),
|
||||
) { entry ->
|
||||
val sessionId = entry.arguments?.getString("sessionId") ?: return@composable
|
||||
val hubGraph = activeHubGraph ?: return@composable
|
||||
val encodedPath = entry.arguments?.getString("path") ?: return@composable
|
||||
val path = Routes.decodeFilePath(encodedPath) ?: return@composable
|
||||
val staged = entry.arguments?.getString("staged")?.toBooleanStrictOrNull()
|
||||
val mode = when (entry.arguments?.getString("mode")) {
|
||||
"diff" -> ViewerMode.DIFF
|
||||
"file" -> ViewerMode.FILE
|
||||
else -> null
|
||||
}
|
||||
val line = entry.arguments?.getString("line")?.toIntOrNull()
|
||||
val holder = viewModel<FileViewerViewModelHolder>(
|
||||
key = "file:${hubGraph.hubUrl}:$sessionId:$encodedPath:$staged:$mode",
|
||||
factory = viewModelFactory {
|
||||
FileViewerViewModelHolder(hubGraph, sessionId, path, staged, mode, line)
|
||||
},
|
||||
)
|
||||
FileViewerScreen(
|
||||
viewModel = holder.viewModel,
|
||||
onBack = { navController.popBackStack() },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -335,6 +453,47 @@ private class ChatViewModelHolder(
|
||||
}
|
||||
}
|
||||
|
||||
/** Shell for the files browser (B-M4c); keyed per hub+session. */
|
||||
private class FilesViewModelHolder(hubGraph: HubGraph, sessionId: String) : ViewModel() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
val viewModel = FilesViewModel(
|
||||
sessionId = sessionId,
|
||||
gateway = ApiFilesGateway(hubGraph.session.api),
|
||||
scope = scope,
|
||||
)
|
||||
|
||||
override fun onCleared() {
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/** Shell for the single-file viewer (B-M4c). */
|
||||
private class FileViewerViewModelHolder(
|
||||
hubGraph: HubGraph,
|
||||
sessionId: String,
|
||||
path: String,
|
||||
staged: Boolean?,
|
||||
mode: ViewerMode?,
|
||||
line: Int?,
|
||||
) : ViewModel() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
val viewModel = FileViewerViewModel(
|
||||
sessionId = sessionId,
|
||||
path = path,
|
||||
initialStaged = staged,
|
||||
initialMode = mode,
|
||||
focusLine = line,
|
||||
gateway = ApiFilesGateway(hubGraph.session.api),
|
||||
scope = scope,
|
||||
)
|
||||
|
||||
override fun onCleared() {
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
/** Shell for the create form (B-M3d); draft persistence survives via prefs. */
|
||||
private class NewSessionViewModelHolder(
|
||||
hubGraph: HubGraph,
|
||||
|
||||
@@ -21,11 +21,14 @@ import app.hapi.protocol.markdown.HrefDecision
|
||||
* The confirm-aware URL opener the M2d1 markdown module defers to this
|
||||
* milestone: [HrefDecision.Allowed] dispatches immediately,
|
||||
* [HrefDecision.ConfirmFirst] asks first (custom schemes), blocked never gets
|
||||
* here. Workspace-file citations stay inert until the session file viewer
|
||||
* lands (M4) — a toast tells the user why.
|
||||
* here. Workspace-file citations route to the session file viewer (B-M4c) via
|
||||
* [onOpenFile] — the chat screen wires it to `chat/{id}/file` in full mode,
|
||||
* passing the cited line along as a hint.
|
||||
*/
|
||||
@Composable
|
||||
fun rememberChatLinkHandler(): MarkdownLinkHandler {
|
||||
fun rememberChatLinkHandler(
|
||||
onOpenFile: (path: String, line: Int?) -> Unit = { _, _ -> },
|
||||
): MarkdownLinkHandler {
|
||||
val context = LocalContext.current
|
||||
var confirmUrl by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
@@ -48,11 +51,9 @@ fun rememberChatLinkHandler(): MarkdownLinkHandler {
|
||||
)
|
||||
}
|
||||
|
||||
return remember(context) {
|
||||
return remember(context, onOpenFile) {
|
||||
object : MarkdownLinkHandler {
|
||||
override fun onFilePath(path: String, line: Int?) {
|
||||
Toast.makeText(context, "File viewer arrives in a later milestone", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
override fun onFilePath(path: String, line: Int?) = onOpenFile(path, line)
|
||||
|
||||
override fun onUrl(url: String, decision: HrefDecision) {
|
||||
when (decision) {
|
||||
|
||||
@@ -63,6 +63,7 @@ import app.hapi.companion.feature.chat.composer.DictationController
|
||||
import app.hapi.companion.feature.chat.composer.DictationEvent
|
||||
import app.hapi.companion.feature.chat.composer.DictationState
|
||||
import app.hapi.companion.feature.chat.composer.QueuedMessagesBar
|
||||
import app.hapi.companion.feature.files.FolderGlyph
|
||||
import app.hapi.companion.feature.sessions.DeleteSessionDialog
|
||||
import app.hapi.companion.feature.sessions.RenameSessionDialog
|
||||
import app.hapi.companion.ui.markdown.LocalMarkdownLinkHandler
|
||||
@@ -100,6 +101,10 @@ fun ChatScreen(
|
||||
onNavigateToSession: (String) -> Unit = {},
|
||||
/** null ⇒ mic button hidden (tests / previews without a controller). */
|
||||
dictation: DictationController? = null,
|
||||
/** Top-bar folder icon → session files browser (B-M4c). */
|
||||
onOpenFiles: () -> Unit = {},
|
||||
/** Markdown file citations → file viewer (full mode; optional line hint). */
|
||||
onOpenFile: (path: String, line: Int?) -> Unit = { _, _ -> },
|
||||
) {
|
||||
val state by viewModel.uiState.collectAsState()
|
||||
val composerState by viewModel.composer.collectAsState()
|
||||
@@ -186,6 +191,9 @@ fun ChatScreen(
|
||||
},
|
||||
title = { ChatTitle(state.header) },
|
||||
actions = {
|
||||
IconButton(onClick = onOpenFiles) {
|
||||
Icon(FolderGlyph, contentDescription = "Session files")
|
||||
}
|
||||
IconButton(onClick = { configSheetOpen = true }) {
|
||||
Icon(Icons.Filled.Settings, contentDescription = "Session settings")
|
||||
}
|
||||
@@ -227,7 +235,7 @@ fun ChatScreen(
|
||||
) { padding ->
|
||||
CompositionLocalProvider(
|
||||
LocalChatMedia provides media,
|
||||
LocalMarkdownLinkHandler provides rememberChatLinkHandler(),
|
||||
LocalMarkdownLinkHandler provides rememberChatLinkHandler(onOpenFile = onOpenFile),
|
||||
LocalChatInteractions provides interactions,
|
||||
) {
|
||||
Column(
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalClipboardManager
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import app.hapi.companion.ui.components.DiffView
|
||||
import app.hapi.companion.ui.markdown.CodeBlock
|
||||
import app.hapi.companion.ui.markdown.Markdown
|
||||
import app.hapi.companion.ui.theme.hapi
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
/**
|
||||
* Single-file viewer (`chat/{sessionId}/file`), the Android take on web
|
||||
* `file.tsx`: diff mode (parsed unified diff in [DiffView], staged/unstaged
|
||||
* toggle) ⇄ full mode ([CodeBlock] with its 400-line highlight cap and copy
|
||||
* button; markdown gets a Source/Preview toggle over the shared [Markdown]
|
||||
* renderer; images decode to a bitmap). Top bar shows the file name with the
|
||||
* middle-ellipsized path and a copy-path action.
|
||||
*
|
||||
* Chat citations may carry a line number; per-line highlighting inside the
|
||||
* single-`Text` [CodeBlock] isn't cheap, so the viewer shows a "Line N" hint
|
||||
* chip instead of scrolling/highlighting (noted B-M4c trade-off).
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun FileViewerScreen(
|
||||
viewModel: FileViewerViewModel,
|
||||
onBack: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
DisposableEffect(viewModel) {
|
||||
viewModel.start()
|
||||
onDispose { }
|
||||
}
|
||||
|
||||
val state by viewModel.state.collectAsState()
|
||||
val colors = MaterialTheme.hapi
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
},
|
||||
title = {
|
||||
Column {
|
||||
Text(
|
||||
text = state.fileName,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = formatFileMetadata(state.sizeBytes, state.modifiedAt) ?: state.path,
|
||||
fontSize = 11.sp,
|
||||
color = colors.hint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.MiddleEllipsis,
|
||||
)
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
IconButton(onClick = viewModel::refresh) {
|
||||
Icon(Icons.Filled.Refresh, contentDescription = "Refresh")
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
) {
|
||||
PathRow(path = state.path)
|
||||
ModeToggleRow(state, viewModel)
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
when (state.mode) {
|
||||
ViewerMode.DIFF -> DiffContent(state)
|
||||
ViewerMode.FILE -> FileContent(state)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PathRow(path: String) {
|
||||
val colors = MaterialTheme.hapi
|
||||
// Sync clipboard API is the deliberate choice, matching CodeBlock's copy.
|
||||
@Suppress("DEPRECATION")
|
||||
val clipboard = LocalClipboardManager.current
|
||||
var copied by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(copied) {
|
||||
if (copied) {
|
||||
delay(1600)
|
||||
copied = false
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 16.dp, end = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
text = path,
|
||||
fontSize = 12.sp,
|
||||
color = colors.hint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.MiddleEllipsis,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Text(
|
||||
text = if (copied) "Copied" else "Copy path",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = if (copied) MaterialTheme.colorScheme.primary else colors.hint,
|
||||
modifier = Modifier
|
||||
.clickable {
|
||||
clipboard.setText(AnnotatedString(path))
|
||||
copied = true
|
||||
}
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModeToggleRow(state: FileViewerUiState, viewModel: FileViewerViewModel) {
|
||||
val hasDiff = state.diff is DiffUiState.Ready
|
||||
val isMarkdownFile = (state.content as? FileContentUiState.Text)?.isMarkdown == true
|
||||
if (!hasDiff && !isMarkdownFile && state.focusLine == null) return
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (hasDiff) {
|
||||
ModeChip("Diff", state.mode == ViewerMode.DIFF) { viewModel.setMode(ViewerMode.DIFF) }
|
||||
ModeChip("File", state.mode == ViewerMode.FILE) { viewModel.setMode(ViewerMode.FILE) }
|
||||
}
|
||||
if (hasDiff && state.mode == ViewerMode.DIFF) {
|
||||
Text("·", color = MaterialTheme.hapi.hint)
|
||||
ModeChip("Unstaged", !state.staged) { viewModel.setStaged(false) }
|
||||
ModeChip("Staged", state.staged) { viewModel.setStaged(true) }
|
||||
}
|
||||
if (isMarkdownFile && state.mode == ViewerMode.FILE) {
|
||||
if (hasDiff) Text("·", color = MaterialTheme.hapi.hint)
|
||||
ModeChip("Source", !state.markdownPreview) { viewModel.setMarkdownPreview(false) }
|
||||
ModeChip("Preview", state.markdownPreview) { viewModel.setMarkdownPreview(true) }
|
||||
}
|
||||
state.focusLine?.let { line ->
|
||||
Text(
|
||||
text = "Line $line",
|
||||
fontSize = 11.sp,
|
||||
color = MaterialTheme.hapi.hint,
|
||||
modifier = Modifier.padding(start = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ModeChip(label: String, selected: Boolean, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.hapi
|
||||
Text(
|
||||
text = label,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = if (selected) MaterialTheme.colorScheme.onPrimary else colors.hint,
|
||||
modifier = Modifier
|
||||
.background(
|
||||
color = if (selected) MaterialTheme.colorScheme.primary else colors.codeHeaderBackground,
|
||||
shape = RoundedCornerShape(50),
|
||||
)
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- content --
|
||||
|
||||
@Composable
|
||||
private fun DiffContent(state: FileViewerUiState) {
|
||||
when (val diff = state.diff) {
|
||||
DiffUiState.Loading -> LoadingBlock()
|
||||
DiffUiState.Empty -> HintBlock("No changes in this file")
|
||||
is DiffUiState.Failed -> HintBlock(diff.message)
|
||||
is DiffUiState.Ready -> diff.files.forEach { file ->
|
||||
DiffView(file = file, compact = false, modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FileContent(state: FileViewerUiState) {
|
||||
when (val content = state.content) {
|
||||
FileContentUiState.Loading -> LoadingBlock()
|
||||
is FileContentUiState.Failed -> HintBlock(content.message)
|
||||
FileContentUiState.Empty -> HintBlock("This file is empty")
|
||||
FileContentUiState.Binary -> HintBlock("Binary file — no preview available")
|
||||
is FileContentUiState.Image -> ImageContent(content, state.fileName)
|
||||
is FileContentUiState.Text ->
|
||||
if (content.isMarkdown && state.markdownPreview) {
|
||||
Markdown(text = content.text, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
CodeBlock(
|
||||
code = content.text,
|
||||
language = content.language,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ImageContent(content: FileContentUiState.Image, fileName: String) {
|
||||
val bitmap = remember(content) {
|
||||
BitmapFactory.decodeByteArray(content.bytes, 0, content.bytes.size)?.asImageBitmap()
|
||||
}
|
||||
if (bitmap == null) {
|
||||
// SVG and other formats BitmapFactory can't decode.
|
||||
HintBlock("Preview not available for this image format")
|
||||
} else {
|
||||
Image(
|
||||
bitmap = bitmap,
|
||||
contentDescription = fileName,
|
||||
contentScale = ContentScale.Fit,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadingBlock() {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 48.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HintBlock(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
fontSize = 13.sp,
|
||||
color = MaterialTheme.hapi.hint,
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 16.dp),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import app.hapi.protocol.git.DiffFile
|
||||
import app.hapi.protocol.git.UnifiedDiffParser
|
||||
import app.hapi.protocol.wire.FileReadResponse
|
||||
import java.util.Base64
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// ------------------------------------------------------------- UI models --
|
||||
|
||||
enum class ViewerMode { DIFF, FILE }
|
||||
|
||||
sealed interface DiffUiState {
|
||||
data object Loading : DiffUiState
|
||||
|
||||
/** Diff succeeded but printed nothing (no changes on this side). */
|
||||
data object Empty : DiffUiState
|
||||
data class Failed(val message: String) : DiffUiState
|
||||
data class Ready(val files: List<DiffFile>) : DiffUiState
|
||||
}
|
||||
|
||||
sealed interface FileContentUiState {
|
||||
data object Loading : FileContentUiState
|
||||
data class Failed(val message: String) : FileContentUiState
|
||||
data object Empty : FileContentUiState
|
||||
|
||||
/** Undecodable or heuristically binary (web `isBinaryContent`). */
|
||||
data object Binary : FileContentUiState
|
||||
|
||||
data class Text(
|
||||
val text: String,
|
||||
/** Lowercased extension, fed to the `CodeBlock` highlighter. */
|
||||
val language: String?,
|
||||
val isMarkdown: Boolean,
|
||||
) : FileContentUiState
|
||||
|
||||
/** Raw image bytes for `BitmapFactory` (identity equality is fine here). */
|
||||
class Image(val bytes: ByteArray, val mimeType: String) : FileContentUiState
|
||||
}
|
||||
|
||||
data class FileViewerUiState(
|
||||
val path: String,
|
||||
val fileName: String,
|
||||
val mode: ViewerMode,
|
||||
/** Which diff side is showing (the staged/unstaged toggle). */
|
||||
val staged: Boolean,
|
||||
val diff: DiffUiState = DiffUiState.Loading,
|
||||
val content: FileContentUiState = FileContentUiState.Loading,
|
||||
/** Markdown files: render preview instead of source (web default: preview). */
|
||||
val markdownPreview: Boolean = true,
|
||||
val sizeBytes: Long? = null,
|
||||
val modifiedAt: Long? = null,
|
||||
/** Requested line from a chat citation; shown as a hint chip (no per-line highlight — see screen note). */
|
||||
val focusLine: Int? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* One file, two modes (web `file.tsx`): **diff** — `git-diff-file` stdout
|
||||
* through `UnifiedDiffParser` into `DiffView`, with a staged/unstaged toggle —
|
||||
* and **full** — `file` read, base64-decoded into highlighted text, markdown
|
||||
* preview, or an image. Both loads run in parallel; like the web page, the
|
||||
* viewer auto-falls to full mode when the diff is empty/failed or the file is
|
||||
* an image, until the user picks a mode explicitly.
|
||||
*/
|
||||
class FileViewerViewModel(
|
||||
private val sessionId: String,
|
||||
private val path: String,
|
||||
initialStaged: Boolean?,
|
||||
initialMode: ViewerMode?,
|
||||
focusLine: Int?,
|
||||
private val gateway: FilesGateway,
|
||||
private val scope: CoroutineScope,
|
||||
) {
|
||||
private val stateFlow = MutableStateFlow(
|
||||
FileViewerUiState(
|
||||
path = path,
|
||||
fileName = path.substringAfterLast('/').ifEmpty { path },
|
||||
mode = initialMode ?: ViewerMode.DIFF,
|
||||
staged = initialStaged ?: false,
|
||||
focusLine = focusLine,
|
||||
),
|
||||
)
|
||||
val state: StateFlow<FileViewerUiState> = stateFlow.asStateFlow()
|
||||
|
||||
/** Explicit mode choice (initial `mode` arg or a chip tap) disables auto-fallback. */
|
||||
private var modeChosen = initialMode != null
|
||||
private var started = false
|
||||
private var diffJob: Job? = null
|
||||
|
||||
fun start() {
|
||||
if (started) return
|
||||
started = true
|
||||
loadDiff()
|
||||
loadContent()
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
loadDiff()
|
||||
loadContent()
|
||||
}
|
||||
|
||||
fun setMode(mode: ViewerMode) {
|
||||
modeChosen = true
|
||||
stateFlow.update { it.copy(mode = mode) }
|
||||
}
|
||||
|
||||
/** Staged/unstaged toggle: reloads the diff for the other side. */
|
||||
fun setStaged(staged: Boolean) {
|
||||
if (stateFlow.value.staged == staged) return
|
||||
stateFlow.update { it.copy(staged = staged) }
|
||||
loadDiff()
|
||||
}
|
||||
|
||||
fun setMarkdownPreview(preview: Boolean) {
|
||||
stateFlow.update { it.copy(markdownPreview = preview) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- diff --
|
||||
|
||||
private fun loadDiff() {
|
||||
diffJob?.cancel()
|
||||
stateFlow.update { it.copy(diff = DiffUiState.Loading) }
|
||||
diffJob = scope.launch {
|
||||
val staged = stateFlow.value.staged
|
||||
val diff = try {
|
||||
val response = gateway.gitDiffFile(sessionId, path, staged)
|
||||
when {
|
||||
!response.success ->
|
||||
DiffUiState.Failed(response.error ?: response.stderr ?: "Failed to load diff")
|
||||
response.stdout.isNullOrEmpty() -> DiffUiState.Empty
|
||||
else -> {
|
||||
val files = UnifiedDiffParser.parse(response.stdout.orEmpty())
|
||||
if (files.isEmpty()) DiffUiState.Empty else DiffUiState.Ready(files)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
DiffUiState.Failed(e.message ?: "Failed to load diff")
|
||||
}
|
||||
stateFlow.update { it.copy(diff = diff) }
|
||||
autoSelectMode()
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- content --
|
||||
|
||||
private fun loadContent() {
|
||||
scope.launch {
|
||||
val content = try {
|
||||
decodeContent(gateway.readFile(sessionId, path))
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
stateFlow.update { it.copy(content = FileContentUiState.Failed(e.message ?: "Failed to read file")) }
|
||||
return@launch
|
||||
}
|
||||
stateFlow.update {
|
||||
it.copy(
|
||||
content = content.state,
|
||||
sizeBytes = content.size,
|
||||
modifiedAt = content.modified,
|
||||
)
|
||||
}
|
||||
autoSelectMode()
|
||||
}
|
||||
}
|
||||
|
||||
private class DecodedContent(val state: FileContentUiState, val size: Long?, val modified: Long?)
|
||||
|
||||
private fun decodeContent(response: FileReadResponse): DecodedContent {
|
||||
if (!response.success) {
|
||||
return DecodedContent(
|
||||
FileContentUiState.Failed(response.error ?: "Failed to read file"),
|
||||
response.size,
|
||||
response.modified,
|
||||
)
|
||||
}
|
||||
val base64 = response.content
|
||||
if (base64.isNullOrEmpty()) {
|
||||
return DecodedContent(FileContentUiState.Empty, response.size, response.modified)
|
||||
}
|
||||
|
||||
val bytes = try {
|
||||
Base64.getMimeDecoder().decode(base64)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
// Undecodable payload — treat like the web's failed decode: binary.
|
||||
return DecodedContent(FileContentUiState.Binary, response.size, response.modified)
|
||||
}
|
||||
|
||||
val mime = imageMimeType(path)
|
||||
if (mime != null) {
|
||||
return DecodedContent(FileContentUiState.Image(bytes, mime), response.size, response.modified)
|
||||
}
|
||||
|
||||
val text = String(bytes, Charsets.UTF_8)
|
||||
if (isBinaryContent(text)) {
|
||||
return DecodedContent(FileContentUiState.Binary, response.size, response.modified)
|
||||
}
|
||||
if (text.isEmpty()) {
|
||||
return DecodedContent(FileContentUiState.Empty, response.size, response.modified)
|
||||
}
|
||||
return DecodedContent(
|
||||
FileContentUiState.Text(
|
||||
text = text,
|
||||
language = fileExtension(path),
|
||||
isMarkdown = isMarkdownFile(path),
|
||||
),
|
||||
response.size,
|
||||
response.modified,
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- mode --
|
||||
|
||||
/**
|
||||
* Web `file.tsx` effect: images always open full; an empty or failed diff
|
||||
* falls back to full. Skipped once the user (or the route) chose a mode.
|
||||
*/
|
||||
private fun autoSelectMode() {
|
||||
if (modeChosen) {
|
||||
// Images have no text diff worth showing even when explicitly
|
||||
// requested via mode=diff from a stale link.
|
||||
return
|
||||
}
|
||||
val current = stateFlow.value
|
||||
val shouldShowFile = current.content is FileContentUiState.Image ||
|
||||
current.diff is DiffUiState.Empty ||
|
||||
current.diff is DiffUiState.Failed
|
||||
if (shouldShowFile && current.mode == ViewerMode.DIFF) {
|
||||
stateFlow.update { it.copy(mode = ViewerMode.FILE) }
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Web `IMAGE_MIME_BY_EXTENSION` (`file.tsx`). */
|
||||
private val IMAGE_MIME_BY_EXTENSION = mapOf(
|
||||
"apng" to "image/apng",
|
||||
"avif" to "image/avif",
|
||||
"bmp" to "image/bmp",
|
||||
"gif" to "image/gif",
|
||||
"ico" to "image/x-icon",
|
||||
"jpeg" to "image/jpeg",
|
||||
"jpg" to "image/jpeg",
|
||||
"png" to "image/png",
|
||||
"svg" to "image/svg+xml",
|
||||
"tif" to "image/tiff",
|
||||
"tiff" to "image/tiff",
|
||||
"webp" to "image/webp",
|
||||
)
|
||||
|
||||
fun fileExtension(path: String): String? {
|
||||
val parts = path.split(".")
|
||||
if (parts.size <= 1) return null
|
||||
return parts.last().lowercase().ifEmpty { null }
|
||||
}
|
||||
|
||||
fun imageMimeType(path: String): String? =
|
||||
fileExtension(path)?.let { IMAGE_MIME_BY_EXTENSION[it] }
|
||||
|
||||
/** Web `isMarkdownFile` (`file-markdown-preview.ts`): md / mdx only. */
|
||||
fun isMarkdownFile(path: String): Boolean {
|
||||
val ext = fileExtension(path)
|
||||
return ext == "md" || ext == "mdx"
|
||||
}
|
||||
|
||||
/** Web `isBinaryContent`: NUL, or > 10% control chars (excluding \t \n \r). */
|
||||
fun isBinaryContent(content: String): Boolean {
|
||||
if (content.isEmpty()) return false
|
||||
if ('\u0000' in content) return true
|
||||
val nonPrintable = content.count { it.code < 32 && it.code != 9 && it.code != 10 && it.code != 13 }
|
||||
return nonPrintable.toDouble() / content.length > 0.1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import app.hapi.data.api.HapiApi
|
||||
import app.hapi.protocol.wire.FileReadResponse
|
||||
import app.hapi.protocol.wire.FileSearchResponse
|
||||
import app.hapi.protocol.wire.GitCommandResponse
|
||||
import app.hapi.protocol.wire.ListDirectoryResponse
|
||||
|
||||
/**
|
||||
* The git/files REST surface the files feature consumes — a seam over
|
||||
* [HapiApi] so [FilesViewModel]/[FileViewerViewModel] tests run against fakes
|
||||
* (same pattern as `NewSessionGateway`). All six endpoints are RPC-wrapped:
|
||||
* check `success` on the body; transport failures throw.
|
||||
*/
|
||||
interface FilesGateway {
|
||||
suspend fun gitStatus(sessionId: String): GitCommandResponse
|
||||
suspend fun gitDiffNumstat(sessionId: String, staged: Boolean): GitCommandResponse
|
||||
suspend fun gitDiffFile(sessionId: String, path: String, staged: Boolean?): GitCommandResponse
|
||||
suspend fun readFile(sessionId: String, path: String): FileReadResponse
|
||||
suspend fun searchFiles(sessionId: String, query: String, limit: Int): FileSearchResponse
|
||||
|
||||
/** [path] is relative to the session root; null lists the root itself. */
|
||||
suspend fun listDirectory(sessionId: String, path: String?): ListDirectoryResponse
|
||||
}
|
||||
|
||||
class ApiFilesGateway(private val api: HapiApi) : FilesGateway {
|
||||
override suspend fun gitStatus(sessionId: String): GitCommandResponse =
|
||||
api.getGitStatus(sessionId)
|
||||
|
||||
override suspend fun gitDiffNumstat(sessionId: String, staged: Boolean): GitCommandResponse =
|
||||
api.getGitDiffNumstat(sessionId, staged)
|
||||
|
||||
override suspend fun gitDiffFile(sessionId: String, path: String, staged: Boolean?): GitCommandResponse =
|
||||
api.getGitDiffFile(sessionId, path, staged)
|
||||
|
||||
override suspend fun readFile(sessionId: String, path: String): FileReadResponse =
|
||||
api.readSessionFile(sessionId, path)
|
||||
|
||||
override suspend fun searchFiles(sessionId: String, query: String, limit: Int): FileSearchResponse =
|
||||
api.searchSessionFiles(sessionId, query, limit)
|
||||
|
||||
override suspend fun listDirectory(sessionId: String, path: String?): ListDirectoryResponse =
|
||||
api.listSessionDirectory(sessionId, path)
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowBack
|
||||
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Search
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Tab
|
||||
import androidx.compose.material3.TabRow
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import app.hapi.companion.ui.theme.hapi
|
||||
import app.hapi.protocol.git.GitFileStatus
|
||||
import app.hapi.protocol.wire.FileSearchItem
|
||||
|
||||
/**
|
||||
* Session files browser (`chat/{sessionId}/files`), the Android take on web
|
||||
* `files.tsx`: **Changes** (branch header + staged/unstaged sections with
|
||||
* status letters and ±counts), **Browse** (lazily expanded directory tree,
|
||||
* dirs-first sort, hidden-file toggle), **Search** (debounced ripgrep query).
|
||||
* Rows open the file viewer — Changes rows carry their staged side so the
|
||||
* viewer opens on the right diff.
|
||||
*/
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun FilesScreen(
|
||||
viewModel: FilesViewModel,
|
||||
onBack: () -> Unit,
|
||||
onOpenFile: (path: String, staged: Boolean?) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
DisposableEffect(viewModel) {
|
||||
viewModel.start()
|
||||
onDispose { }
|
||||
}
|
||||
|
||||
val changes by viewModel.changes.collectAsState()
|
||||
val browse by viewModel.browse.collectAsState()
|
||||
val search by viewModel.search.collectAsState()
|
||||
var tab by rememberSaveable { mutableIntStateOf(0) }
|
||||
|
||||
Scaffold(
|
||||
modifier = modifier.fillMaxSize(),
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
|
||||
}
|
||||
},
|
||||
title = { Text("Files") },
|
||||
actions = {
|
||||
IconButton(
|
||||
onClick = {
|
||||
when (tab) {
|
||||
0 -> viewModel.refreshChanges()
|
||||
1 -> viewModel.refreshBrowse()
|
||||
else -> viewModel.refreshSearch()
|
||||
}
|
||||
},
|
||||
) {
|
||||
Icon(Icons.Filled.Refresh, contentDescription = "Refresh")
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding),
|
||||
) {
|
||||
TabRow(selectedTabIndex = tab) {
|
||||
Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text("Changes") })
|
||||
Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text("Browse") })
|
||||
Tab(selected = tab == 2, onClick = { tab = 2 }, text = { Text("Search") })
|
||||
}
|
||||
when (tab) {
|
||||
0 -> ChangesTab(changes, onOpenFile)
|
||||
1 -> BrowseTab(
|
||||
browse,
|
||||
onToggleDirectory = viewModel::toggleDirectory,
|
||||
onToggleHidden = viewModel::setShowHidden,
|
||||
onOpenFile = { path -> onOpenFile(path, null) },
|
||||
)
|
||||
else -> SearchTab(
|
||||
search,
|
||||
onQueryChange = viewModel::setSearchQuery,
|
||||
onOpenFile = { path -> onOpenFile(path, null) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ Changes tab --
|
||||
|
||||
@Composable
|
||||
private fun ChangesTab(
|
||||
state: ChangesUiState,
|
||||
onOpenFile: (path: String, staged: Boolean?) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.hapi
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
state.error?.let { ErrorBanner(it) }
|
||||
|
||||
when {
|
||||
state.loading && state.status == null -> CenteredProgress()
|
||||
state.status == null -> CenteredHint("Git status unavailable for this session")
|
||||
else -> {
|
||||
val status = state.status
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(
|
||||
GitBranchGlyph,
|
||||
contentDescription = null,
|
||||
tint = colors.hint,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
Column {
|
||||
Text(
|
||||
text = status.branch ?: "Detached HEAD",
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
Text(
|
||||
text = "${status.totalStaged} staged · ${status.totalUnstaged} unstaged",
|
||||
fontSize = 12.sp,
|
||||
color = colors.hint,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (status.stagedFiles.isEmpty() && status.unstagedFiles.isEmpty()) {
|
||||
CenteredHint("No changes in the working tree")
|
||||
} else {
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
if (status.stagedFiles.isNotEmpty()) {
|
||||
item(key = "staged-header") {
|
||||
SectionHeader("Staged (${status.stagedFiles.size})")
|
||||
}
|
||||
items(
|
||||
status.stagedFiles.size,
|
||||
key = { "staged-${status.stagedFiles[it].fullPath}-$it" },
|
||||
) { index ->
|
||||
val file = status.stagedFiles[index]
|
||||
GitFileRow(file) { onOpenFile(file.fullPath, true) }
|
||||
}
|
||||
}
|
||||
if (status.unstagedFiles.isNotEmpty()) {
|
||||
item(key = "unstaged-header") {
|
||||
SectionHeader("Unstaged (${status.unstagedFiles.size})")
|
||||
}
|
||||
items(
|
||||
status.unstagedFiles.size,
|
||||
key = { "unstaged-${status.unstagedFiles[it].fullPath}-$it" },
|
||||
) { index ->
|
||||
val file = status.unstagedFiles[index]
|
||||
GitFileRow(file) { onOpenFile(file.fullPath, false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SectionHeader(text: String) {
|
||||
Text(
|
||||
text = text,
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.hapi.hint,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.hapi.codeHeaderBackground)
|
||||
.padding(horizontal = 16.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GitFileRow(file: GitFileStatus, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.hapi
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = file.fileName,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
val subtitle = file.oldPath?.let { "$it → ${file.fullPath}" }
|
||||
?: file.filePath.ifEmpty { "Project root" }
|
||||
Text(
|
||||
text = subtitle,
|
||||
fontSize = 12.sp,
|
||||
color = colors.hint,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.MiddleEllipsis,
|
||||
)
|
||||
}
|
||||
if (file.linesAdded > 0 || file.linesRemoved > 0) {
|
||||
Text(
|
||||
text = buildString {
|
||||
if (file.linesAdded > 0) append("+${file.linesAdded}")
|
||||
if (file.linesAdded > 0 && file.linesRemoved > 0) append(' ')
|
||||
if (file.linesRemoved > 0) append("-${file.linesRemoved}")
|
||||
},
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 11.sp,
|
||||
color = colors.hint,
|
||||
)
|
||||
}
|
||||
StatusBadge(file)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusBadge(file: GitFileStatus) {
|
||||
val color = statusColor(file.status, MaterialTheme.hapi.isDark)
|
||||
Text(
|
||||
text = statusLetter(file.status),
|
||||
fontSize = 10.sp,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = color,
|
||||
modifier = Modifier
|
||||
.border(1.dp, color, RoundedCornerShape(4.dp))
|
||||
.padding(horizontal = 6.dp, vertical = 2.dp),
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Browse tab --
|
||||
|
||||
@Composable
|
||||
private fun BrowseTab(
|
||||
state: BrowseUiState,
|
||||
onToggleDirectory: (String) -> Unit,
|
||||
onToggleHidden: (Boolean) -> Unit,
|
||||
onOpenFile: (path: String) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.hapi
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onToggleHidden(!state.showHidden) }
|
||||
.padding(horizontal = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Checkbox(checked = state.showHidden, onCheckedChange = onToggleHidden)
|
||||
Text("Show hidden files", fontSize = 13.sp, color = colors.hint)
|
||||
}
|
||||
|
||||
LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(state.rows.size) { index ->
|
||||
when (val row = state.rows[index]) {
|
||||
is BrowseRow.Dir -> DirectoryRow(row, onToggleDirectory)
|
||||
is BrowseRow.File -> FileRow(row, onOpenFile)
|
||||
is BrowseRow.Loading -> Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = rowIndent(row.depth) + 16.dp, top = 10.dp, bottom = 10.dp),
|
||||
) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
is BrowseRow.Error -> Text(
|
||||
text = row.message,
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = rowIndent(row.depth) + 16.dp, top = 8.dp, bottom = 8.dp, end = 16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun rowIndent(depth: Int) = (depth * 16).dp
|
||||
|
||||
@Composable
|
||||
private fun DirectoryRow(row: BrowseRow.Dir, onToggle: (String) -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onToggle(row.path) }
|
||||
.padding(start = rowIndent(row.depth) + 8.dp, end = 16.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Icon(
|
||||
if (row.expanded) Icons.Filled.KeyboardArrowDown else Icons.AutoMirrored.Filled.KeyboardArrowRight,
|
||||
contentDescription = if (row.expanded) "Collapse" else "Expand",
|
||||
tint = MaterialTheme.hapi.hint,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Icon(
|
||||
FolderGlyph,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
Text(
|
||||
text = row.name,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FileRow(row: BrowseRow.File, onOpenFile: (String) -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onOpenFile(row.path) }
|
||||
// Files align with sibling directory names (chevron width offset).
|
||||
.padding(start = rowIndent(row.depth) + 30.dp, end = 16.dp, top = 8.dp, bottom = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = row.name,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
formatFileMetadata(row.size, row.modified)?.let {
|
||||
Text(text = it, fontSize = 11.sp, color = MaterialTheme.hapi.hint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- Search tab --
|
||||
|
||||
@Composable
|
||||
private fun SearchTab(
|
||||
state: SearchUiState,
|
||||
onQueryChange: (String) -> Unit,
|
||||
onOpenFile: (path: String) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.hapi
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
OutlinedTextField(
|
||||
value = state.query,
|
||||
onValueChange = onQueryChange,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
placeholder = { Text("Search files…") },
|
||||
leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
|
||||
singleLine = true,
|
||||
)
|
||||
|
||||
when {
|
||||
state.query.isBlank() -> CenteredHint("Type to search files in the session directory")
|
||||
state.loading -> CenteredProgress()
|
||||
state.error != null -> ErrorBanner(state.error)
|
||||
state.searched && state.results.isEmpty() -> CenteredHint("No files matched")
|
||||
else -> LazyColumn(modifier = Modifier.fillMaxSize()) {
|
||||
items(state.results, key = { it.fullPath }) { item ->
|
||||
SearchResultRow(item) { onOpenFile(item.fullPath) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SearchResultRow(item: FileSearchItem, onClick: () -> Unit) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = item.fullPath,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.MiddleEllipsis,
|
||||
)
|
||||
formatFileMetadata(item.size, item.modified)?.let {
|
||||
Text(text = it, fontSize = 11.sp, color = MaterialTheme.hapi.hint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ misc --
|
||||
|
||||
@Composable
|
||||
private fun ErrorBanner(message: String) {
|
||||
Text(
|
||||
text = message,
|
||||
fontSize = 12.sp,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.background(MaterialTheme.colorScheme.errorContainer)
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenteredProgress() {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(top = 48.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CenteredHint(text: String) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp, vertical = 48.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(text = text, fontSize = 13.sp, color = MaterialTheme.hapi.hint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.SolidColor
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.StrokeJoin
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.graphics.vector.addPathNodes
|
||||
import androidx.compose.ui.unit.dp
|
||||
import app.hapi.protocol.git.GitFileChange
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import kotlin.math.roundToLong
|
||||
|
||||
// Shared bits of the files feature UI: metadata formatting (web
|
||||
// `file-metadata.ts`), status-badge palette, and the folder glyph the chat
|
||||
// top bar and Browse tab share (the material core icon set has no folder).
|
||||
|
||||
/** `1.2 KB` / `640 B`; null when size is unknown (web `formatFileSize`). */
|
||||
internal fun formatFileSize(bytes: Long?): String? {
|
||||
if (bytes == null || bytes < 0) return null
|
||||
if (bytes < 1024) return "$bytes B"
|
||||
val units = arrayOf("KB", "MB", "GB", "TB")
|
||||
var value = bytes.toDouble()
|
||||
var unit = -1
|
||||
while (value >= 1024 && unit < units.size - 1) {
|
||||
value /= 1024
|
||||
unit += 1
|
||||
}
|
||||
val formatted = if (value >= 10) {
|
||||
value.roundToLong().toString()
|
||||
} else {
|
||||
String.format(Locale.US, "%.1f", value).removeSuffix(".0")
|
||||
}
|
||||
return "$formatted ${units[unit]}"
|
||||
}
|
||||
|
||||
/** `12/31/2026, 10:03 · 1.2 KB`-style joined metadata line (web `formatFileMetadata`). */
|
||||
internal fun formatFileMetadata(size: Long?, modified: Long?): String? {
|
||||
val time = modified?.let {
|
||||
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(it))
|
||||
}
|
||||
val parts = listOfNotNull(time, formatFileSize(size))
|
||||
return parts.joinToString(" · ").ifEmpty { null }
|
||||
}
|
||||
|
||||
/** Single status letter of the Changes list (web `StatusBadge`). */
|
||||
internal fun statusLetter(status: GitFileChange): String = when (status) {
|
||||
GitFileChange.ADDED -> "A"
|
||||
GitFileChange.DELETED -> "D"
|
||||
GitFileChange.RENAMED -> "R"
|
||||
GitFileChange.UNTRACKED -> "?"
|
||||
GitFileChange.CONFLICTED -> "U"
|
||||
GitFileChange.MODIFIED -> "M"
|
||||
}
|
||||
|
||||
/** Badge tint per status, tuned per theme (web `--app-git-*-color` vars). */
|
||||
internal fun statusColor(status: GitFileChange, dark: Boolean): Color = when (status) {
|
||||
GitFileChange.ADDED -> if (dark) Color(0xFF4CC38A) else Color(0xFF1A7F37)
|
||||
GitFileChange.DELETED, GitFileChange.CONFLICTED -> if (dark) Color(0xFFF47067) else Color(0xFFCF222E)
|
||||
GitFileChange.RENAMED -> if (dark) Color(0xFFDBAB0A) else Color(0xFF9A6700)
|
||||
GitFileChange.UNTRACKED -> if (dark) Color(0xFF8E8E93) else Color(0xFF6B7280)
|
||||
GitFileChange.MODIFIED -> if (dark) Color(0xFF539BF5) else Color(0xFF0969DA)
|
||||
}
|
||||
|
||||
private fun strokeIcon(name: String, pathData: String, strokeWidth: Float = 1.8f): ImageVector =
|
||||
ImageVector.Builder(
|
||||
name = name,
|
||||
defaultWidth = 24.dp,
|
||||
defaultHeight = 24.dp,
|
||||
viewportWidth = 24f,
|
||||
viewportHeight = 24f,
|
||||
).apply {
|
||||
addPath(
|
||||
pathData = addPathNodes(pathData),
|
||||
fill = null,
|
||||
// Any opaque stroke works: Icon() recolors via ColorFilter tint.
|
||||
stroke = SolidColor(Color.Black),
|
||||
strokeLineWidth = strokeWidth,
|
||||
strokeLineCap = StrokeCap.Round,
|
||||
strokeLineJoin = StrokeJoin.Round,
|
||||
)
|
||||
}.build()
|
||||
|
||||
/** Folder outline (the web `FolderIcon` path). */
|
||||
internal val FolderGlyph: ImageVector by lazy {
|
||||
strokeIcon("HapiFolder", "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z", 1.6f)
|
||||
}
|
||||
|
||||
/** Git branch glyph for the Changes header (the web `GitBranchIcon` paths). */
|
||||
internal val GitBranchGlyph: ImageVector by lazy {
|
||||
strokeIcon(
|
||||
"HapiGitBranch",
|
||||
"M6 3 L6 15 M6 15 a3 3 0 1 0 0.0001 0 M18 3 a3 3 0 1 0 0.0001 0 M18 9 a9 9 0 0 1 -9 9",
|
||||
2f,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import app.hapi.protocol.git.GitStatusFiles
|
||||
import app.hapi.protocol.git.GitStatusParser
|
||||
import app.hapi.protocol.wire.DirectoryEntry
|
||||
import app.hapi.protocol.wire.FileSearchItem
|
||||
import app.hapi.protocol.wire.GitCommandResponse
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.collectLatest
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// ------------------------------------------------------------- UI models --
|
||||
|
||||
/** Changes tab (web `useGitStatusFiles` + `files.tsx` Changes list). */
|
||||
data class ChangesUiState(
|
||||
val loading: Boolean = true,
|
||||
/** null after load ⇒ git unavailable for this session (not a repo / no path). */
|
||||
val status: GitStatusFiles? = null,
|
||||
/** Banner text: status failure, or partial numstat failures. */
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** One row of the flattened Browse tree ([FilesViewModel.browse]). */
|
||||
sealed interface BrowseRow {
|
||||
val depth: Int
|
||||
|
||||
data class Dir(
|
||||
/** Session-root-relative path (`src/app`). */
|
||||
val path: String,
|
||||
val name: String,
|
||||
override val depth: Int,
|
||||
val expanded: Boolean,
|
||||
) : BrowseRow
|
||||
|
||||
data class File(
|
||||
val path: String,
|
||||
val name: String,
|
||||
override val depth: Int,
|
||||
val size: Long?,
|
||||
val modified: Long?,
|
||||
) : BrowseRow
|
||||
|
||||
/** Placeholder while a directory listing is in flight. */
|
||||
data class Loading(val parentPath: String, override val depth: Int) : BrowseRow
|
||||
|
||||
/** Inline listing failure for one directory (web `DirectoryErrorRow`). */
|
||||
data class Error(val parentPath: String, override val depth: Int, val message: String) : BrowseRow
|
||||
}
|
||||
|
||||
data class BrowseUiState(
|
||||
val rows: List<BrowseRow> = emptyList(),
|
||||
val showHidden: Boolean = false,
|
||||
)
|
||||
|
||||
/** Search tab (debounced `GET /files?query=`). */
|
||||
data class SearchUiState(
|
||||
val query: String = "",
|
||||
val loading: Boolean = false,
|
||||
val results: List<FileSearchItem> = emptyList(),
|
||||
val error: String? = null,
|
||||
/** True once a search for the current query completed (drives the empty state). */
|
||||
val searched: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Files screen state: three independent tabs over the session's git/files
|
||||
* endpoints. Changes ports `useGitStatusFiles` (status + both numstat sides
|
||||
* merged in `:core:protocol`'s `GitStatusParser.buildGitStatusFiles`); Browse
|
||||
* is a lazily-expanded directory tree flattened to rows (dirs-first name sort
|
||||
* like web `directory-sort.ts`, plus an Android-only hidden-file toggle);
|
||||
* Search debounces the ripgrep-backed `/files` query.
|
||||
*/
|
||||
class FilesViewModel(
|
||||
private val sessionId: String,
|
||||
private val gateway: FilesGateway,
|
||||
private val scope: CoroutineScope,
|
||||
private val searchDebounceMs: Long = SEARCH_DEBOUNCE_MS,
|
||||
) {
|
||||
private val changesState = MutableStateFlow(ChangesUiState())
|
||||
val changes: StateFlow<ChangesUiState> = changesState.asStateFlow()
|
||||
|
||||
private val browseState = MutableStateFlow(BrowseUiState())
|
||||
val browse: StateFlow<BrowseUiState> = browseState.asStateFlow()
|
||||
|
||||
private val searchState = MutableStateFlow(SearchUiState())
|
||||
val search: StateFlow<SearchUiState> = searchState.asStateFlow()
|
||||
|
||||
/** null = never requested; entries null while loading. */
|
||||
private data class DirNode(val entries: List<DirectoryEntry>? = null, val error: String? = null) {
|
||||
val loading: Boolean get() = entries == null && error == null
|
||||
}
|
||||
|
||||
private val nodes = MutableStateFlow<Map<String, DirNode>>(emptyMap())
|
||||
private val expanded = MutableStateFlow<Set<String>>(emptySet())
|
||||
private val queryInput = MutableStateFlow("")
|
||||
private var started = false
|
||||
|
||||
fun start() {
|
||||
if (started) return
|
||||
started = true
|
||||
refreshChanges()
|
||||
loadDirectory(ROOT)
|
||||
scope.launch {
|
||||
queryInput.collectLatest { query ->
|
||||
if (query.isBlank()) {
|
||||
searchState.value = SearchUiState(query = query)
|
||||
return@collectLatest
|
||||
}
|
||||
delay(searchDebounceMs)
|
||||
runSearch(query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- changes --
|
||||
|
||||
fun refreshChanges() {
|
||||
scope.launch { loadChanges() }
|
||||
}
|
||||
|
||||
private suspend fun loadChanges() {
|
||||
changesState.update { it.copy(loading = true, error = null) }
|
||||
|
||||
val statusResult = try {
|
||||
gateway.gitStatus(sessionId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
changesState.value = ChangesUiState(
|
||||
loading = false,
|
||||
status = null,
|
||||
error = e.message ?: "Git status unavailable",
|
||||
)
|
||||
return
|
||||
}
|
||||
if (!statusResult.success) {
|
||||
changesState.value = ChangesUiState(
|
||||
loading = false,
|
||||
status = null,
|
||||
error = statusResult.error ?: statusResult.stderr ?: "Git status unavailable",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Both numstat sides in parallel; a failed side degrades to zero
|
||||
// counts plus a banner note, never a failed tab (web parity).
|
||||
val (unstagedResult, stagedResult) = coroutineScope {
|
||||
val unstaged = async { runCatching { gateway.gitDiffNumstat(sessionId, staged = false) } }
|
||||
val staged = async { runCatching { gateway.gitDiffNumstat(sessionId, staged = true) } }
|
||||
unstaged.await() to staged.await()
|
||||
}
|
||||
|
||||
val unstaged = unstagedResult.getOrNull()
|
||||
val staged = stagedResult.getOrNull()
|
||||
val status = GitStatusParser.buildGitStatusFiles(
|
||||
statusOutput = statusResult.stdout.orEmpty(),
|
||||
unstagedDiffOutput = if (unstaged?.success == true) unstaged.stdout.orEmpty() else "",
|
||||
stagedDiffOutput = if (staged?.success == true) staged.stdout.orEmpty() else "",
|
||||
)
|
||||
|
||||
val errors = buildList {
|
||||
if (unstaged?.success != true) {
|
||||
add("Unstaged diff unavailable: ${describeNumstatFailure(unstaged, unstagedResult.exceptionOrNull())}")
|
||||
}
|
||||
if (staged?.success != true) {
|
||||
add("Staged diff unavailable: ${describeNumstatFailure(staged, stagedResult.exceptionOrNull())}")
|
||||
}
|
||||
}
|
||||
|
||||
changesState.value = ChangesUiState(
|
||||
loading = false,
|
||||
status = status,
|
||||
error = errors.joinToString(" ").ifEmpty { null },
|
||||
)
|
||||
}
|
||||
|
||||
private fun describeNumstatFailure(
|
||||
result: GitCommandResponse?,
|
||||
exception: Throwable?,
|
||||
): String = result?.error ?: result?.stderr ?: exception?.message ?: "unknown error"
|
||||
|
||||
// -------------------------------------------------------------- browse --
|
||||
|
||||
fun toggleDirectory(path: String) {
|
||||
val wasExpanded = path in expanded.value
|
||||
expanded.update { if (wasExpanded) it - path else it + path }
|
||||
if (!wasExpanded && nodes.value[path] == null) {
|
||||
loadDirectory(path)
|
||||
} else {
|
||||
rebuildBrowse()
|
||||
}
|
||||
}
|
||||
|
||||
fun setShowHidden(showHidden: Boolean) {
|
||||
browseState.update { it.copy(showHidden = showHidden) }
|
||||
rebuildBrowse()
|
||||
}
|
||||
|
||||
/** Re-lists the root and every expanded directory. */
|
||||
fun refreshBrowse() {
|
||||
loadDirectory(ROOT)
|
||||
for (path in expanded.value) loadDirectory(path)
|
||||
}
|
||||
|
||||
private fun loadDirectory(path: String) {
|
||||
nodes.update { it + (path to DirNode()) }
|
||||
rebuildBrowse()
|
||||
scope.launch {
|
||||
val node = try {
|
||||
val response = gateway.listDirectory(sessionId, path.ifEmpty { null })
|
||||
if (response.success) {
|
||||
DirNode(entries = response.entries.orEmpty())
|
||||
} else {
|
||||
DirNode(error = response.error ?: "Failed to list directory")
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
DirNode(error = e.message ?: "Failed to list directory")
|
||||
}
|
||||
nodes.update { it + (path to node) }
|
||||
rebuildBrowse()
|
||||
}
|
||||
}
|
||||
|
||||
private fun rebuildBrowse() {
|
||||
val rows = mutableListOf<BrowseRow>()
|
||||
appendChildren(ROOT, 0, rows)
|
||||
browseState.update { it.copy(rows = rows) }
|
||||
}
|
||||
|
||||
private fun appendChildren(path: String, depth: Int, out: MutableList<BrowseRow>) {
|
||||
val node = nodes.value[path]
|
||||
when {
|
||||
node == null || node.loading -> out += BrowseRow.Loading(path, depth)
|
||||
node.error != null -> out += BrowseRow.Error(path, depth, node.error)
|
||||
else -> {
|
||||
val showHidden = browseState.value.showHidden
|
||||
val visible = node.entries.orEmpty()
|
||||
.filter { showHidden || !it.name.startsWith(".") }
|
||||
.sortedWith(DIRS_FIRST_BY_NAME)
|
||||
for (entry in visible) {
|
||||
val childPath = if (path.isEmpty()) entry.name else "$path/${entry.name}"
|
||||
when (entry.type) {
|
||||
"directory" -> {
|
||||
val isExpanded = childPath in expanded.value
|
||||
out += BrowseRow.Dir(childPath, entry.name, depth, isExpanded)
|
||||
if (isExpanded) appendChildren(childPath, depth + 1, out)
|
||||
}
|
||||
"file" -> out += BrowseRow.File(childPath, entry.name, depth, entry.size, entry.modified)
|
||||
// 'other' entries (sockets, links, …) are dropped, like the web tree.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- search --
|
||||
|
||||
fun setSearchQuery(query: String) {
|
||||
searchState.update { it.copy(query = query) }
|
||||
queryInput.value = query
|
||||
}
|
||||
|
||||
fun refreshSearch() {
|
||||
val query = queryInput.value
|
||||
if (query.isBlank()) return
|
||||
scope.launch { runSearch(query) }
|
||||
}
|
||||
|
||||
private suspend fun runSearch(query: String) {
|
||||
searchState.update { it.copy(loading = true, error = null) }
|
||||
try {
|
||||
val response = gateway.searchFiles(sessionId, query, SEARCH_LIMIT)
|
||||
searchState.update {
|
||||
if (response.success) {
|
||||
it.copy(loading = false, results = response.files.orEmpty(), error = null, searched = true)
|
||||
} else {
|
||||
it.copy(
|
||||
loading = false,
|
||||
results = emptyList(),
|
||||
error = response.error ?: "Failed to search files",
|
||||
searched = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
searchState.update {
|
||||
it.copy(
|
||||
loading = false,
|
||||
results = emptyList(),
|
||||
error = e.message ?: "Failed to search files",
|
||||
searched = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val ROOT = ""
|
||||
const val SEARCH_DEBOUNCE_MS = 300L
|
||||
|
||||
/** Web default limit (`useSessionFileSearch`). */
|
||||
const val SEARCH_LIMIT = 200
|
||||
|
||||
/** Dirs first, then case-insensitive name — web `sortDirectoryEntries` default. */
|
||||
val DIRS_FIRST_BY_NAME: Comparator<DirectoryEntry> =
|
||||
compareBy<DirectoryEntry> { it.type != "directory" }
|
||||
.thenBy(String.CASE_INSENSITIVE_ORDER) { it.name }
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import app.hapi.protocol.wire.FileReadResponse
|
||||
import app.hapi.protocol.wire.GitCommandResponse
|
||||
import java.util.Base64
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertIs
|
||||
import kotlin.test.assertTrue
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.TestScope
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.runTest
|
||||
|
||||
class FileViewerViewModelTest {
|
||||
|
||||
private fun TestScope.buildViewModel(
|
||||
gateway: FakeFilesGateway,
|
||||
path: String = "src/app.ts",
|
||||
staged: Boolean? = null,
|
||||
mode: ViewerMode? = null,
|
||||
line: Int? = null,
|
||||
): FileViewerViewModel = FileViewerViewModel(
|
||||
sessionId = "s1",
|
||||
path = path,
|
||||
initialStaged = staged,
|
||||
initialMode = mode,
|
||||
focusLine = line,
|
||||
gateway = gateway,
|
||||
scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)),
|
||||
)
|
||||
|
||||
private fun b64(text: String): String = Base64.getEncoder().encodeToString(text.toByteArray())
|
||||
|
||||
private val sampleDiff = """
|
||||
diff --git a/src/app.ts b/src/app.ts
|
||||
--- a/src/app.ts
|
||||
+++ b/src/app.ts
|
||||
@@ -1,2 +1,2 @@
|
||||
keep
|
||||
-old
|
||||
+new
|
||||
""".trimIndent()
|
||||
|
||||
@Test
|
||||
fun `parses the diff and stays in diff mode`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = sampleDiff)
|
||||
readFileResult = FileReadResponse(success = true, content = b64("keep\nnew\n"))
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val state = viewModel.state.value
|
||||
assertEquals(ViewerMode.DIFF, state.mode)
|
||||
val diff = assertIs<DiffUiState.Ready>(state.diff)
|
||||
assertEquals("src/app.ts", diff.files.single().displayPath)
|
||||
assertEquals(1, diff.files.single().additions)
|
||||
assertEquals(listOf<Pair<String, Boolean?>>("src/app.ts" to false), gateway.diffFileCalls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty diff auto-falls back to file mode`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
readFileResult = FileReadResponse(success = true, content = b64("hello"))
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val state = viewModel.state.value
|
||||
assertEquals(ViewerMode.FILE, state.mode)
|
||||
assertEquals(DiffUiState.Empty, state.diff)
|
||||
val text = assertIs<FileContentUiState.Text>(state.content)
|
||||
assertEquals("hello", text.text)
|
||||
assertEquals("ts", text.language)
|
||||
assertEquals(false, text.isMarkdown)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `failed diff auto-falls back to file mode with message kept`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = false, error = "not a repo")
|
||||
readFileResult = FileReadResponse(success = true, content = b64("x"))
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(ViewerMode.FILE, viewModel.state.value.mode)
|
||||
assertEquals("not a repo", assertIs<DiffUiState.Failed>(viewModel.state.value.diff).message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `explicit file mode from the route disables auto behavior`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = sampleDiff)
|
||||
readFileResult = FileReadResponse(success = true, content = b64("body"))
|
||||
}
|
||||
val viewModel = buildViewModel(gateway, mode = ViewerMode.FILE, line = 12)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(ViewerMode.FILE, viewModel.state.value.mode)
|
||||
assertEquals(12, viewModel.state.value.focusLine)
|
||||
// The diff still loaded, so the user can flip to it.
|
||||
assertIs<DiffUiState.Ready>(viewModel.state.value.diff)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `staged toggle reloads the diff for the other side`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = sampleDiff)
|
||||
readFileResult = FileReadResponse(success = true, content = b64("x"))
|
||||
}
|
||||
val viewModel = buildViewModel(gateway, staged = false)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
viewModel.setStaged(true)
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(
|
||||
listOf<Pair<String, Boolean?>>("src/app.ts" to false, "src/app.ts" to true),
|
||||
gateway.diffFileCalls,
|
||||
)
|
||||
assertTrue(viewModel.state.value.staged)
|
||||
// Same side again is a no-op.
|
||||
viewModel.setStaged(true)
|
||||
advanceUntilIdle()
|
||||
assertEquals(2, gateway.diffFileCalls.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `markdown files flag markdown and default to preview`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
readFileResult = FileReadResponse(success = true, content = b64("# Title"), size = 7, modified = 123L)
|
||||
}
|
||||
val viewModel = buildViewModel(gateway, path = "README.md")
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val state = viewModel.state.value
|
||||
assertTrue(assertIs<FileContentUiState.Text>(state.content).isMarkdown)
|
||||
assertTrue(state.markdownPreview)
|
||||
assertEquals(7L, state.sizeBytes)
|
||||
assertEquals(123L, state.modifiedAt)
|
||||
|
||||
viewModel.setMarkdownPreview(false)
|
||||
assertEquals(false, viewModel.state.value.markdownPreview)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `image extensions decode to image content`() = runTest {
|
||||
val bytes = byteArrayOf(1, 2, 3, 4)
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
readFileResult = FileReadResponse(
|
||||
success = true,
|
||||
content = Base64.getEncoder().encodeToString(bytes),
|
||||
)
|
||||
}
|
||||
val viewModel = buildViewModel(gateway, path = "assets/logo.PNG")
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val image = assertIs<FileContentUiState.Image>(viewModel.state.value.content)
|
||||
assertEquals("image/png", image.mimeType)
|
||||
assertTrue(bytes.contentEquals(image.bytes))
|
||||
assertEquals(ViewerMode.FILE, viewModel.state.value.mode)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `NUL bytes classify as binary`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
readFileResult = FileReadResponse(
|
||||
success = true,
|
||||
content = Base64.getEncoder().encodeToString(byteArrayOf(104, 105, 0, 106)),
|
||||
)
|
||||
}
|
||||
val viewModel = buildViewModel(gateway, path = "blob.bin")
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(FileContentUiState.Binary, viewModel.state.value.content)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `read failure surfaces its message`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
readFileResult = FileReadResponse(success = false, error = "File not found")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("File not found", assertIs<FileContentUiState.Failed>(viewModel.state.value.content).message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `invalid base64 classifies as binary`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
readFileResult = FileReadResponse(success = true, content = "%%%not-base64%%%")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(FileContentUiState.Binary, viewModel.state.value.content)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
|
||||
|
||||
package app.hapi.companion.feature.files
|
||||
|
||||
import app.hapi.protocol.git.GitFileChange
|
||||
import app.hapi.protocol.wire.DirectoryEntry
|
||||
import app.hapi.protocol.wire.FileReadResponse
|
||||
import app.hapi.protocol.wire.FileSearchItem
|
||||
import app.hapi.protocol.wire.FileSearchResponse
|
||||
import app.hapi.protocol.wire.GitCommandResponse
|
||||
import app.hapi.protocol.wire.ListDirectoryResponse
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.TestScope
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
import kotlinx.coroutines.test.advanceUntilIdle
|
||||
import kotlinx.coroutines.test.runTest
|
||||
|
||||
// ------------------------------------------------------------------ fakes --
|
||||
|
||||
internal class FakeFilesGateway : FilesGateway {
|
||||
var statusResult = GitCommandResponse(success = true, stdout = "")
|
||||
var unstagedNumstat = GitCommandResponse(success = true, stdout = "")
|
||||
var stagedNumstat = GitCommandResponse(success = true, stdout = "")
|
||||
var diffFileResult = GitCommandResponse(success = true, stdout = "")
|
||||
var readFileResult = FileReadResponse(success = true, content = "")
|
||||
var searchResult = FileSearchResponse(success = true, files = emptyList())
|
||||
var directories: MutableMap<String?, ListDirectoryResponse> = mutableMapOf()
|
||||
var throwOnStatus: Exception? = null
|
||||
|
||||
val diffFileCalls = mutableListOf<Pair<String, Boolean?>>()
|
||||
val searchCalls = mutableListOf<Pair<String, Int>>()
|
||||
val listDirectoryCalls = mutableListOf<String?>()
|
||||
val numstatCalls = mutableListOf<Boolean>()
|
||||
|
||||
override suspend fun gitStatus(sessionId: String): GitCommandResponse {
|
||||
throwOnStatus?.let { throw it }
|
||||
return statusResult
|
||||
}
|
||||
|
||||
override suspend fun gitDiffNumstat(sessionId: String, staged: Boolean): GitCommandResponse {
|
||||
numstatCalls += staged
|
||||
return if (staged) stagedNumstat else unstagedNumstat
|
||||
}
|
||||
|
||||
override suspend fun gitDiffFile(sessionId: String, path: String, staged: Boolean?): GitCommandResponse {
|
||||
diffFileCalls += path to staged
|
||||
return diffFileResult
|
||||
}
|
||||
|
||||
override suspend fun readFile(sessionId: String, path: String): FileReadResponse = readFileResult
|
||||
|
||||
override suspend fun searchFiles(sessionId: String, query: String, limit: Int): FileSearchResponse {
|
||||
searchCalls += query to limit
|
||||
return searchResult
|
||||
}
|
||||
|
||||
override suspend fun listDirectory(sessionId: String, path: String?): ListDirectoryResponse {
|
||||
listDirectoryCalls += path
|
||||
return directories[path] ?: ListDirectoryResponse(success = true, entries = emptyList())
|
||||
}
|
||||
}
|
||||
|
||||
class FilesViewModelTest {
|
||||
|
||||
private fun TestScope.buildViewModel(gateway: FakeFilesGateway): FilesViewModel =
|
||||
FilesViewModel(
|
||||
sessionId = "s1",
|
||||
gateway = gateway,
|
||||
scope = CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)),
|
||||
)
|
||||
|
||||
// ------------------------------------------------------------- changes --
|
||||
|
||||
private val porcelain = listOf(
|
||||
"# branch.head main",
|
||||
"1 M. N... 100644 100644 100644 aaaaaaaa bbbbbbbb staged.txt",
|
||||
"1 .M N... 100644 100644 100644 cccccccc dddddddd unstaged.txt",
|
||||
"1 MM N... 100644 100644 100644 eeeeeeee ffffffff both.txt",
|
||||
"? fresh.txt",
|
||||
).joinToString("\n")
|
||||
|
||||
@Test
|
||||
fun `changes tab merges status with both numstat sides`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
statusResult = GitCommandResponse(success = true, stdout = porcelain)
|
||||
unstagedNumstat = GitCommandResponse(success = true, stdout = "3\t1\tunstaged.txt\n2\t2\tboth.txt")
|
||||
stagedNumstat = GitCommandResponse(success = true, stdout = "5\t0\tstaged.txt\n1\t0\tboth.txt")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val state = viewModel.changes.value
|
||||
assertEquals(false, state.loading)
|
||||
assertNull(state.error)
|
||||
val status = assertNotNull(state.status)
|
||||
assertEquals("main", status.branch)
|
||||
assertEquals(listOf(true, false).sorted(), gateway.numstatCalls.sorted())
|
||||
|
||||
// Staged side takes counts from the staged numstat.
|
||||
assertEquals(listOf("staged.txt", "both.txt"), status.stagedFiles.map { it.fullPath })
|
||||
assertEquals(5, status.stagedFiles[0].linesAdded)
|
||||
assertEquals(1, status.stagedFiles[1].linesAdded)
|
||||
|
||||
// Unstaged side: modified + both + untracked appended last.
|
||||
assertEquals(listOf("unstaged.txt", "both.txt", "fresh.txt"), status.unstagedFiles.map { it.fullPath })
|
||||
assertEquals(3, status.unstagedFiles[0].linesAdded)
|
||||
assertEquals(2, status.unstagedFiles[1].linesRemoved)
|
||||
assertEquals(GitFileChange.UNTRACKED, status.unstagedFiles[2].status)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `status failure surfaces error with no status`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
statusResult = GitCommandResponse(success = false, error = "Session path not available")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val state = viewModel.changes.value
|
||||
assertNull(state.status)
|
||||
assertEquals("Session path not available", state.error)
|
||||
assertTrue(gateway.numstatCalls.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `numstat failure degrades to zero counts plus banner`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
statusResult = GitCommandResponse(success = true, stdout = porcelain)
|
||||
unstagedNumstat = GitCommandResponse(success = false, stderr = "boom")
|
||||
stagedNumstat = GitCommandResponse(success = true, stdout = "5\t0\tstaged.txt")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val state = viewModel.changes.value
|
||||
val status = assertNotNull(state.status)
|
||||
assertEquals(0, status.unstagedFiles[0].linesAdded)
|
||||
assertEquals(5, status.stagedFiles[0].linesAdded)
|
||||
assertEquals("Unstaged diff unavailable: boom", state.error)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `transport failure on status maps to error state`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply { throwOnStatus = IllegalStateException("offline") }
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
assertNull(viewModel.changes.value.status)
|
||||
assertEquals("offline", viewModel.changes.value.error)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- browse --
|
||||
|
||||
private fun dir(name: String) = DirectoryEntry(name = name, type = "directory")
|
||||
private fun file(name: String, size: Long? = null) = DirectoryEntry(name = name, type = "file", size = size)
|
||||
|
||||
@Test
|
||||
fun `root listing sorts dirs first and hides dot entries by default`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
directories[null] = ListDirectoryResponse(
|
||||
success = true,
|
||||
entries = listOf(
|
||||
file("zeta.txt"),
|
||||
dir("src"),
|
||||
file(".env"),
|
||||
dir(".git"),
|
||||
file("Alpha.md"),
|
||||
DirectoryEntry(name = "weird-socket", type = "other"),
|
||||
),
|
||||
)
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val rows = viewModel.browse.value.rows
|
||||
assertEquals(listOf("src", "Alpha.md", "zeta.txt"), rows.map { rowName(it) })
|
||||
assertTrue(rows[0] is BrowseRow.Dir)
|
||||
|
||||
viewModel.setShowHidden(true)
|
||||
assertEquals(
|
||||
listOf(".git", "src", ".env", "Alpha.md", "zeta.txt"),
|
||||
viewModel.browse.value.rows.map { rowName(it) },
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `expanding a directory lazily loads it exactly once`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
directories[null] = ListDirectoryResponse(success = true, entries = listOf(dir("src")))
|
||||
directories["src"] = ListDirectoryResponse(success = true, entries = listOf(file("app.ts", size = 10)))
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
viewModel.toggleDirectory("src")
|
||||
advanceUntilIdle()
|
||||
|
||||
var rows = viewModel.browse.value.rows
|
||||
assertEquals(listOf("src", "app.ts"), rows.map { rowName(it) })
|
||||
assertEquals(1, (rows[1] as BrowseRow.File).depth)
|
||||
assertEquals("src/app.ts", (rows[1] as BrowseRow.File).path)
|
||||
|
||||
// Collapse and re-expand: entries come from the cache, no second call.
|
||||
viewModel.toggleDirectory("src")
|
||||
viewModel.toggleDirectory("src")
|
||||
advanceUntilIdle()
|
||||
rows = viewModel.browse.value.rows
|
||||
assertEquals(listOf("src", "app.ts"), rows.map { rowName(it) })
|
||||
assertEquals(listOf(null, "src"), gateway.listDirectoryCalls)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `directory failure renders an inline error row`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
directories[null] = ListDirectoryResponse(success = false, error = "denied")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
val row = viewModel.browse.value.rows.single() as BrowseRow.Error
|
||||
assertEquals("denied", row.message)
|
||||
}
|
||||
|
||||
private fun rowName(row: BrowseRow): String = when (row) {
|
||||
is BrowseRow.Dir -> row.name
|
||||
is BrowseRow.File -> row.name
|
||||
is BrowseRow.Loading -> "<loading>"
|
||||
is BrowseRow.Error -> "<error>"
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- search --
|
||||
|
||||
@Test
|
||||
fun `search debounces rapid typing into a single request`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
searchResult = FileSearchResponse(
|
||||
success = true,
|
||||
files = listOf(
|
||||
FileSearchItem(fileName = "app.ts", filePath = "src", fullPath = "src/app.ts", fileType = "file"),
|
||||
),
|
||||
)
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
viewModel.setSearchQuery("a")
|
||||
advanceTimeBy(100)
|
||||
viewModel.setSearchQuery("ap")
|
||||
advanceTimeBy(100)
|
||||
viewModel.setSearchQuery("app")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals(listOf("app" to 200), gateway.searchCalls)
|
||||
val state = viewModel.search.value
|
||||
assertEquals("app", state.query)
|
||||
assertTrue(state.searched)
|
||||
assertEquals(listOf("src/app.ts"), state.results.map { it.fullPath })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `clearing the query resets results without a request`() = runTest {
|
||||
val gateway = FakeFilesGateway()
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
viewModel.setSearchQuery("app")
|
||||
advanceUntilIdle()
|
||||
assertEquals(1, gateway.searchCalls.size)
|
||||
|
||||
viewModel.setSearchQuery("")
|
||||
advanceUntilIdle()
|
||||
assertEquals(1, gateway.searchCalls.size)
|
||||
assertTrue(viewModel.search.value.results.isEmpty())
|
||||
assertEquals(false, viewModel.search.value.searched)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `search failure surfaces the error`() = runTest {
|
||||
val gateway = FakeFilesGateway().apply {
|
||||
searchResult = FileSearchResponse(success = false, error = "ripgrep missing")
|
||||
}
|
||||
val viewModel = buildViewModel(gateway)
|
||||
viewModel.start()
|
||||
advanceUntilIdle()
|
||||
|
||||
viewModel.setSearchQuery("x")
|
||||
advanceUntilIdle()
|
||||
|
||||
assertEquals("ripgrep missing", viewModel.search.value.error)
|
||||
assertTrue(viewModel.search.value.results.isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,12 @@ import app.hapi.protocol.wire.CodexModelsResponse
|
||||
import app.hapi.protocol.wire.DeleteUploadRequest
|
||||
import app.hapi.protocol.wire.DeleteUploadResponse
|
||||
import app.hapi.protocol.wire.DenyPermissionRequest
|
||||
import app.hapi.protocol.wire.FileReadResponse
|
||||
import app.hapi.protocol.wire.FileSearchResponse
|
||||
import app.hapi.protocol.wire.GitCommandResponse
|
||||
import app.hapi.protocol.wire.HapiJson
|
||||
import app.hapi.protocol.wire.HubHealthResponse
|
||||
import app.hapi.protocol.wire.ListDirectoryResponse
|
||||
import app.hapi.protocol.wire.MachineListDirectoryRequest
|
||||
import app.hapi.protocol.wire.MachineListDirectoryResponse
|
||||
import app.hapi.protocol.wire.MachinePathsExistsRequest
|
||||
@@ -477,6 +481,55 @@ class HapiApi(
|
||||
suspend fun getMachineCodexModels(machineId: String): CodexModelsResponse =
|
||||
request("GET", url("api", "machines", machineId, "codex-models").build())
|
||||
|
||||
// --------------------------------------------------------- git & files --
|
||||
// RAW-stdout contract (`docs/api/client-contract/rest.md` "Git & files"):
|
||||
// the hub relays git output verbatim inside `GitCommandResponse.stdout`;
|
||||
// parsing happens client-side in `app.hapi.protocol.git`. All six are
|
||||
// RPC-wrapped — check `success` (HTTP 200 + `{success:false}` is normal).
|
||||
|
||||
/** `GET /api/sessions/:id/git-status` — raw `git status --porcelain=v2 --branch` stdout. */
|
||||
suspend fun getGitStatus(sessionId: String): GitCommandResponse =
|
||||
request("GET", url("api", "sessions", sessionId, "git-status").build())
|
||||
|
||||
/** `GET /api/sessions/:id/git-diff-numstat?staged=` — raw `git diff --numstat` stdout. */
|
||||
suspend fun getGitDiffNumstat(sessionId: String, staged: Boolean): GitCommandResponse {
|
||||
val target = url("api", "sessions", sessionId, "git-diff-numstat")
|
||||
.addQueryParameter("staged", staged.toString())
|
||||
return request("GET", target.build())
|
||||
}
|
||||
|
||||
/** `GET /api/sessions/:id/git-diff-file?path=&staged=` — raw unified diff for one file. */
|
||||
suspend fun getGitDiffFile(sessionId: String, path: String, staged: Boolean? = null): GitCommandResponse {
|
||||
val target = url("api", "sessions", sessionId, "git-diff-file")
|
||||
.addQueryParameter("path", path)
|
||||
.apply { staged?.let { addQueryParameter("staged", it.toString()) } }
|
||||
return request("GET", target.build())
|
||||
}
|
||||
|
||||
/** `GET /api/sessions/:id/file?path=` — `content` is base64; decode before display. */
|
||||
suspend fun readSessionFile(sessionId: String, path: String): FileReadResponse {
|
||||
val target = url("api", "sessions", sessionId, "file")
|
||||
.addQueryParameter("path", path)
|
||||
return request("GET", target.build())
|
||||
}
|
||||
|
||||
/** `GET /api/sessions/:id/files?query=&limit=` — ripgrep-backed search (limit 1–500, default 200). */
|
||||
suspend fun searchSessionFiles(sessionId: String, query: String, limit: Int? = null): FileSearchResponse {
|
||||
val target = url("api", "sessions", sessionId, "files").apply {
|
||||
if (query.isNotEmpty()) addQueryParameter("query", query)
|
||||
limit?.let { addQueryParameter("limit", it.toString()) }
|
||||
}
|
||||
return request("GET", target.build())
|
||||
}
|
||||
|
||||
/** `GET /api/sessions/:id/directory?path=` — omitted path lists the session root. */
|
||||
suspend fun listSessionDirectory(sessionId: String, path: String? = null): ListDirectoryResponse {
|
||||
val target = url("api", "sessions", sessionId, "directory").apply {
|
||||
if (!path.isNullOrEmpty()) addQueryParameter("path", path)
|
||||
}
|
||||
return request("GET", target.build())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- visibility --
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
package app.hapi.protocol.git
|
||||
|
||||
/**
|
||||
* Parser for the raw `git status --porcelain=v2 --branch` stdout the hub
|
||||
* relays verbatim in `GET /api/sessions/:id/git-status`
|
||||
* (`GitCommandResponse.stdout`). Behavioral twin of
|
||||
* `parseStatusSummaryV2`/`buildGitStatusFiles` in `web/src/lib/gitParsers.ts`
|
||||
* — including its quirks, which the Kotlin port reproduces on purpose so both
|
||||
* clients render identical lists:
|
||||
*
|
||||
* - Rename/copy (`2`) records assign the first tab-separated path to [GitFileEntryV2.from]
|
||||
* and the second to [GitFileEntryV2.path] (the web parser's reading of the
|
||||
* `<path><sep><origPath>` payload).
|
||||
* - Unmerged (`u`) records surface in both staged and unstaged lists when both
|
||||
* XY letters are set (e.g. `UU`).
|
||||
* - Untracked entries ending in `/` are kept in [GitStatusSummary.notAdded] but
|
||||
* dropped from the merged [GitStatusFiles].
|
||||
*/
|
||||
|
||||
/** One `1 ` / `2 ` / `u ` record: XY letters + path(s). */
|
||||
data class GitFileEntryV2(
|
||||
val path: String,
|
||||
/** Index (staged) status letter; `.` = unmodified. */
|
||||
val index: String,
|
||||
/** Working-tree status letter; `.` = unmodified. */
|
||||
val workingDir: String,
|
||||
/** Pre-image path of a rename/copy record. */
|
||||
val from: String? = null,
|
||||
)
|
||||
|
||||
/** `# branch.*` header lines. */
|
||||
data class GitBranchInfo(
|
||||
val oid: String? = null,
|
||||
/** Branch name, or `(detached)` / `(initial)`. */
|
||||
val head: String? = null,
|
||||
val upstream: String? = null,
|
||||
val ahead: Int? = null,
|
||||
val behind: Int? = null,
|
||||
)
|
||||
|
||||
data class GitStatusSummary(
|
||||
val files: List<GitFileEntryV2>,
|
||||
/** `? ` untracked paths (directories keep their trailing `/`). */
|
||||
val notAdded: List<String>,
|
||||
/** `! ` ignored paths (only present with `--ignored`). */
|
||||
val ignored: List<String>,
|
||||
val branch: GitBranchInfo,
|
||||
)
|
||||
|
||||
/** Display status derived from one XY letter (`getFileStatus` in the web parser). */
|
||||
enum class GitFileChange { MODIFIED, ADDED, DELETED, RENAMED, UNTRACKED, CONFLICTED }
|
||||
|
||||
/** One row of the Changes list (web `GitFileStatus`, `web/src/types/api.ts`). */
|
||||
data class GitFileStatus(
|
||||
/** Last path segment (`app.ts`). */
|
||||
val fileName: String,
|
||||
/** Directory part without trailing slash; empty at the repo root. */
|
||||
val filePath: String,
|
||||
val fullPath: String,
|
||||
val status: GitFileChange,
|
||||
val isStaged: Boolean,
|
||||
val linesAdded: Int,
|
||||
val linesRemoved: Int,
|
||||
val oldPath: String? = null,
|
||||
)
|
||||
|
||||
/** Merged status + numstat model the Changes tab renders (web `GitStatusFiles`). */
|
||||
data class GitStatusFiles(
|
||||
val stagedFiles: List<GitFileStatus>,
|
||||
val unstagedFiles: List<GitFileStatus>,
|
||||
/** Branch name; null for detached HEAD / unborn branch. */
|
||||
val branch: String?,
|
||||
val totalStaged: Int,
|
||||
val totalUnstaged: Int,
|
||||
)
|
||||
|
||||
object GitStatusParser {
|
||||
|
||||
private val BRANCH_OID = Regex("""^# branch\.oid (.+)$""")
|
||||
private val BRANCH_HEAD = Regex("""^# branch\.head (.+)$""")
|
||||
private val BRANCH_UPSTREAM = Regex("""^# branch\.upstream (.+)$""")
|
||||
private val BRANCH_AB = Regex("""^# branch\.ab \+(\d+) -(\d+)$""")
|
||||
|
||||
private val ORDINARY_CHANGE =
|
||||
Regex("""^1 (.)(.) (.{4}) (\d{6}) (\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) (.+)$""")
|
||||
private val RENAME_COPY =
|
||||
Regex("""^2 (.)(.) (.{4}) (\d{6}) (\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) ([RC])(\d{1,3}) (.+)\t(.+)$""")
|
||||
private val UNMERGED =
|
||||
Regex("""^u (.)(.) (.{4}) (\d{6}) (\d{6}) (\d{6}) (\d{6}) ([0-9a-f]+) ([0-9a-f]+) ([0-9a-f]+) (.+)$""")
|
||||
private val UNTRACKED = Regex("""^\? (.+)$""")
|
||||
private val IGNORED = Regex("""^! (.+)$""")
|
||||
|
||||
/** Porcelain-v2 stdout → structured summary (`parseStatusSummaryV2`). */
|
||||
fun parse(statusOutput: String): GitStatusSummary {
|
||||
val files = mutableListOf<GitFileEntryV2>()
|
||||
val notAdded = mutableListOf<String>()
|
||||
val ignored = mutableListOf<String>()
|
||||
var branch = GitBranchInfo()
|
||||
|
||||
for (line in statusOutput.trim().split("\n").filter { it.isNotEmpty() }) {
|
||||
when {
|
||||
line.startsWith("# branch.oid ") ->
|
||||
BRANCH_OID.find(line)?.let { branch = branch.copy(oid = it.groupValues[1]) }
|
||||
line.startsWith("# branch.head ") ->
|
||||
BRANCH_HEAD.find(line)?.let { branch = branch.copy(head = it.groupValues[1]) }
|
||||
line.startsWith("# branch.upstream ") ->
|
||||
BRANCH_UPSTREAM.find(line)?.let { branch = branch.copy(upstream = it.groupValues[1]) }
|
||||
line.startsWith("# branch.ab ") ->
|
||||
BRANCH_AB.find(line)?.let {
|
||||
branch = branch.copy(
|
||||
ahead = it.groupValues[1].toInt(),
|
||||
behind = it.groupValues[2].toInt(),
|
||||
)
|
||||
}
|
||||
line.startsWith("1 ") ->
|
||||
ORDINARY_CHANGE.find(line)?.let { match ->
|
||||
files += GitFileEntryV2(
|
||||
index = match.groupValues[1],
|
||||
workingDir = match.groupValues[2],
|
||||
path = match.groupValues[9],
|
||||
)
|
||||
}
|
||||
line.startsWith("2 ") ->
|
||||
RENAME_COPY.find(line)?.let { match ->
|
||||
files += GitFileEntryV2(
|
||||
index = match.groupValues[1],
|
||||
workingDir = match.groupValues[2],
|
||||
from = match.groupValues[11],
|
||||
path = match.groupValues[12],
|
||||
)
|
||||
}
|
||||
line.startsWith("u ") ->
|
||||
UNMERGED.find(line)?.let { match ->
|
||||
files += GitFileEntryV2(
|
||||
index = match.groupValues[1],
|
||||
workingDir = match.groupValues[2],
|
||||
path = match.groupValues[11],
|
||||
)
|
||||
}
|
||||
line.startsWith("? ") -> UNTRACKED.find(line)?.let { notAdded += it.groupValues[1] }
|
||||
line.startsWith("! ") -> IGNORED.find(line)?.let { ignored += it.groupValues[1] }
|
||||
}
|
||||
}
|
||||
|
||||
return GitStatusSummary(files, notAdded, ignored, branch)
|
||||
}
|
||||
|
||||
/** Branch name to display; null for `(detached)` / `(initial)` (`getCurrentBranchV2`). */
|
||||
fun currentBranch(summary: GitStatusSummary): String? {
|
||||
val head = summary.branch.head
|
||||
if (head == null || head == "(detached)" || head == "(initial)") return null
|
||||
return head
|
||||
}
|
||||
|
||||
/**
|
||||
* Status stdout + the two `git diff --numstat` stdouts → the Changes-tab
|
||||
* model (`buildGitStatusFiles`): staged/unstaged split by XY letter, line
|
||||
* counts merged from the matching numstat side, untracked files appended
|
||||
* to the unstaged list (directories skipped).
|
||||
*/
|
||||
fun buildGitStatusFiles(
|
||||
statusOutput: String,
|
||||
unstagedDiffOutput: String,
|
||||
stagedDiffOutput: String,
|
||||
): GitStatusFiles {
|
||||
val summary = parse(statusOutput)
|
||||
val branchName = currentBranch(summary)
|
||||
|
||||
val unstagedStats = NumstatParser.statsMap(NumstatParser.parse(unstagedDiffOutput))
|
||||
val stagedStats = NumstatParser.statsMap(NumstatParser.parse(stagedDiffOutput))
|
||||
val noStats = DiffLineStats(added = 0, removed = 0, binary = false)
|
||||
|
||||
val stagedFiles = mutableListOf<GitFileStatus>()
|
||||
val unstagedFiles = mutableListOf<GitFileStatus>()
|
||||
|
||||
for (file in summary.files) {
|
||||
val parts = file.path.split("/")
|
||||
val fileName = parts.last().ifEmpty { file.path }
|
||||
val filePath = parts.dropLast(1).joinToString("/")
|
||||
|
||||
if (file.index != " " && file.index != "." && file.index != "?") {
|
||||
val stats = stagedStats[file.path] ?: noStats
|
||||
stagedFiles += GitFileStatus(
|
||||
fileName = fileName,
|
||||
filePath = filePath,
|
||||
fullPath = file.path,
|
||||
status = fileStatus(file.index),
|
||||
isStaged = true,
|
||||
linesAdded = stats.added,
|
||||
linesRemoved = stats.removed,
|
||||
oldPath = file.from,
|
||||
)
|
||||
}
|
||||
|
||||
if (file.workingDir != " " && file.workingDir != ".") {
|
||||
val stats = unstagedStats[file.path] ?: noStats
|
||||
unstagedFiles += GitFileStatus(
|
||||
fileName = fileName,
|
||||
filePath = filePath,
|
||||
fullPath = file.path,
|
||||
status = fileStatus(file.workingDir),
|
||||
isStaged = false,
|
||||
linesAdded = stats.added,
|
||||
linesRemoved = stats.removed,
|
||||
oldPath = file.from,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
for (untrackedPath in summary.notAdded) {
|
||||
if (untrackedPath.endsWith("/")) continue // untracked directories are not rows
|
||||
val parts = untrackedPath.split("/")
|
||||
unstagedFiles += GitFileStatus(
|
||||
fileName = parts.last().ifEmpty { untrackedPath },
|
||||
filePath = parts.dropLast(1).joinToString("/"),
|
||||
fullPath = untrackedPath,
|
||||
status = GitFileChange.UNTRACKED,
|
||||
isStaged = false,
|
||||
linesAdded = 0,
|
||||
linesRemoved = 0,
|
||||
)
|
||||
}
|
||||
|
||||
return GitStatusFiles(
|
||||
stagedFiles = stagedFiles,
|
||||
unstagedFiles = unstagedFiles,
|
||||
branch = branchName,
|
||||
totalStaged = stagedFiles.size,
|
||||
totalUnstaged = unstagedFiles.size,
|
||||
)
|
||||
}
|
||||
|
||||
private fun fileStatus(statusChar: String): GitFileChange = when (statusChar) {
|
||||
"M" -> GitFileChange.MODIFIED
|
||||
"A" -> GitFileChange.ADDED
|
||||
"D" -> GitFileChange.DELETED
|
||||
"R", "C" -> GitFileChange.RENAMED
|
||||
"?" -> GitFileChange.UNTRACKED
|
||||
"U" -> GitFileChange.CONFLICTED
|
||||
else -> GitFileChange.MODIFIED
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package app.hapi.protocol.git
|
||||
|
||||
/**
|
||||
* Parser for raw `git diff --numstat` stdout
|
||||
* (`GET /api/sessions/:id/git-diff-numstat?staged=`), the behavioral twin of
|
||||
* `parseNumStat`/`createDiffStatsMap` in `web/src/lib/gitParsers.ts`: binary
|
||||
* files report `-\t-` and count as 0/0, rename paths come in either the brace
|
||||
* form (`src/{old => new}/x.ts`) or the plain form (`old.txt => new.txt`) and
|
||||
* the stats map indexes the raw spelling plus both normalized paths so the
|
||||
* status-list merge finds them under the post-image path.
|
||||
*/
|
||||
|
||||
/** One numstat row. */
|
||||
data class DiffFileStat(
|
||||
/** Raw path column, rename arrows included. */
|
||||
val file: String,
|
||||
val changes: Int,
|
||||
val insertions: Int,
|
||||
val deletions: Int,
|
||||
val binary: Boolean,
|
||||
)
|
||||
|
||||
data class DiffSummary(
|
||||
val files: List<DiffFileStat>,
|
||||
val insertions: Int,
|
||||
val deletions: Int,
|
||||
val changes: Int,
|
||||
/** Number of files listed. */
|
||||
val changed: Int,
|
||||
)
|
||||
|
||||
/** Per-path counts for the Changes-list merge (web `createDiffStatsMap` values). */
|
||||
data class DiffLineStats(val added: Int, val removed: Int, val binary: Boolean)
|
||||
|
||||
object NumstatParser {
|
||||
|
||||
private val NUMSTAT_LINE = Regex("""^(\d+|-)\t(\d+|-)\t(.*)$""")
|
||||
private val BRACE_RENAME = Regex("""\{([^{}]+?)\s*=>\s*([^{}]+?)\}""")
|
||||
private val PLAIN_ARROW = Regex("""\s*=>\s*""")
|
||||
|
||||
/** Numstat stdout → per-file counts + totals (`parseNumStat`). */
|
||||
fun parse(numStatOutput: String): DiffSummary {
|
||||
val files = mutableListOf<DiffFileStat>()
|
||||
var insertionsTotal = 0
|
||||
var deletionsTotal = 0
|
||||
var changesTotal = 0
|
||||
|
||||
for (line in numStatOutput.trim().split("\n").filter { it.isNotEmpty() }) {
|
||||
val match = NUMSTAT_LINE.find(line) ?: continue
|
||||
val insertionsStr = match.groupValues[1]
|
||||
val deletionsStr = match.groupValues[2]
|
||||
val file = match.groupValues[3]
|
||||
|
||||
val isBinary = insertionsStr == "-" || deletionsStr == "-"
|
||||
val insertions = if (isBinary) 0 else insertionsStr.toInt()
|
||||
val deletions = if (isBinary) 0 else deletionsStr.toInt()
|
||||
val changes = insertions + deletions
|
||||
|
||||
files += DiffFileStat(
|
||||
file = file,
|
||||
changes = changes,
|
||||
insertions = insertions,
|
||||
deletions = deletions,
|
||||
binary = isBinary,
|
||||
)
|
||||
insertionsTotal += insertions
|
||||
deletionsTotal += deletions
|
||||
changesTotal += changes
|
||||
}
|
||||
|
||||
return DiffSummary(
|
||||
files = files,
|
||||
insertions = insertionsTotal,
|
||||
deletions = deletionsTotal,
|
||||
changes = changesTotal,
|
||||
changed = files.size,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts keyed by every spelling of each path — the raw column plus the
|
||||
* normalized new/old paths of a rename (`createDiffStatsMap`), so lookups
|
||||
* by porcelain-status path always hit.
|
||||
*/
|
||||
fun statsMap(summary: DiffSummary): Map<String, DiffLineStats> {
|
||||
val stats = mutableMapOf<String, DiffLineStats>()
|
||||
|
||||
for (file in summary.files) {
|
||||
val stat = DiffLineStats(added = file.insertions, removed = file.deletions, binary = file.binary)
|
||||
val paths = normalizePath(file.file)
|
||||
stats[file.file] = stat
|
||||
if (paths.newPath.isNotEmpty() && paths.newPath != file.file) {
|
||||
stats[paths.newPath] = stat
|
||||
}
|
||||
val oldPath = paths.oldPath
|
||||
if (!oldPath.isNullOrEmpty() && oldPath != file.file && oldPath != paths.newPath) {
|
||||
stats[oldPath] = stat
|
||||
}
|
||||
}
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
internal data class NormalizedPaths(val newPath: String, val oldPath: String? = null)
|
||||
|
||||
/** `src/{old => new}/x.ts` / `old.txt => new.txt` → post/pre-image paths. */
|
||||
internal fun normalizePath(rawPath: String): NormalizedPaths {
|
||||
val trimmed = rawPath.trim()
|
||||
|
||||
if (trimmed.contains("{") && trimmed.contains("=>") && trimmed.contains("}")) {
|
||||
val newPath = BRACE_RENAME.replace(trimmed) { it.groupValues[2].trim() }
|
||||
val oldPath = BRACE_RENAME.replace(trimmed) { it.groupValues[1].trim() }
|
||||
return NormalizedPaths(newPath = newPath, oldPath = oldPath)
|
||||
}
|
||||
|
||||
if (trimmed.contains("=>")) {
|
||||
val parts = trimmed.split(PLAIN_ARROW)
|
||||
val oldPath = parts.firstOrNull()?.trim()
|
||||
val newPath = parts.lastOrNull()?.trim()
|
||||
if (!newPath.isNullOrEmpty()) {
|
||||
return NormalizedPaths(newPath = newPath, oldPath = oldPath)
|
||||
}
|
||||
}
|
||||
|
||||
return NormalizedPaths(newPath = trimmed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package app.hapi.protocol.wire
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
// Wire types of the git & files surface (B-M4c):
|
||||
// `docs/api/client-contract/rest.md` "Git & files"; shapes from
|
||||
// `shared/src/apiTypes.ts` (`CommandResponse`, `FileReadResponse`,
|
||||
// `FileSearchResponse`, `ListDirectoryResponse`). All are RPC-wrapped —
|
||||
// HTTP 200 with `success: false` is a normal failure, callers must check.
|
||||
|
||||
/**
|
||||
* `GET /api/sessions/:id/git-status|git-diff-numstat|git-diff-file` —
|
||||
* `CommandResponse`: the hub relays raw git stdout verbatim; clients parse it
|
||||
* themselves (`app.hapi.protocol.git` twins `web/src/lib/gitParsers.ts`).
|
||||
*/
|
||||
@Serializable
|
||||
data class GitCommandResponse(
|
||||
val success: Boolean,
|
||||
val stdout: String? = null,
|
||||
val stderr: String? = null,
|
||||
val exitCode: Int? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** `GET /api/sessions/:id/file?path=` — [content] is **base64** (decode before display). */
|
||||
@Serializable
|
||||
data class FileReadResponse(
|
||||
val success: Boolean,
|
||||
val content: String? = null,
|
||||
/** Bytes on disk. */
|
||||
val size: Long? = null,
|
||||
/** Epoch ms. */
|
||||
val modified: Long? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/** `GET /api/sessions/:id/files?query=&limit=` (ripgrep-backed search). */
|
||||
@Serializable
|
||||
data class FileSearchResponse(
|
||||
val success: Boolean,
|
||||
val files: List<FileSearchItem>? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FileSearchItem(
|
||||
val fileName: String,
|
||||
/** Directory part; empty at the session root. */
|
||||
val filePath: String,
|
||||
val fullPath: String,
|
||||
/** `'file' | 'folder'` (search results are files in practice). */
|
||||
val fileType: String,
|
||||
val size: Long? = null,
|
||||
/** Epoch ms. */
|
||||
val modified: Long? = null,
|
||||
)
|
||||
|
||||
/** `GET /api/sessions/:id/directory?path=` — empty path = session root. */
|
||||
@Serializable
|
||||
data class ListDirectoryResponse(
|
||||
val success: Boolean,
|
||||
val entries: List<DirectoryEntry>? = null,
|
||||
val error: String? = null,
|
||||
)
|
||||
|
||||
/**
|
||||
* `DirectoryEntry` (`shared/src/apiTypes.ts`). The machine-RPC twin with
|
||||
* `isGitRepo` is [MachineDirectoryEntry].
|
||||
*/
|
||||
@Serializable
|
||||
data class DirectoryEntry(
|
||||
val name: String,
|
||||
/** `'file' | 'directory' | 'other'`. */
|
||||
val type: String,
|
||||
val size: Long? = null,
|
||||
/** Epoch ms. */
|
||||
val modified: Long? = null,
|
||||
)
|
||||
@@ -0,0 +1,164 @@
|
||||
package app.hapi.protocol.git
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* Inline porcelain-v2 samples with expectations produced by running the exact
|
||||
* inputs through `web/src/lib/gitParsers.ts` (`parseStatusSummaryV2`,
|
||||
* `getCurrentBranchV2`, `buildGitStatusFiles`) — the Kotlin parser must match
|
||||
* the web behavior byte for byte, quirks included.
|
||||
*/
|
||||
class GitStatusParserTest {
|
||||
|
||||
private val fullStatus = listOf(
|
||||
"# branch.oid 3b18e512dba79e4c8300dd08aeb37f8e728b8dad",
|
||||
"# branch.head main",
|
||||
"# branch.upstream origin/main",
|
||||
"# branch.ab +2 -1",
|
||||
"1 .M N... 100644 100644 100644 aaaaaaaa bbbbbbbb src/app.ts",
|
||||
"1 M. N... 100644 100644 100644 cccccccc dddddddd docs/readme.md",
|
||||
"1 MM N... 100644 100644 100644 eeeeeeee ffffffff both.txt",
|
||||
"1 A. N... 000000 100644 100644 00000000 11111111 new file.txt",
|
||||
"1 .D N... 100644 100644 000000 22222222 33333333 gone.txt",
|
||||
"2 R. N... 100644 100644 100644 44444444 55555555 R100 old/name.ts\tnew/name.ts",
|
||||
"u UU N... 100644 100644 100644 100644 66666666 77777777 88888888 conflict.txt",
|
||||
"? untracked.txt",
|
||||
"? build/",
|
||||
"! ignored.txt",
|
||||
).joinToString("\n")
|
||||
|
||||
@Test
|
||||
fun `parses branch headers`() {
|
||||
val branch = GitStatusParser.parse(fullStatus).branch
|
||||
|
||||
assertEquals("3b18e512dba79e4c8300dd08aeb37f8e728b8dad", branch.oid)
|
||||
assertEquals("main", branch.head)
|
||||
assertEquals("origin/main", branch.upstream)
|
||||
assertEquals(2, branch.ahead)
|
||||
assertEquals(1, branch.behind)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `parses ordinary, rename, unmerged, untracked and ignored records`() {
|
||||
val summary = GitStatusParser.parse(fullStatus)
|
||||
|
||||
assertEquals(7, summary.files.size)
|
||||
assertEquals(GitFileEntryV2(path = "src/app.ts", index = ".", workingDir = "M"), summary.files[0])
|
||||
assertEquals(GitFileEntryV2(path = "docs/readme.md", index = "M", workingDir = "."), summary.files[1])
|
||||
assertEquals(GitFileEntryV2(path = "both.txt", index = "M", workingDir = "M"), summary.files[2])
|
||||
// Paths with spaces survive (the path group is greedy).
|
||||
assertEquals(GitFileEntryV2(path = "new file.txt", index = "A", workingDir = "."), summary.files[3])
|
||||
assertEquals(GitFileEntryV2(path = "gone.txt", index = ".", workingDir = "D"), summary.files[4])
|
||||
// Rename record: first tab-separated path -> from, second -> path
|
||||
// (exactly how the web parser reads the payload).
|
||||
assertEquals(
|
||||
GitFileEntryV2(path = "new/name.ts", index = "R", workingDir = ".", from = "old/name.ts"),
|
||||
summary.files[5],
|
||||
)
|
||||
assertEquals(GitFileEntryV2(path = "conflict.txt", index = "U", workingDir = "U"), summary.files[6])
|
||||
|
||||
assertEquals(listOf("untracked.txt", "build/"), summary.notAdded)
|
||||
assertEquals(listOf("ignored.txt"), summary.ignored)
|
||||
assertEquals("main", GitStatusParser.currentBranch(summary))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `detached and initial heads have no current branch`() {
|
||||
val detached = GitStatusParser.parse(
|
||||
"# branch.oid deadbeef\n# branch.head (detached)\n1 .M N... 100644 100644 100644 aa bb x.txt",
|
||||
)
|
||||
assertEquals("(detached)", detached.branch.head)
|
||||
assertNull(GitStatusParser.currentBranch(detached))
|
||||
assertEquals(1, detached.files.size)
|
||||
|
||||
val initial = GitStatusParser.parse("# branch.head (initial)")
|
||||
assertNull(GitStatusParser.currentBranch(initial))
|
||||
|
||||
assertNull(GitStatusParser.currentBranch(GitStatusParser.parse("")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `malformed records are skipped`() {
|
||||
val summary = GitStatusParser.parse(
|
||||
listOf(
|
||||
"1 not-a-valid-record",
|
||||
"2 R. missing-everything",
|
||||
"# branch.ab +x -y",
|
||||
"1 MM N... 100644 100644 100644 eeeeeeee ffffffff ok.txt",
|
||||
).joinToString("\n"),
|
||||
)
|
||||
|
||||
assertEquals(listOf(GitFileEntryV2(path = "ok.txt", index = "M", workingDir = "M")), summary.files)
|
||||
assertNull(summary.branch.ahead)
|
||||
}
|
||||
|
||||
// ------------------------------------------------- buildGitStatusFiles --
|
||||
|
||||
private val unstagedNumstat = "3\t1\tsrc/app.ts\n5\t2\tboth.txt\n-\t-\timage.png"
|
||||
private val stagedNumstat =
|
||||
"4\t0\tdocs/readme.md\n1\t1\tboth.txt\n10\t0\tnew file.txt\n0\t0\t{old => new}/name.ts"
|
||||
|
||||
@Test
|
||||
fun `merges status with numstat into staged and unstaged sections`() {
|
||||
val built = GitStatusParser.buildGitStatusFiles(fullStatus, unstagedNumstat, stagedNumstat)
|
||||
|
||||
assertEquals("main", built.branch)
|
||||
assertEquals(5, built.totalStaged)
|
||||
assertEquals(5, built.totalUnstaged)
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
GitFileStatus("readme.md", "docs", "docs/readme.md", GitFileChange.MODIFIED, true, 4, 0),
|
||||
GitFileStatus("both.txt", "", "both.txt", GitFileChange.MODIFIED, true, 1, 1),
|
||||
GitFileStatus("new file.txt", "", "new file.txt", GitFileChange.ADDED, true, 10, 0),
|
||||
// Rename counts resolve through the normalized brace path.
|
||||
GitFileStatus("name.ts", "new", "new/name.ts", GitFileChange.RENAMED, true, 0, 0, "old/name.ts"),
|
||||
GitFileStatus("conflict.txt", "", "conflict.txt", GitFileChange.CONFLICTED, true, 0, 0),
|
||||
),
|
||||
built.stagedFiles,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
GitFileStatus("app.ts", "src", "src/app.ts", GitFileChange.MODIFIED, false, 3, 1),
|
||||
GitFileStatus("both.txt", "", "both.txt", GitFileChange.MODIFIED, false, 5, 2),
|
||||
GitFileStatus("gone.txt", "", "gone.txt", GitFileChange.DELETED, false, 0, 0),
|
||||
// UU conflicts appear on both sides, like the web list.
|
||||
GitFileStatus("conflict.txt", "", "conflict.txt", GitFileChange.CONFLICTED, false, 0, 0),
|
||||
// Untracked files land unstaged; the untracked build/ dir is dropped.
|
||||
GitFileStatus("untracked.txt", "", "untracked.txt", GitFileChange.UNTRACKED, false, 0, 0),
|
||||
),
|
||||
built.unstagedFiles,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty outputs build an empty model`() {
|
||||
val built = GitStatusParser.buildGitStatusFiles("", "", "")
|
||||
|
||||
assertNull(built.branch)
|
||||
assertTrue(built.stagedFiles.isEmpty())
|
||||
assertTrue(built.unstagedFiles.isEmpty())
|
||||
assertEquals(0, built.totalStaged)
|
||||
assertEquals(0, built.totalUnstaged)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `files missing from numstat keep zero counts`() {
|
||||
val built = GitStatusFilesFixture.singleModified()
|
||||
|
||||
assertEquals(0, built.unstagedFiles.single().linesAdded)
|
||||
assertEquals(0, built.unstagedFiles.single().linesRemoved)
|
||||
}
|
||||
|
||||
private object GitStatusFilesFixture {
|
||||
fun singleModified(): GitStatusFiles = GitStatusParser.buildGitStatusFiles(
|
||||
"# branch.head work\n1 .M N... 100644 100644 100644 aa bb solo.txt",
|
||||
"",
|
||||
"",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package app.hapi.protocol.git
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* Inline numstat samples with expectations produced by running the exact
|
||||
* inputs through `parseNumStat`/`createDiffStatsMap` in
|
||||
* `web/src/lib/gitParsers.ts`.
|
||||
*/
|
||||
class NumstatParserTest {
|
||||
|
||||
@Test
|
||||
fun `parses counts, totals and binary markers`() {
|
||||
val summary = NumstatParser.parse("3\t1\tsrc/app.ts\n5\t2\tboth.txt\n-\t-\timage.png")
|
||||
|
||||
assertEquals(
|
||||
listOf(
|
||||
DiffFileStat("src/app.ts", changes = 4, insertions = 3, deletions = 1, binary = false),
|
||||
DiffFileStat("both.txt", changes = 7, insertions = 5, deletions = 2, binary = false),
|
||||
DiffFileStat("image.png", changes = 0, insertions = 0, deletions = 0, binary = true),
|
||||
),
|
||||
summary.files,
|
||||
)
|
||||
assertEquals(8, summary.insertions)
|
||||
assertEquals(3, summary.deletions)
|
||||
assertEquals(11, summary.changes)
|
||||
assertEquals(3, summary.changed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `blank and malformed lines are ignored`() {
|
||||
val summary = NumstatParser.parse("\n\nnot numstat\n1\t2\tok.txt\n")
|
||||
|
||||
assertEquals(1, summary.changed)
|
||||
assertEquals("ok.txt", summary.files.single().file)
|
||||
assertTrue(NumstatParser.parse("").files.isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stats map indexes raw path plus normalized brace-rename paths`() {
|
||||
val map = NumstatParser.statsMap(NumstatParser.parse("0\t0\t{old => new}/name.ts"))
|
||||
|
||||
val stat = DiffLineStats(added = 0, removed = 0, binary = false)
|
||||
assertEquals(stat, map["{old => new}/name.ts"])
|
||||
assertEquals(stat, map["new/name.ts"])
|
||||
assertEquals(stat, map["old/name.ts"])
|
||||
assertEquals(3, map.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stats map indexes plain arrow renames`() {
|
||||
val map = NumstatParser.statsMap(NumstatParser.parse("2\t3\told.txt => new.txt"))
|
||||
|
||||
val stat = DiffLineStats(added = 2, removed = 3, binary = false)
|
||||
assertEquals(stat, map["old.txt => new.txt"])
|
||||
assertEquals(stat, map["new.txt"])
|
||||
assertEquals(stat, map["old.txt"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `stats map keeps binary flag and plain paths`() {
|
||||
val map = NumstatParser.statsMap(NumstatParser.parse("-\t-\tassets/logo.png\n7\t0\tREADME.md"))
|
||||
|
||||
assertEquals(DiffLineStats(0, 0, binary = true), map["assets/logo.png"])
|
||||
assertEquals(DiffLineStats(7, 0, binary = false), map["README.md"])
|
||||
assertNull(map["missing.txt"])
|
||||
assertEquals(2, map.size)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `mid-path brace rename normalizes both sides`() {
|
||||
val paths = NumstatParser.normalizePath("src/{components => ui}/Button.tsx")
|
||||
|
||||
assertEquals("src/ui/Button.tsx", paths.newPath)
|
||||
assertEquals("src/components/Button.tsx", paths.oldPath)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `path without rename markers passes through trimmed`() {
|
||||
val paths = NumstatParser.normalizePath(" plain/path.txt ")
|
||||
|
||||
assertEquals("plain/path.txt", paths.newPath)
|
||||
assertNull(paths.oldPath)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user