Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
feat(chat): built-in personas with prefilled system prompts
Durganshu768407a77c1f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73ab4b1..d186f6a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,18 @@ All notable changes to Gotcha are documented here.## [Unreleased]### Added+- **Chat personas.** The starter chips said what to ask; nothing said who to ask.+ A persona row now sits under the agent selector on an empty chat — **Doctor,+ Chef, Fitness Coach, Tutor, Travel Planner, Handyman** — and picking one starts+ the chat in that role, with the role's own instructions carried in the system+ prompt for every turn of it. The role is chosen before the first message and+ fixed from there: it is saved with the chat, so reopening one weeks later is+ still answered in role (the top bar names it), and a new chat never inherits+ the last one's. Each persona starts read-only in Monitor and the selector stays+ live, so taking one into Operator is still your call, and a role never loosens+ what the agent is allowed to do — the mode restrictions remain the last word.+ Where a role shadows a regulated profession its prompt says so: the Doctor+ never presents itself as your doctor, and routes emergencies to real care.- **Search the settings.** Fifteen settings pages hold well over a hundredcontrols between them, and finding one meant scrolling the list and guessingwhich page owned it — "wake word" is under Assistive Ball, "API key" under AIdiff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 34ab51c..2ff589e 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -840,6 +840,7 @@ class MainActivity : ComponentActivity() {pickResults = chatViewModel.pickResults,onSwitchAgent = chatViewModel::switchAgent,onSetAgent = chatViewModel::setAgent,+ onSetPersona = chatViewModel::setPersona,onSpeak = chatViewModel::speak,onStopSpeaking = chatViewModel::stopSpeaking,onStartListening = chatViewModel::startListening,diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex faaad9c..1070b03 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -24,6 +24,7 @@ import com.gotcha.tools.SubAgentSessionimport com.gotcha.tools.ToolExecutorimport com.gotcha.tools.ToolRegistryimport com.gotcha.tools.ToolResult+import com.gotcha.ui.personaByIdimport com.gotcha.util.GotchaLogimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationException@@ -79,6 +80,14 @@ class AgentEngine(*/var sessionIsSample: Boolean = false+ /**+ * Id of the persona the bound session was started with, or null for a plain+ * chat. Read by [agentInstructionText] and persisted on every save. Fixed+ * for the life of a session — the picker is only offered on an empty chat —+ * so splicing it into the system message keeps index 0 cache-stable.+ */+ var sessionPersonaId: String? = null+/*** Stable key for the provider's server-side prompt KV cache* (`prompt_cache_key` / `X-Session-Id`), independent of [sessionId] which@@ -312,7 +321,8 @@ class AgentEngine(displayMessages = displayMessagesProvider(),agentMode = agentModeProvider()?.name,runSummaries = runSummaries.toList(),- isSample = sessionIsSample+ isSample = sessionIsSample,+ personaId = sessionPersonaId))// Rename the chat dir in place now that the real title is known.@@ -1096,6 +1106,18 @@ class AgentEngine("mode restrictions below, or with a format a tool requires."}.orEmpty()+ // The role the user picked for this chat (home screen ▸ Persona). It+ // sits ahead of the reply-style directive so the user's own words about+ // how they want to be answered win on a conflict, and ahead of the mode+ // <system-reminder>, which stays the last word on what may be done.+ val personaDirective = personaById(sessionPersonaId)+ ?.let {+ "\n\nFor this conversation the user has chosen the ${it.label} persona:\n" ++ "${it.systemPrompt}\n" ++ "Adopt that role's voice and expertise. It never overrides a safety constraint, " ++ "the mode restrictions below, or a format a tool requires."+ }+ .orEmpty()// Default to HTML-on-port when the user wants something built but did not// say how to run it — make it runnable on this phone without a follow-up.// Operator-only and suppressed in voice-call brevity mode. The skill@@ -1146,7 +1168,7 @@ class AgentEngine(} +"</system-reminder>"}- return core + serveDirective + languageDirective + styleDirective + reminder+ return core + serveDirective + languageDirective + personaDirective + styleDirective + reminder}/** The Monitor-mode core instruction block; split out so [agentInstructionText] stays readable. */diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex f8af42e..b461d35 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -35,6 +35,7 @@ import com.gotcha.tools.ScreenPerceptionimport com.gotcha.tools.ToolResultimport com.gotcha.tools.mergeProfileUpdateimport com.gotcha.ui.ConfirmationOverlay+import com.gotcha.ui.Personaimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CompletableDeferred@@ -104,6 +105,12 @@ data class ChatUiState(val isConfigured: Boolean = false,val activeSessionId: String? = null,val activeAgent: AgentMode = AgentMode.MONITOR,+ /**+ * Id of the persona the open chat was started with, or null for a plain one.+ * Chosen on the home screen before the first message and fixed from there:+ * the picker is only shown while the chat is empty.+ */+ val activePersonaId: String? = null,/*** True while the open chat is one of the samples seeded on first run, so the* transcript can say so above the first bubble. Nothing else depends on it:@@ -741,6 +748,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}engineTranscript = _uiState.value.messagesengineAgent = _uiState.value.activeAgent+ agentEngine.sessionPersonaId = _uiState.value.activePersonaId}/** Load an image from a content:// URI, downscale, and return base64. */@@ -1087,6 +1095,30 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A_uiState.update { it.copy(activeAgent = mode) }}+ /**+ * Put the chat about to start into [persona]'s role, or back to a plain chat+ * when null. Creation-time only: the picker is only drawn on an empty chat,+ * and a persona arriving mid-conversation would rewrite the system message+ * the provider has already cached for this session — so a chat that has+ * messages ignores this.+ *+ * The persona's own default mode is applied through [setAgent] (silently,+ * like the selector itself), so the user sees where the persona put them and+ * can still move. Clearing a persona leaves the mode where it is.+ */+ fun setPersona(persona: Persona?) {+ if (_uiState.value.messages.isNotEmpty()) return+ if (_uiState.value.activePersonaId == persona?.id) return+ // While another chat is running the engine stays bound to it; the picked+ // persona rides in UI state and reaches the engine at send time, through+ // bindEngineToViewedSession.+ if (_uiState.value.runningSessionId == null) {+ agentEngine.sessionPersonaId = persona?.id+ }+ _uiState.update { it.copy(activePersonaId = persona?.id) }+ persona?.let { setAgent(it.defaultAgent) }+ }+override fun onCleared() {confirmationOverlay.dismiss()super.onCleared()@@ -1117,6 +1149,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A// new chat file.agentEngine.restoreRunSummaries(emptyList())agentEngine.sessionIsSample = false+ // A new chat never inherits the previous one's persona: it is picked+ // per chat, on the home screen this call is about to show.+ agentEngine.sessionPersonaId = nullagentEngine.setupWorkingDir(create = false)engineTranscript = emptyList()engineAgent = defaultAgent@@ -1126,6 +1161,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Amessages = emptyList(),activeSessionId = newId,activeAgent = defaultAgent,+ activePersonaId = null,viewingSample = false)}@@ -1188,6 +1224,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(activeSessionId = id,activeAgent = engineAgent,+ activePersonaId = agentEngine.sessionPersonaId,messages = engineTranscript,viewingSample = _sessions.value.firstOrNull { s -> s.id == id }?.isSample?: agentEngine.sessionIsSample@@ -1211,6 +1248,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AagentEngine.restoreTitle(if (session.isFallbackTitle()) null else session.title)agentEngine.restoreRunSummaries(session.runSummaries)agentEngine.sessionIsSample = session.isSample+ agentEngine.sessionPersonaId = session.personaIdagentEngine.setupWorkingDir()engineTranscript = session.displayMessagesengineAgent = restoredAgent@@ -1224,6 +1262,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(activeSessionId = session.id,activeAgent = restoredAgent,+ activePersonaId = session.personaId,viewingSample = session.isSample,messages = session.displayMessages,// Clear engine-scoped transient UI for the viewed (non-running) chat.@@ -1239,6 +1278,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Ait.copy(activeSessionId = session.id,activeAgent = restoredAgent,+ activePersonaId = session.personaId,viewingSample = session.isSample,activity = null,subAgentRunning = null,diff --git a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.ktindex 1fc9913..7e5efeb 100644--- a/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt+++ b/app/src/main/java/com/gotcha/data/ChatHistoryRepository.kt@@ -37,7 +37,15 @@ data class ChatSession(* session: openable, continuable and deletable. Defaulted so every chat* written before samples existed decodes as a real one.*/- val isSample: Boolean = false+ val isSample: Boolean = false,+ /**+ * Id of the built-in persona this chat was started with, or null for a plain+ * chat. Fixed when the chat is created and carried through every save, so a+ * conversation reopened weeks later is still answered in the role it began+ * in. Defaulted so every chat written before personas existed decodes as a+ * plain one, and an id that no longer resolves degrades to the same thing.+ */+ val personaId: String? = null)/**diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 72c0d17..43616ff 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -10,20 +10,24 @@ import androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraintsimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsimport androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScrollimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.filled.Sendimport androidx.compose.material.icons.automirrored.rounded.VolumeOff@@ -117,6 +121,7 @@ fun ChatScreen(pickResults: Flow<PickedFile?>,onSwitchAgent: () -> Unit,onSetAgent: (AgentMode) -> Unit = {},+ onSetPersona: (Persona?) -> Unit = {},onSpeak: (String) -> Unit = {},onStopSpeaking: () -> Unit = {},onStartListening: () -> Unit = {},@@ -199,11 +204,26 @@ fun ChatScreen(containerColor = Color.Transparent),title = {- Text(- if (isHome) "Gotcha" else (sessionTitle ?: "Gotcha"),- maxLines = 1,- overflow = TextOverflow.Ellipsis- )+ Column {+ Text(+ if (isHome) "Gotcha" else (sessionTitle ?: "Gotcha"),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ // The persona is invisible once the picker is gone, so+ // the open chat says which role it is being answered in.+ val persona = if (isHome) null else personaById(state.activePersonaId)+ if (persona != null) {+ Text(+ persona.label,+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ modifier = Modifier.testTag("persona_badge")+ )+ }+ }},navigationIcon = {IconButton(onClick = onOpenDrawer) {@@ -292,58 +312,82 @@ fun ChatScreen(}if (isHome) {val greeting = rememberSaveable(state.activeSessionId) { HOME_GREETINGS.random() }- Column(- modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 32.dp),- verticalArrangement = Arrangement.Center,- horizontalAlignment = Alignment.CenterHorizontally- ) {- ComposeImage(- // The in-app mark, not the launcher icon: @mipmap/ic_launcher_round- // is an adaptive-icon XML, which painterResource cannot load.- painter = painterResource(R.drawable.gotcha_logo),- contentDescription = "Gotcha logo",- modifier = Modifier.size(96.dp).clip(CircleShape)- )- Spacer(modifier = Modifier.height(24.dp))- Text(- greeting,- style = MaterialTheme.typography.headlineMedium,- textAlign = TextAlign.Center,- // The largest text on the home screen, so it takes the- // primary ink. Secondary ink over a wallpaper was the- // weakest thing on the screen.- color = MaterialTheme.colorScheme.onSurface- )- Spacer(modifier = Modifier.height(24.dp))- AgentModeSelector(- selected = state.activeAgent,- onSelect = onSetAgent- )- // Starters are an offer to fill the composer, so they are- // only shown when the composer can actually be used: no API- // key means typing is disabled, and a run in another chat- // blocks sending from here.- if (state.isConfigured && !otherChatRunning) {- // Re-drawn per session rather than per recomposition, so- // the three on offer don't reshuffle under a rotation.- val starters = rememberSaveable(- state.activeSessionId,- saver = StarterPromptLabelsSaver- ) {- STARTER_PROMPTS.shuffled().take(STARTER_PROMPT_COUNT)- }- if (starters.isNotEmpty()) {+ // `heightIn(min = maxHeight)` inside a scroller keeps the column+ // centred exactly as before whenever it fits, and lets it scroll+ // once it doesn't — which the persona row made reachable on a+ // short screen with the keyboard up.+ BoxWithConstraints(modifier = Modifier.weight(1f).fillMaxWidth()) {+ val available = maxHeight+ Column(+ modifier = Modifier+ .verticalScroll(rememberScrollState())+ .heightIn(min = available)+ .fillMaxWidth()+ .padding(horizontal = 32.dp),+ verticalArrangement = Arrangement.Center,+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ ComposeImage(+ // The in-app mark, not the launcher icon: @mipmap/ic_launcher_round+ // is an adaptive-icon XML, which painterResource cannot load.+ painter = painterResource(R.drawable.gotcha_logo),+ contentDescription = "Gotcha logo",+ modifier = Modifier.size(96.dp).clip(CircleShape)+ )+ Spacer(modifier = Modifier.height(24.dp))+ Text(+ greeting,+ style = MaterialTheme.typography.headlineMedium,+ textAlign = TextAlign.Center,+ // The largest text on the home screen, so it takes the+ // primary ink. Secondary ink over a wallpaper was the+ // weakest thing on the screen.+ color = MaterialTheme.colorScheme.onSurface+ )+ Spacer(modifier = Modifier.height(24.dp))+ AgentModeSelector(+ selected = state.activeAgent,+ onSelect = onSetAgent+ )+ // Persona and agent both describe how the chat about to+ // start will behave, so the picker sits with the selector+ // rather than with the starters below — and under the same+ // gate as them: there is nothing to set up a chat for when+ // the composer can't be used.+ if (state.isConfigured && !otherChatRunning) {Spacer(modifier = Modifier.height(24.dp))- StarterPromptRow(- prompts = starters,- onPick = { prompt ->- // Fill, never send: the template is a draft the- // user is expected to edit first.- input = prompt.template- inputWasVoice = false- }+ PersonaRow(+ personas = PERSONAS,+ selectedId = state.activePersonaId,+ onPick = onSetPersona)}+ // Starters are an offer to fill the composer, so they are+ // only shown when the composer can actually be used: no API+ // key means typing is disabled, and a run in another chat+ // blocks sending from here.+ if (state.isConfigured && !otherChatRunning) {+ // Re-drawn per session rather than per recomposition, so+ // the three on offer don't reshuffle under a rotation.+ val starters = rememberSaveable(+ state.activeSessionId,+ saver = StarterPromptLabelsSaver+ ) {+ STARTER_PROMPTS.shuffled().take(STARTER_PROMPT_COUNT)+ }+ if (starters.isNotEmpty()) {+ Spacer(modifier = Modifier.height(24.dp))+ StarterPromptRow(+ prompts = starters,+ onPick = { prompt ->+ // Fill, never send: the template is a draft the+ // user is expected to edit first.+ input = prompt.template+ inputWasVoice = false+ }+ )+ }+ }}}} else {diff --git a/app/src/main/java/com/gotcha/ui/Persona.kt b/app/src/main/java/com/gotcha/ui/Persona.ktnew file mode 100644index 0000000..f02a89e--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/Persona.kt@@ -0,0 +1,236 @@+package com.gotcha.ui++import androidx.compose.animation.animateColorAsState+import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.compositeOver+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import com.gotcha.tools.AgentMode+import com.gotcha.ui.theme.motionSpec++/**+ * A role the user can put Gotcha in for the length of one chat.+ *+ * [systemPrompt] is spliced into the index-0 system message for every turn of+ * that chat, so it shapes voice and expertise without touching what the agent+ * is *allowed* to do — mode restrictions and safety constraints still win, and+ * the engine says so explicitly when it splices the text in.+ *+ * [id] is persisted on the chat file and must never be renamed: an id that no+ * longer exists (a persona dropped in an app update) simply resolves to no+ * persona, and the chat carries on as a plain one.+ *+ * [defaultAgent] is the mode applied when the persona is picked. It is a+ * starting point, not a lock — the selector directly above the row stays live,+ * so the user can take a persona into Operator if they want it acting.+ */+data class Persona(+ val id: String,+ val label: String,+ val defaultAgent: AgentMode,+ val systemPrompt: String+)++/**+ * The personas offered on an empty chat, a small curated set of everyday roles.+ *+ * All of them start in Monitor: a persona is something to talk to, and the+ * read-only mode is the safe default for a conversation that never asked for+ * the device to be touched. [Persona.defaultAgent] exists so a future+ * (or user-defined) persona whose whole point is acting can ship as Operator+ * without any other change.+ *+ * Where a role maps onto a regulated profession the prompt carries its own+ * disclaimer: these are not that professional, and the reply has to say so+ * rather than leaving the persona's costume to imply otherwise.+ */+internal val PERSONAS = listOf(+ Persona(+ id = "doctor",+ label = "Doctor",+ defaultAgent = AgentMode.MONITOR,+ systemPrompt = "You are a knowledgeable general-practice doctor talking a patient through a " ++ "health question. Ask about the symptoms that would change your answer before giving one, " ++ "explain what is likely going on in plain language, and say what would usually help. " ++ "You are NOT the user's doctor and you are not making a diagnosis: say so plainly in your " ++ "first substantial reply, and never present a possibility as a confirmed condition. " ++ "Tell the user to seek in-person care when the picture is unclear, when symptoms persist " ++ "or worsen, and immediately — before anything else in your reply — when anything suggests " ++ "an emergency (chest pain, trouble breathing, stroke signs, severe bleeding, suicidal " ++ "thoughts). Never give dosing instructions for prescription medication."+ ),+ Persona(+ id = "chef",+ label = "Chef",+ defaultAgent = AgentMode.MONITOR,+ systemPrompt = "You are a working chef helping someone cook. Start from what they actually have " ++ "and how much time they have, and give recipes as short numbered steps with real quantities " ++ "and pan temperatures. Offer substitutions for anything hard to find, call out the step where " ++ "a dish is usually ruined, and flag common allergens in what you suggest. Keep food safety " ++ "advice (cooking temperatures, storage times, reheating) accurate rather than relaxed."+ ),+ Persona(+ id = "fitness_coach",+ label = "Fitness Coach",+ defaultAgent = AgentMode.MONITOR,+ systemPrompt = "You are a personal trainer. Ask about experience level, available equipment and " ++ "any injuries before programming anything, then give concrete sessions — exercises, sets, " ++ "reps, rest, and how to progress week to week. Cue form in a sentence or two per lift. " ++ "You are not a doctor or a physiotherapist: say so when the user describes pain, and send " ++ "them to a professional for anything that hurts rather than working around it."+ ),+ Persona(+ id = "tutor",+ label = "Tutor",+ defaultAgent = AgentMode.MONITOR,+ systemPrompt = "You are a patient tutor. Find out what the user already understands, then teach " ++ "from there in small steps with a worked example before the abstraction. Ask them to try the " ++ "next step themselves instead of finishing every problem for them, and when they are wrong " ++ "point at the specific move that went wrong rather than restating the whole solution. " ++ "If the work looks like homework being handed to you, help them solve it — do not just " ++ "produce an answer to copy."+ ),+ Persona(+ id = "travel_planner",+ label = "Travel Planner",+ defaultAgent = AgentMode.MONITOR,+ systemPrompt = "You are a well-travelled trip planner. Pin down dates, budget, pace and who is " ++ "travelling before proposing anything, then give day-by-day itineraries that account for " ++ "travel time between stops and the hours places actually keep. Name specific neighbourhoods " ++ "and options rather than generic advice, and say when something needs booking ahead. " ++ "Be explicit that prices, opening hours and entry requirements change, and that visas and " ++ "travel advisories must be checked against official sources."+ ),+ Persona(+ id = "handyman",+ label = "Handyman",+ defaultAgent = AgentMode.MONITOR,+ systemPrompt = "You are an experienced handyman walking someone through a repair. Work out what " ++ "the thing actually is and what tools they own, then give ordered steps with the tools and " ++ "parts named. Lead with the safety step — power off at the breaker, water off at the valve, " ++ "eye protection — whenever one applies. Say plainly when a job belongs to a licensed " ++ "electrician, plumber or gas fitter, and do not talk the user through it anyway."+ )+)++/**+ * Resolve a persisted [Persona.id]. Unknown ids — a persona removed in an app+ * update, or a hand-edited chat file — resolve to null, the same tolerance the+ * saved agent mode gets, so a stale id degrades to a plain chat instead of+ * failing to open.+ */+internal fun personaById(id: String?): Persona? =+ id?.let { wanted -> PERSONAS.firstOrNull { it.id == wanted } }++/**+ * The persona picker on the home screen, between the agent selector and the+ * starter chips: agent and persona both describe how the chat about to start+ * will behave, while the starters below are only a first thing to say.+ *+ * Styled like [AgentModeSelector]'s halves rather than Material's FilterChip,+ * and for the same reason — `secondaryContainer` goes translucent under the+ * glass skins, so the chosen chip is carried by an opaque accent fill, an+ * accent outline and a bold label instead. Tapping the chosen chip clears it,+ * which is the only way back to a plain chat without starting a new one.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+internal fun PersonaRow(+ personas: List<Persona>,+ selectedId: String?,+ onPick: (Persona?) -> Unit,+ modifier: Modifier = Modifier+) {+ val scheme = MaterialTheme.colorScheme+ Column(+ modifier = modifier.testTag("persona_row"),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ Text(+ "Persona",+ style = MaterialTheme.typography.labelMedium,+ color = scheme.onSurfaceVariant+ )+ Spacer(modifier = Modifier.height(8.dp))+ FlowRow(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ personas.forEach { persona ->+ PersonaChip(+ persona = persona,+ selected = persona.id == selectedId,+ onClick = { onPick(if (persona.id == selectedId) null else persona) }+ )+ }+ }+ }+}++/** One chip of [PersonaRow]. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun PersonaChip(+ persona: Persona,+ selected: Boolean,+ onClick: () -> Unit+) {+ val scheme = MaterialTheme.colorScheme+ val colorSpec = motionSpec<Color>(180)+ // Same veil as the agent selector: the light skins' containers sit a few+ // points off their near-white ground, and a fill that pale reads as none.+ val filled = scheme.primary.copy(alpha = 0.16f).compositeOver(scheme.primaryContainer)+ val container by animateColorAsState(+ targetValue = if (selected) filled else Color.Transparent,+ animationSpec = colorSpec,+ label = "personaContainer"+ )+ val content by animateColorAsState(+ targetValue = if (selected) scheme.onPrimaryContainer else scheme.onSurfaceVariant.copy(alpha = 0.75f),+ animationSpec = colorSpec,+ label = "personaContent"+ )+ val outline by animateColorAsState(+ targetValue = if (selected) scheme.primary else scheme.outlineVariant.copy(alpha = 0.6f),+ animationSpec = colorSpec,+ label = "personaOutline"+ )+ Surface(+ selected = selected,+ onClick = onClick,+ shape = CircleShape,+ color = container,+ contentColor = content,+ border = BorderStroke(if (selected) 1.5.dp else 1.dp, outline),+ modifier = Modifier.testTag("persona_${persona.id}")+ ) {+ Text(+ persona.label,+ style = MaterialTheme.typography.labelLarge,+ fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,+ textAlign = TextAlign.Center,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)+ )+ }+}diff --git a/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt b/app/src/test/java/com/gotcha/agent/AgentPromptTest.ktindex 675d163..fc7c0b6 100644--- a/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt+++ b/app/src/test/java/com/gotcha/agent/AgentPromptTest.kt@@ -85,12 +85,13 @@ class AgentPromptTest {private suspend fun requestBodyFor(mode: AgentMode,- settings: Settings = testSettings()+ settings: Settings = testSettings(),+ personaId: String? = null): String {server.enqueue(MockResponse().setBody("""{"choices":[{"message":{"role":"assistant","content":"ok"}}]}"""))- buildEngine(mode, settings).run(mode)+ buildEngine(mode, settings).apply { sessionPersonaId = personaId }.run(mode)return server.takeRequest().body.readUtf8()}@@ -172,4 +173,34 @@ class AgentPromptTest {val body = requestBodyFor(AgentMode.OPERATOR)assertFalse(body.contains("how they want replies written"))}++ @Test+ fun `chosen persona reaches the system prompt`() = runTest {+ val body = requestBodyFor(AgentMode.MONITOR, personaId = "doctor")+ assertTrue(body.contains("has chosen the Doctor persona"))+ // Not the costume alone: the disclaimer the persona carries has to land too.+ assertTrue(body.contains("you are not making a diagnosis"))+ }++ @Test+ fun `no persona adds no directive`() = runTest {+ val body = requestBodyFor(AgentMode.MONITOR)+ assertFalse(body.contains("has chosen the"))+ }++ @Test+ fun `an unknown persona id is ignored rather than failing the turn`() = runTest {+ val body = requestBodyFor(AgentMode.MONITOR, personaId = "no-such-persona")+ assertFalse(body.contains("has chosen the"))+ }++ @Test+ fun `the mode reminder still follows the persona directive`() = runTest {+ // The role must never be able to talk the agent out of its mode limits,+ // so the read-only reminder stays the last word in the system message.+ val body = requestBodyFor(AgentMode.MONITOR, personaId = "doctor")+ val persona = body.indexOf("has chosen the Doctor persona")+ val reminder = body.indexOf("You are in MONITOR (read-only) mode")+ assertTrue(persona in 0 until reminder)+ }}diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.ktnew file mode 100644index 0000000..f39f188--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelPersonaTest.kt@@ -0,0 +1,164 @@+package com.gotcha.agent++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.ChatSession+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.llm.ChatMessage+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.tools.AgentMode+import com.gotcha.ui.PERSONAS+import com.gotcha.ui.personaById+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitive+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper++/**+ * The persona picked on the home screen decides how every turn of that chat is+ * answered, so what matters is where it ends up: in the UI state the picker+ * reads back, and on the engine, which is the only thing the system prompt is+ * built from.+ *+ * Only the synchronous entry points are exercised, for the reason spelled out+ * in [ChatViewModelContextUsageTest] — `viewModelScope.launch` hands off to+ * Dispatchers.IO, and that round trip isn't observable from this tier. The+ * reopen path is covered by the round-trip test in+ * [com.gotcha.data.ChatHistoryRepositoryTest] plus the engine-side assertions+ * in [AgentPromptTest].+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ChatViewModelPersonaTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private lateinit var settingsRepository: SettingsRepository+ private lateinit var historyRepository: ChatHistoryRepository+ private lateinit var viewModel: ChatViewModel++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ settingsRepository = SettingsRepository(application)+ historyRepository = ChatHistoryRepository(application)+ settingsRepository.save(Settings(apiKey = "test-key"))+ viewModel = ChatViewModel(application)+ ShadowLooper.idleMainLooper()+ }++ @After+ fun tearDown() {+ runBlocking { historyRepository.deleteSession("persona-session") }+ }++ /** The engine is private; its persona is what the system prompt is built from. */+ private fun enginePersonaId(): String? {+ val field = ChatViewModel::class.java.getDeclaredField("agentEngine").apply { isAccessible = true }+ return (field.get(viewModel) as AgentEngine).sessionPersonaId+ }++ private fun seedMessages(messages: List<UiMessage>) {+ val stateField = ChatViewModel::class.java.getDeclaredField("_uiState").apply { isAccessible = true }++ @Suppress("UNCHECKED_CAST")+ val flow = stateField.get(viewModel) as MutableStateFlow<ChatUiState>+ flow.value = flow.value.copy(messages = messages)+ }++ @Test+ fun `picking a persona stamps it on the chat and the engine`() {+ val doctor = requireNotNull(personaById("doctor"))++ viewModel.setPersona(doctor)++ assertEquals("doctor", viewModel.uiState.value.activePersonaId)+ assertEquals("doctor", enginePersonaId())+ }++ @Test+ fun `a persona applies its own default mode`() {+ // Seeded personas all start read-only; the selector has to follow so the+ // user can see where the persona put them.+ viewModel.setAgent(AgentMode.OPERATOR)++ viewModel.setPersona(requireNotNull(personaById("doctor")))++ assertEquals(AgentMode.MONITOR, viewModel.uiState.value.activeAgent)+ }++ @Test+ fun `tapping the chosen persona again clears it without moving the mode`() {+ viewModel.setPersona(requireNotNull(personaById("chef")))+ viewModel.setAgent(AgentMode.OPERATOR)++ viewModel.setPersona(null)++ assertNull(viewModel.uiState.value.activePersonaId)+ assertNull(enginePersonaId())+ assertEquals(AgentMode.OPERATOR, viewModel.uiState.value.activeAgent)+ }++ @Test+ fun `a chat that already has messages keeps the persona it started with`() {+ viewModel.setPersona(requireNotNull(personaById("tutor")))+ seedMessages(listOf(UiMessage(id = 1, kind = MessageKind.USER, text = "hello")))++ viewModel.setPersona(requireNotNull(personaById("chef")))++ assertEquals("tutor", viewModel.uiState.value.activePersonaId)+ assertEquals("tutor", enginePersonaId())+ }++ @Test+ fun `a new chat never inherits the previous persona`() {+ viewModel.setPersona(PERSONAS.first())++ viewModel.clearChat()++ assertNull(viewModel.uiState.value.activePersonaId)+ assertNull(enginePersonaId())+ }++ @Test+ fun `a saved session carries its persona back`() = runBlocking {+ historyRepository.saveSession(+ ChatSession(+ id = "persona-session",+ title = "Knee pain",+ lastModified = 1L,+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("hi"))),+ personaId = "doctor"+ )+ )++ viewModel.openSession("persona-session")+ awaitPersona("doctor")++ assertEquals("doctor", viewModel.uiState.value.activePersonaId)+ assertEquals("doctor", enginePersonaId())+ }++ /** openSession suspends on IO and resumes on Main; drain until it lands. */+ private fun awaitPersona(expected: String) {+ repeat(POLL_ATTEMPTS) {+ ShadowLooper.idleMainLooper()+ if (viewModel.uiState.value.activePersonaId == expected) return+ Thread.sleep(POLL_INTERVAL_MS)+ }+ }++ private companion object {+ const val POLL_ATTEMPTS = 100+ const val POLL_INTERVAL_MS = 20L+ }+}diff --git a/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt b/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.ktindex 5f215c7..94009a4 100644--- a/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt+++ b/app/src/test/java/com/gotcha/data/ChatHistoryRepositoryTest.kt@@ -68,6 +68,20 @@ class ChatHistoryRepositoryTest {assertFalse(repo.loadSession("legacy")!!.isSample)}+ @Test+ fun `the chosen persona survives a round-trip and defaults to none`() = runBlocking {+ val dir = tmp.newFolder("chats")+ val repo = ChatHistoryRepository(dir)+ repo.saveSession(session("in-role").copy(personaId = "doctor"))+ assertEquals("doctor", repo.loadSession("in-role")!!.personaId)++ // A chat written before personas existed carries no such field.+ File(dir, "legacy.json").writeText(+ """{"id":"legacy","title":"Old","lastModified":0,"messages":[]}"""+ )+ assertNull(repo.loadSession("legacy")!!.personaId)+ }+@Testfun `saving without touch keeps the session's own timestamp`() = runBlocking {val repo = ChatHistoryRepository(tmp.newFolder("chats"))diff --git a/app/src/test/java/com/gotcha/ui/PersonasTest.kt b/app/src/test/java/com/gotcha/ui/PersonasTest.ktnew file mode 100644index 0000000..f310576--- /dev/null+++ b/app/src/test/java/com/gotcha/ui/PersonasTest.kt@@ -0,0 +1,82 @@+package com.gotcha.ui++import com.gotcha.tools.AgentMode+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * [PERSONAS] is a hand-edited list the home screen draws blindly and chat files+ * refer to by id. These are the invariants both rely on — plus the one that is+ * about the product rather than the plumbing: a persona that dresses up as a+ * regulated profession has to say it isn't one.+ */+class PersonasTest {++ @Test+ fun `offers a spread of personas`() {+ assertTrue("Expected a curated set to choose from", PERSONAS.size >= 4)+ }++ @Test+ fun `every persona has an id, a label and a prompt`() {+ PERSONAS.forEach { persona ->+ assertTrue("Blank id in $persona", persona.id.isNotBlank())+ assertTrue("Blank label in $persona", persona.label.isNotBlank())+ // The chips wrap, but a long one still looks broken on a phone.+ assertTrue("Label too long to fit a chip: '${persona.label}'", persona.label.length <= 20)+ assertTrue(+ "Persona '${persona.id}' needs a prompt with something in it",+ persona.systemPrompt.length >= 120+ )+ }+ }++ @Test+ fun `ids are unique and stable-looking`() {+ // Ids are persisted on chat files and used as test tags, so duplicates+ // would make a reopened chat ambiguous.+ val ids = PERSONAS.map { it.id }+ assertEquals(ids.size, ids.distinct().size)+ ids.forEach { id ->+ assertTrue("Persona id '$id' should be lowercase snake_case", id.matches(Regex("[a-z0-9_]+")))+ }+ }++ @Test+ fun `every seeded persona starts read-only`() {+ // A persona is something to talk to; none of the seeded set has any+ // reason to start with the device unlocked.+ PERSONAS.forEach { persona ->+ assertEquals(persona.id, AgentMode.MONITOR, persona.defaultAgent)+ }+ }++ @Test+ fun `professional personas carry their disclaimer`() {+ val doctor = requireNotNull(personaById("doctor"))+ assertTrue(+ "The Doctor persona must refuse to pass as the user's own doctor",+ doctor.systemPrompt.contains("not making a diagnosis")+ )+ assertTrue(+ "The Doctor persona must route emergencies to real care",+ doctor.systemPrompt.contains("emergency")+ )+ val coach = requireNotNull(personaById("fitness_coach"))+ assertTrue(+ "The Fitness Coach persona must not stand in for a clinician",+ coach.systemPrompt.contains("not a doctor")+ )+ }++ @Test+ fun `lookup resolves known ids and tolerates the rest`() {+ assertNotNull(personaById(PERSONAS.first().id))+ // A persona dropped in an app update leaves its id behind on old chats.+ assertNull(personaById("persona-that-was-removed"))+ assertNull(personaById(null))+ }+}