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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
261 changes: 259 additions & 2 deletions app/src/main/java/com/sayanthrock/freeairock/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,108 @@ import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModelProvider
import com.sayanthrock.freeairock.data.ai.CodeAnalysisState
import com.sayanthrock.freeairock.data.github.GitHubApiService
import com.sayanthrock.freeairock.data.storage.SecureStorageManager
import com.sayanthrock.freeairock.ui.AboutScreen
import com.sayanthrock.freeairock.ui.AppViewModel
import com.sayanthrock.freeairock.ui.AppViewModelFactory
import com.sayanthrock.freeairock.ui.HomeScaffold
import com.sayanthrock.freeairock.ui.ImageStudioScreen
import com.sayanthrock.freeairock.ui.ImageViewModel
import com.sayanthrock.freeairock.ui.PlaceholderPanel
import com.sayanthrock.freeairock.ui.ImageStudioScreen
import com.sayanthrock.freeairock.data.ai.PollinationsApiService
import retrofit2.converter.scalars.ScalarsConverterFactory
import com.sayanthrock.freeairock.ui.ReviewScreen
import com.sayanthrock.freeairock.ui.ReviewViewModel
import com.sayanthrock.freeairock.ui.ThemeMode
import com.sayanthrock.freeairock.ui.theme.FreeAiRockTheme
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : ComponentActivity() {

private val secureStorage by lazy { SecureStorageManager(this) }

private val okHttpClient by lazy {
OkHttpClient.Builder()
.addInterceptor { chain ->
val requestBuilder = chain.request().newBuilder()
val token = secureStorage.getGitHubToken()

if (!token.isNullOrBlank()) {
requestBuilder.header("Authorization", "Bearer $token")
}

chain.proceed(requestBuilder.build())
Comment thread
SayanthRock marked this conversation as resolved.
Comment thread
SayanthRock marked this conversation as resolved.
}
.build()
}

private val githubApiService by lazy {
Retrofit.Builder()
.baseUrl("https://api.github.com/")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(GitHubApiService::class.java)
}


private val pollinationsApiService by lazy {
Retrofit.Builder()
.baseUrl("https://text.pollinations.ai/")
.client(OkHttpClient.Builder().build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(PollinationsApiService::class.java)
}

private val viewModelFactory by lazy {
AppViewModelFactory(secureStorage)
AppViewModelFactory(secureStorage, githubApiService, pollinationsApiService)
}

private val viewModelProvider by lazy {
ViewModelProvider(this, viewModelFactory)
}

private val appViewModel: AppViewModel by lazy {
viewModelProvider[AppViewModel::class.java]
}

private val reviewViewModel: ReviewViewModel by lazy {
viewModelProvider[ReviewViewModel::class.java]
}

private val imageViewModel: ImageViewModel by lazy {
viewModelProvider[ImageViewModel::class.java]
}
Expand All @@ -47,6 +123,24 @@ class MainActivity : ComponentActivity() {

FreeAiRockTheme(darkTheme = darkTheme) {
HomeScaffold(
codeContent = { modifier ->
CodeAnalyzerScreen(
uiState = appViewModel.analysisState.collectAsState().value,
onSave = { githubToken ->
appViewModel.saveKeys(githubToken)
imageViewModel.refreshRenderer()
},
onAnalyze = appViewModel::analyzeCodeFile,
onReset = appViewModel::resetAnalysis,
modifier = modifier
)
},
reviewContent = { modifier ->
ReviewScreen(
viewModel = reviewViewModel,
modifier = modifier
)
},
studioContent = { modifier ->
ImageStudioScreen(modifier = modifier)
},
Expand All @@ -62,3 +156,166 @@ class MainActivity : ComponentActivity() {
}
}
}

@Composable
private fun CodeAnalyzerScreen(
uiState: CodeAnalysisState,
onSave: (githubToken: String) -> Unit,
onAnalyze: (fileName: String, downloadUrl: String?) -> Unit,
onReset: () -> Unit,
modifier: Modifier = Modifier
) {
var githubToken by remember { mutableStateOf("") }

var fileName by remember { mutableStateOf("MainActivity.kt") }
var fileUrl by remember { mutableStateOf("") }
var savedMessage by remember { mutableStateOf<String?>(null) }
val clipboardManager = LocalClipboardManager.current

Surface(
modifier = modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(24.dp)
) {
Text(
text = "FREE-AI-ROCK",
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.primary
)

Spacer(modifier = Modifier.height(12.dp))

Text(
text = "Secure setup for GitHub file analysis and AI code summaries.",
color = MaterialTheme.colorScheme.onBackground
)

Spacer(modifier = Modifier.height(24.dp))

OutlinedTextField(
value = githubToken,
onValueChange = { githubToken = it },
label = { Text("GitHub token") },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier.fillMaxWidth(),
singleLine = true
)



Spacer(modifier = Modifier.height(16.dp))

Button(
onClick = {
onSave(githubToken)
savedMessage = "Saved securely on this device"
},
modifier = Modifier.fillMaxWidth()
) {
Text("Save Securely")
}

savedMessage?.let {
Spacer(modifier = Modifier.height(12.dp))
Text(
text = it,
color = MaterialTheme.colorScheme.onBackground
)
}

Spacer(modifier = Modifier.height(28.dp))

Text(
text = "Code AI",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary
)

Spacer(modifier = Modifier.height(12.dp))

OutlinedTextField(
value = fileName,
onValueChange = { fileName = it },
label = { Text("File name") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)

Spacer(modifier = Modifier.height(12.dp))

OutlinedTextField(
value = fileUrl,
onValueChange = { fileUrl = it },
label = { Text("GitHub raw/blob file URL") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
)

Spacer(modifier = Modifier.height(16.dp))

Button(
onClick = { onAnalyze(fileName, fileUrl) },
enabled = uiState !is CodeAnalysisState.Loading && fileUrl.isNotBlank(),
modifier = Modifier.fillMaxWidth()
) {
Text(if (uiState is CodeAnalysisState.Loading) "Analyzing..." else "Summarize Code with AI")
}

Spacer(modifier = Modifier.height(20.dp))

when (uiState) {
CodeAnalysisState.Idle -> Text(
text = "Paste a GitHub raw URL or normal blob URL, then run the analyzer.",
color = MaterialTheme.colorScheme.onBackground
)

CodeAnalysisState.Loading -> CircularProgressIndicator(
color = MaterialTheme.colorScheme.primary
)

is CodeAnalysisState.Success -> {
Surface(
color = MaterialTheme.colorScheme.surface,
shape = MaterialTheme.shapes.medium,
modifier = Modifier.fillMaxWidth()
) {
Text(
text = uiState.result,
modifier = Modifier.padding(16.dp),
color = MaterialTheme.colorScheme.onSurface,
style = MaterialTheme.typography.bodyMedium
)
}

Spacer(modifier = Modifier.height(12.dp))

OutlinedButton(
onClick = { clipboardManager.setText(AnnotatedString(uiState.result)) },
modifier = Modifier.fillMaxWidth()
) {
Text("Copy Result")
}

Spacer(modifier = Modifier.height(8.dp))

OutlinedButton(
onClick = onReset,
modifier = Modifier.fillMaxWidth()
) {
Text("Reset")
}
}

is CodeAnalysisState.Error -> Text(
text = "Error: ${uiState.message}",
color = MaterialTheme.colorScheme.error
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.sayanthrock.freeairock.data.ai

class AiCodeAnalyzer(private val pollinationsApiService: PollinationsApiService) {

suspend fun analyzeCode(fileName: String, rawCode: String): String {
val safeFileName = fileName.ifBlank { "selected-file" }
val prompt = buildString {
appendLine("You are an expert software developer.")
appendLine("Analyze the file named '$safeFileName'.")
appendLine("Explain its core functionality, architecture role, important methods, risks, and improvement ideas.")
appendLine("Keep the explanation clear for a junior developer.")
appendLine()
appendLine("Code:")
appendLine("```")
appendLine(rawCode.take(MAX_CODE_CHARS))
appendLine("```")
}

return generateText(prompt, "No explanation generated.")
}

suspend fun summarizePullRequest(diffCode: String): String {
val prompt = buildString {
appendLine("You are an expert lead developer reviewing a pull request.")
appendLine("Analyze the following Git diff.")
appendLine("Do not read line-by-line changes back to the user.")
appendLine("Explain the high-level purpose, likely bug fix or feature, architecture impact, risk, and testing notes.")
appendLine("Keep the explanation approachable for a junior developer.")
appendLine()
appendLine("Git diff:")
appendLine("```diff")
appendLine(diffCode.take(MAX_DIFF_CHARS))
appendLine("```")
}

return generateText(prompt, "No pull request explanation generated.")
}

suspend fun summarizePullRequest(owner: String, repo: String, pullNumber: Int, diffText: String): String {
val safeOwner = owner.ifBlank { "owner" }
val safeRepo = repo.ifBlank { "repo" }
val prompt = buildString {
appendLine("You are a senior code reviewer.")
appendLine("Summarize pull request #$pullNumber in $safeOwner/$safeRepo using the Git diff below.")
appendLine("Focus on developer impact, affected files, behavior changes, risks, testing notes, and release notes.")
appendLine("Use clear plain English. Avoid repeating every line of the diff.")
appendLine()
appendLine("Return this structure:")
appendLine("1. Summary")
appendLine("2. Key changes")
appendLine("3. Risk level")
appendLine("4. Testing checklist")
appendLine("5. Suggested release note")
appendLine()
appendLine("Git diff:")
appendLine("```diff")
appendLine(diffText.take(MAX_DIFF_CHARS))
appendLine("```")
}

return generateText(prompt, "No pull request summary generated.")
}

private suspend fun generateText(prompt: String, fallback: String): String {
return try {
val response = pollinationsApiService.generateText(
PollinationsRequest(
messages = listOf(PollinationsMessage(role = "user", content = prompt))
)
)
response.takeIf { it.isNotBlank() } ?: fallback
} catch (error: Exception) {
"AI analysis failed: ${error.localizedMessage ?: "Unknown error"}"
}
Comment thread
SayanthRock marked this conversation as resolved.
Comment thread
SayanthRock marked this conversation as resolved.
}

companion object {
private const val MAX_CODE_CHARS = 12000
private const val MAX_DIFF_CHARS = 18000
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.sayanthrock.freeairock.data.ai

sealed interface CodeAnalysisState {
data object Idle : CodeAnalysisState
data object Loading : CodeAnalysisState
data class Success(val result: String) : CodeAnalysisState
data class Error(val message: String) : CodeAnalysisState
}
Loading
Loading