diff --git a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt index 416c1ce2f..f106563e0 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt @@ -294,6 +294,7 @@ class AndCodeApplication : Application() { runtimeDirectory = runtimeDirectory, abi = abi, accessCoordinator = accessCoordinator, + userAgentInstructions = { settings.agentInstructions }, ) localRuntimeInstaller = installer // Guest startup commands (issue #379): read from the workspace on every runtime start, diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/connection/SecureSettingsRepository.kt b/app/src/main/java/com/yugahashimoto/andcode/data/connection/SecureSettingsRepository.kt index 6b77346cd..c45601ec6 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/data/connection/SecureSettingsRepository.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/data/connection/SecureSettingsRepository.kt @@ -468,6 +468,16 @@ class SecureSettingsRepository(context: Context) : get() = preferences.getBoolean(KEY_ANALYTICS_ENABLED, false) set(value) = preferences.edit().putBoolean(KEY_ANALYTICS_ENABLED, value).apply() + /** + * Extra instructions appended to every agent's shared AndCode context. + * + * The bundled context is the part AndCode owns; this is the user's own addition, applied to + * OpenCode, Claude Code, Antigravity and Codex together so a rule only has to be written once. + */ + var agentInstructions: String + get() = preferences.getString(KEY_AGENT_INSTRUCTIONS, "") ?: "" + set(value) = preferences.edit().putString(KEY_AGENT_INSTRUCTIONS, value).apply() + /** * Lets the in-guest agent drive the Guest Browser by exposing its WebView devtools socket. * @@ -616,6 +626,7 @@ class SecureSettingsRepository(context: Context) : private const val KEY_LANGUAGE = "language" private const val KEY_LIVE_TRANSCRIPT_ENABLED = "live_transcript_enabled" private const val KEY_ANALYTICS_ENABLED = "analytics_enabled" + private const val KEY_AGENT_INSTRUCTIONS = "agent_instructions" private const val KEY_GUEST_BROWSER_AGENT_CONTROL = "guest_browser_agent_control" private const val KEY_LOCAL_RUNTIME_IDLE_STOP_ENABLED = "local_runtime_idle_stop_enabled" private const val KEY_LOCAL_RUNTIME_STOPPED_BY_USER = "local_runtime_stopped_by_user" diff --git a/app/src/main/java/com/yugahashimoto/andcode/data/settings/AppPreferencesRepository.kt b/app/src/main/java/com/yugahashimoto/andcode/data/settings/AppPreferencesRepository.kt index 8fa5df2d9..514f3a267 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/data/settings/AppPreferencesRepository.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/data/settings/AppPreferencesRepository.kt @@ -53,6 +53,8 @@ data class AppPreferences( val language: String = "system", val liveTranscriptEnabled: Boolean = false, val analyticsEnabled: Boolean = false, + /** Extra instructions appended to every agent's shared AndCode context. */ + val agentInstructions: String = "", val guestBrowserAgentControlEnabled: Boolean = false, val localRuntimeIdleStopEnabled: Boolean = true, val autoArchiveStaleEnabled: Boolean = false, @@ -106,6 +108,7 @@ class AppPreferencesRepository( language = settings.language, liveTranscriptEnabled = settings.liveTranscriptEnabled, analyticsEnabled = settings.analyticsEnabled, + agentInstructions = settings.agentInstructions, guestBrowserAgentControlEnabled = settings.guestBrowserAgentControlEnabled, localRuntimeIdleStopEnabled = settings.localRuntimeIdleStopEnabled, autoArchiveStaleEnabled = settings.autoArchiveStaleEnabled, @@ -360,6 +363,11 @@ class AppPreferencesRepository( mutableState.update { it.copy(analyticsEnabled = enabled) } } + fun setAgentInstructions(instructions: String) { + settings.agentInstructions = instructions + mutableState.update { it.copy(agentInstructions = instructions) } + } + fun setGuestBrowserAgentControlEnabled(enabled: Boolean) { settings.guestBrowserAgentControlEnabled = enabled mutableState.update { it.copy(guestBrowserAgentControlEnabled = enabled) } diff --git a/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt b/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt index 8c6c84dbb..da235f412 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt @@ -77,11 +77,13 @@ val appModule = single { val runtimeDirectory: File = get() val abi = Build.SUPPORTED_ABIS.firstOrNull().orEmpty() + val settings: SecureSettingsRepository = get() LocalRuntimeInstaller( context = androidContext(), runtimeDirectory = runtimeDirectory, abi = abi, accessCoordinator = get(), + userAgentInstructions = { settings.agentInstructions }, ) } diff --git a/app/src/main/java/com/yugahashimoto/andcode/di/ViewModelModule.kt b/app/src/main/java/com/yugahashimoto/andcode/di/ViewModelModule.kt index af461c427..fd65799bd 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/di/ViewModelModule.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/di/ViewModelModule.kt @@ -27,6 +27,8 @@ val viewModelModule = // Same Codex fast-mode wiring as the factory in ui/AndCodeApp.kt; keep the two in step. onCodexFastModeChanged = preferences::setCodexFastMode, initialCodexFastMode = settings.codexFastMode, + initialSendBehavior = preferences.state.value.sendBehavior, + isSessionRunning = { id -> id in app.activityRepository.state.value.activeSessionIds }, // Kept in step with the hand-rolled factory in ui/AndCodeApp.kt: both construction // paths have to park the connection probe and stall watchdog while the app is // backgrounded, or whichever one the screen happens to use decides whether those diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt index 7662ba57f..7f0320adb 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatHomeScreen.kt @@ -250,6 +250,12 @@ fun ChatHomeScreen( supportsPermissions: Boolean = true, onToggleAutoAccept: (Boolean) -> Unit = {}, sendBehavior: String = "interrupt", + /** + * True for a runtime that always queues a send behind a running turn instead of interrupting it + * (Antigravity), so the composer offers send-while-running the same way the "queue" setting + * does rather than hiding the send action behind the stop button. + */ + forcesQueue: Boolean = false, enterToSend: Boolean = false, /** Whether reasoning/thinking cards should start expanded when the activity sheet opens. */ autoExpandReasoning: Boolean = false, @@ -769,6 +775,7 @@ fun ChatHomeScreen( onSelectSystemPrompt = onSelectSystemPrompt, onToggleAutoAccept = onToggleAutoAccept, sendBehavior = sendBehavior, + forcesQueue = forcesQueue, enterToSend = enterToSend, contextTokensUsed = state.contextTokensUsed, contextLimit = @@ -1438,6 +1445,7 @@ private fun ChatComposer( selectedSystemPromptId: String?, onSelectSystemPrompt: (String?) -> Unit, sendBehavior: String, + forcesQueue: Boolean, enterToSend: Boolean, contextTokensUsed: Long, contextLimit: Long, @@ -1748,7 +1756,11 @@ private fun ChatComposer( } } if (isRunning) { - if (sendBehavior == "queue") { + // A queueing runtime (the "queue" setting, or Antigravity which always + // queues) keeps the send action available mid-turn: the prompt waits behind + // the running turn instead of interrupting it, and rejecting it here left + // the user with no way to add to a long-running turn at all. + if (sendBehavior == "queue" || forcesQueue) { Surface( shape = RoundedCornerShape(100.dp), color = MaterialTheme.colorScheme.tertiaryContainer, @@ -1760,6 +1772,17 @@ private fun ChatComposer( style = MaterialTheme.typography.labelSmall, ) } + FilledIconButton( + onClick = onSend, + enabled = input.isNotBlank() || attachments.isNotEmpty(), + modifier = Modifier.size(38.dp), + ) { + Icon( + Icons.AutoMirrored.Filled.Send, + contentDescription = stringResource(R.string.send_description), + modifier = Modifier.size(20.dp), + ) + } } FilledIconButton(onClick = onAbort, modifier = Modifier.size(38.dp)) { Icon(Icons.Default.Stop, contentDescription = stringResource(R.string.stop_run)) diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt index 51e89c354..a42889ecc 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt @@ -149,6 +149,12 @@ internal fun mergeReloadedMessages( existing: List, previewsByFilename: Map = emptyMap(), retainIds: Set = emptySet(), + /** + * Texts of user prompts still waiting in the send queue. They are on screen but not in the + * runtime's transcript yet, so a reload driven by the previous turn would erase them until the + * drained prompt is persisted. Kept here, they survive that reload exactly once. + */ + retainUserTexts: Set = emptySet(), ): List { // Nothing persisted yet means nothing to reconcile against: keeping what is on screen is both // correct and what callers did with an empty result before this could ever retain anything. @@ -204,6 +210,22 @@ internal fun mergeReloadedMessages( } } } + if (retainUserTexts.isNotEmpty()) { + val reloadedUserTexts = reloaded.filter { it.isUser }.map { it.text }.toSet() + existing + .asSequence() + .filter { it.isUser && it.text in retainUserTexts && it.text !in reloadedUserTexts && it !in merged } + .forEach { message -> + // Queued before the reply it is sitting behind finished, so it keeps that place + // rather than jumping to the bottom of a timeline it did not take part in yet. + val index = merged.indexOfFirst { it.timestamp > message.timestamp } + if (index >= 0) { + merged.add(index, message) + } else { + merged.add(message) + } + } + } return merged } @@ -650,6 +672,16 @@ class ChatViewModel( private val onCodexFastModeChanged: (Boolean?) -> Unit = {}, /** The user's saved Codex fast-mode choice, read when the ViewModel starts. */ private val initialCodexFastMode: Boolean? = null, + /** The user's saved send behavior ("interrupt" or "queue"), read when the ViewModel starts. */ + private val initialSendBehavior: String = "interrupt", + /** + * Whether a session already has a run in flight, learned from the app's activity store. + * + * Opening such a chat used to leave [ChatUiState.isRunning] false, so a send there was treated + * as idle and went straight to the runtime. Antigravity cannot interrupt a one-shot turn (it + * kills the process), so that send silently discarded the run the user was watching. + */ + private val isSessionRunning: (String) -> Boolean = { false }, ) : ViewModel() { private val _uiState = MutableStateFlow( @@ -657,7 +689,7 @@ class ChatViewModel( ) val uiState: StateFlow = _uiState.asStateFlow() - private val _sendBehavior = MutableStateFlow("interrupt") + private val _sendBehavior = MutableStateFlow(initialSendBehavior) val sendBehavior: StateFlow = _sendBehavior.asStateFlow() private val _workspaceTitleSource = MutableStateFlow("title") @@ -755,18 +787,20 @@ class ChatViewModel( .distinctUntilChanged() .collect { (sessionId, running) -> if (sessionId == null) return@collect - // The run we last reported as active is over the moment the open chat - // stops running OR the client moves to another chat (it can no longer - // track the old one's isRunning). The previous logic keyed on the - // (sessionId, isRunning) pair, so a mid-turn navigation produced the - // transition (oldSession, true) -> (newSession, false) and matched neither - // branch: the old session was never reported finished and its drawer dot - // stayed on the spinner forever. Clear the stale run explicitly here so the - // drawer only reflects chats the runtime itself still reports as active. + // Only a run of the chat that is still on screen can be tracked here, so + // moving to another chat hands the old one to the runtime's own stream + // rather than reporting it finished. Reporting it finished on navigation + // cleared the drawer spinner for a turn that was still in flight, and a + // runtime that emits no busy status (Antigravity) never put it back until + // the next streamed token - so the drawer showed the chat as idle mid-run. + // The activity store still settles the session on the runtime's idle (or + // its watchdog if that never arrives). runningSession?.let { previous -> - if (previous != sessionId || !running) { + if (previous == sessionId && !running) { onRunStateChanged(previous, false) runningSession = null + } else if (previous != sessionId) { + runningSession = null } } if (running && runningSession != sessionId) { @@ -1094,6 +1128,10 @@ class ChatViewModel( // state too — otherwise the composer opens the new chat already stuck on the stop button // because the old chat happened to be mid-turn when the user navigated away. val switchingSession = _uiState.value.sessionId != sessionId + // Opening a chat whose run is still in flight (started before this client opened it) must + // not look idle: a send there would reach the runtime as an interrupt, which on Antigravity + // kills the one-shot process instead of cancelling anything. + val alreadyRunning = switchingSession && isSessionRunning(sessionId) if (switchingSession) pendingInterrupts.clear() // The composer is moving to another chat, so a preset chosen for the one it is leaving - // which never got a session to record it on - stops applying here. @@ -1114,12 +1152,13 @@ class ChatViewModel( permissions = emptyList(), pendingQuestions = emptyList(), sessionDirectory = null, - isRunning = if (switchingSession) false else it.isRunning, - isThinking = if (switchingSession) false else it.isThinking, + isRunning = if (switchingSession) alreadyRunning else it.isRunning, + isThinking = if (switchingSession) alreadyRunning else it.isThinking, dismissedTodoBarId = null, error = null, ) } + if (alreadyRunning) recordProgress() if (parent == null) resolveParentSession(sessionId) refreshPendingQuestions(sessionId) viewModelScope.launch { @@ -1131,7 +1170,12 @@ class ChatViewModel( _uiState.update { it.copy( isLoadingHistory = false, - messages = mergeReloadedMessages(messages.mapNotNull(::toUiMessage), it.messages), + messages = + mergeReloadedMessages( + messages.mapNotNull(::toUiMessage), + it.messages, + retainUserTexts = pendingQueuedTexts(), + ), selectedProviderId = selectedModel?.providerId ?: it.selectedProviderId, selectedModelId = selectedModel?.modelId ?: it.selectedModelId, ) @@ -1391,7 +1435,14 @@ class ChatViewModel( ) { val messages = currentBackend.listMessages(sessionId) _uiState.update { - it.copy(messages = mergeReloadedMessages(messages.mapNotNull(::toUiMessage), it.messages)) + it.copy( + messages = + mergeReloadedMessages( + messages.mapNotNull(::toUiMessage), + it.messages, + retainUserTexts = pendingQueuedTexts(), + ), + ) } } @@ -1417,6 +1468,17 @@ class ChatViewModel( } fun sendMessage(text: String) { + sendMessage(text, fromQueue = false) + } + + /** + * [fromQueue] means the prompt was already drawn as the user's bubble when it was queued, so + * sending it now must not add a second copy to the transcript. + */ + private fun sendMessage( + text: String, + fromQueue: Boolean, + ) { val normalized = text.trim() val pendingAttachments = _uiState.value.attachments val messageIdsBeforeSend = _uiState.value.messages.map { it.id }.toSet() @@ -1453,7 +1515,7 @@ class ChatViewModel( // (OpenCode expands the template server-side) rather than sent as a plain prompt. val slashCommand = matchSlashCommand(normalized) if (slashCommand != null) { - sendSlashCommand(slashCommand.first, slashCommand.second) + sendSlashCommand(slashCommand.first, slashCommand.second, fromQueue) return } @@ -1470,7 +1532,7 @@ class ChatViewModel( ) _uiState.update { it.copy( - messages = it.messages + userMessage, + messages = if (fromQueue) it.messages else it.messages + userMessage, offlineQueue = it.offlineQueue + outgoingText, isOfflineQueued = true, attachments = emptyList(), @@ -1480,6 +1542,17 @@ class ChatViewModel( return } + val userMessage = + ChatMessage( + isUser = true, + parts = + outgoingText.takeIf { it.isNotEmpty() }?.let { + listOf(ChatPart.Text(id = UUID.randomUUID().toString(), text = it)) + }.orEmpty(), + attachments = pendingAttachments, + imagePreviews = _uiState.value.imagePreviews, + ) + // Some runtimes (Antigravity) must always queue behind a running turn rather than interrupt // it - interrupting there kills the in-flight one-shot process instead of cancelling a // request, which surfaced as a crash. See RuntimeCapabilities.forcesQueue. @@ -1488,24 +1561,23 @@ class ChatViewModel( messageQueue.update { it + QueuedPrompt(outgoingText, modelAttachments, _uiState.value.imagePreviews) } - _uiState.update { it.copy(attachments = emptyList(), imagePreviews = emptyList()) } + // The prompt waits for the running turn, but it has to be visible while it waits: the + // old path dropped it from the screen entirely, which read as if the send had been + // swallowed. When it is already drawn (a drain), only the attachments are consumed. + _uiState.update { + it.copy( + messages = if (fromQueue) it.messages else it.messages + userMessage, + attachments = emptyList(), + imagePreviews = emptyList(), + ) + } return } val interrupting = _uiState.value.isRunning - val userMessage = - ChatMessage( - isUser = true, - parts = - outgoingText.takeIf { it.isNotEmpty() }?.let { - listOf(ChatPart.Text(id = UUID.randomUUID().toString(), text = it)) - }.orEmpty(), - attachments = pendingAttachments, - imagePreviews = _uiState.value.imagePreviews, - ) _uiState.update { it.copy( - messages = it.messages + userMessage, + messages = if (fromQueue) it.messages else it.messages + userMessage, isRunning = true, isThinking = true, retry = null, @@ -1602,6 +1674,7 @@ class ChatViewModel( _uiState.value.messages, pendingPreviewsByFilename, retainIds, + retainUserTexts = pendingQueuedTexts(), ) if (uiMessages.isNotEmpty() && uiMessages != _uiState.value.messages) { _uiState.update { it.copy(messages = uiMessages) } @@ -1644,6 +1717,7 @@ class ChatViewModel( _uiState.value.messages, pendingPreviewsByFilename, retainedIds, + retainUserTexts = pendingQueuedTexts(), ) _uiState.update { it.copy( @@ -1655,6 +1729,10 @@ class ChatViewModel( // Refresh after the final assistant message is persisted. The // pre-send refresh only contains the previous turn's tokens. refreshContextUsage(targetSessionId) + // The turn ended through this fallback rather than the runtime's own + // idle, so the idle handler will not drain the queue: a prompt sent + // while the run was going would wait forever. + drainQueue() } } }.onFailure { error -> @@ -1682,6 +1760,14 @@ class ChatViewModel( fun sendSlashCommand( command: String, arguments: String, + ) { + sendSlashCommand(command, arguments, fromQueue = false) + } + + private fun sendSlashCommand( + command: String, + arguments: String, + fromQueue: Boolean, ) { val currentBackend = backend if (currentBackend == null) { @@ -1708,21 +1794,25 @@ class ChatViewModel( return } + val userMessage = + ChatMessage( + isUser = true, + parts = listOf(ChatPart.Text(id = UUID.randomUUID().toString(), text = displayText)), + ) + val mustQueue = (currentBackend as? RuntimeTarget)?.capabilities?.forcesQueue == true if ((_sendBehavior.value == "queue" || mustQueue) && _uiState.value.isRunning) { messageQueue.update { it + QueuedPrompt(displayText, emptyList(), emptyList()) } + if (!fromQueue) { + _uiState.update { it.copy(messages = it.messages + userMessage) } + } return } val interrupting = _uiState.value.isRunning - val userMessage = - ChatMessage( - isUser = true, - parts = listOf(ChatPart.Text(id = UUID.randomUUID().toString(), text = displayText)), - ) _uiState.update { it.copy( - messages = it.messages + userMessage, + messages = if (fromQueue) it.messages else it.messages + userMessage, isRunning = true, isThinking = true, retry = null, @@ -1802,6 +1892,7 @@ class ChatViewModel( serverMessages.mapNotNull(::toUiMessage), _uiState.value.messages, retainIds = retainIds, + retainUserTexts = pendingQueuedTexts(), ) if (uiMessages.isNotEmpty() && uiMessages != _uiState.value.messages) { _uiState.update { it.copy(messages = uiMessages) } @@ -1832,12 +1923,16 @@ class ChatViewModel( serverMessages.mapNotNull(::toUiMessage), it.messages, retainIds = retainedIds, + retainUserTexts = pendingQueuedTexts(), ), isRunning = false, isThinking = false, ) } refreshContextUsage(targetSessionId) + // See sendMessage: a turn ended by this fallback still has to drain + // prompts the user queued while it ran. + drainQueue() } } }.onFailure { error -> @@ -2329,6 +2424,7 @@ class ChatViewModel( messages.mapNotNull(::toUiMessage), it.messages, retainIds = retainedIds, + retainUserTexts = pendingQueuedTexts(), ), ) } @@ -2532,6 +2628,10 @@ class ChatViewModel( retainIds: Set = emptySet(), ) { val currentBackend = backend ?: return + // Captured before the launch: the idle handler drains the queue right after calling this, + // so reading it inside the coroutine would already see the queue emptied and drop the + // just-queued bubble from the reload. + val retainUserTexts = pendingQueuedTexts() viewModelScope.launch { runCatching { currentBackend.listMessages(sessionId) } .onSuccess { messages -> @@ -2540,6 +2640,7 @@ class ChatViewModel( messages.mapNotNull(::toUiMessage), _uiState.value.messages, retainIds = retainIds, + retainUserTexts = retainUserTexts, ) if (uiMessages.isNotEmpty()) { _uiState.update { it.copy(messages = uiMessages) } @@ -2681,6 +2782,12 @@ class ChatViewModel( return _uiState.value.messages.firstOrNull { it.id == messageId }?.text } + /** + * Prompts waiting in [messageQueue], by text. A transcript reload must keep their optimistic + * bubbles on screen even though the runtime has not been given them yet. + */ + private fun pendingQueuedTexts(): Set = messageQueue.value.mapTo(mutableSetOf()) { it.text } + private fun drainQueue() { val queued = messageQueue.value if (queued.isEmpty()) return @@ -2711,7 +2818,8 @@ class ChatViewModel( imagePreviews = queuedPrompt.imagePreviews, ) } - sendMessage(queuedPrompt.text) + // The bubble was drawn when this prompt was queued, so it is not added again here. + sendMessage(queuedPrompt.text, fromQueue = true) } override fun onCleared() { @@ -2800,6 +2908,7 @@ class ChatViewModel( messages.mapNotNull(::toUiMessage), it.messages, retainIds = retainedIds, + retainUserTexts = pendingQueuedTexts(), ), ) } diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/settings/AgentInstructionsScreen.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/settings/AgentInstructionsScreen.kt new file mode 100644 index 000000000..0ec3df6b4 --- /dev/null +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/settings/AgentInstructionsScreen.kt @@ -0,0 +1,114 @@ +package com.yugahashimoto.andcode.feature.settings + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.unit.dp +import com.yugahashimoto.andcode.R +import com.yugahashimoto.andcode.runtime.local.AND_CODE_AGENT_CONTEXT_ASSET +import kotlinx.coroutines.launch + +/** + * Lets the user add one set of instructions that every agent receives. + * + * The text is stored in settings and appended to the bundled AndCode context when the runtime + * writes each agent's own instruction file (OpenCode's instructions file, Claude Code's + * CLAUDE.md, Antigravity's GEMINI.md and Codex's AGENTS.md), so a rule only has to be written once + * instead of once per harness. The bundled part is shown read-only: it is what AndCode owns, and + * the user's addition is kept separate rather than mixed into it. + */ +@Composable +fun AgentInstructionsScreen( + savedInstructions: String, + onSave: (String) -> Unit, + onBack: () -> Unit, +) { + val context = LocalContext.current + val bundled = + remember { + runCatching { + context.assets.open(AND_CODE_AGENT_CONTEXT_ASSET).bufferedReader().use { it.readText() } + }.getOrDefault("") + } + var draft by rememberSaveable(savedInstructions) { mutableStateOf(savedInstructions) } + val snackbarHostState = remember { SnackbarHostState() } + val scope = rememberCoroutineScope() + val savedMessage = stringResource(R.string.agent_instructions_saved) + + SettingsScaffold( + title = stringResource(R.string.agent_instructions_title), + onBack = onBack, + snackbarHost = { SnackbarHost(snackbarHostState) }, + ) { padding -> + LazyColumn( + modifier = Modifier.fillMaxSize().padding(padding), + contentPadding = PaddingValues(start = 20.dp, end = 20.dp, top = 8.dp, bottom = 28.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + item { + Text( + text = stringResource(R.string.agent_instructions_description), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + item { + OutlinedTextField( + value = draft, + onValueChange = { draft = it }, + modifier = Modifier.fillMaxWidth().heightIn(min = 160.dp), + label = { Text(stringResource(R.string.agent_instructions_label)) }, + placeholder = { Text(stringResource(R.string.agent_instructions_hint)) }, + minLines = 6, + maxLines = 14, + ) + } + item { + Button( + onClick = { + onSave(draft) + scope.launch { snackbarHostState.showSnackbar(savedMessage) } + }, + enabled = draft != savedInstructions, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.agent_instructions_save)) + } + } + item { + SettingsSection(title = stringResource(R.string.agent_instructions_builtin_title)) { + Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) { + Text( + text = bundled, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/yugahashimoto/andcode/feature/settings/SettingsScreenV2.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/settings/SettingsScreenV2.kt index db35e8684..89f8de067 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/feature/settings/SettingsScreenV2.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/feature/settings/SettingsScreenV2.kt @@ -130,6 +130,7 @@ fun SettingsScreenV2( onSendBehaviorChange: (String) -> Unit = {}, enterToSend: Boolean = false, onEnterToSendChange: (Boolean) -> Unit = {}, + onOpenAgentInstructions: () -> Unit = {}, autoArchiveStaleEnabled: Boolean = false, onAutoArchiveStaleEnabledChange: (Boolean) -> Unit = {}, autoArchiveStaleDays: Int = 30, @@ -285,6 +286,12 @@ fun SettingsScreenV2( checked = enterToSend, onCheckedChange = onEnterToSendChange, ) + SettingsDivider() + SettingsRow( + icon = Icons.Default.DataObject, + title = stringResource(R.string.agent_instructions_row), + onClick = onOpenAgentInstructions, + ) } SettingsSection(title = stringResource(R.string.section_sessions_settings)) { diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AndCodeAgentContext.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AndCodeAgentContext.kt index 80e33f6c9..885bbec67 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AndCodeAgentContext.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AndCodeAgentContext.kt @@ -30,22 +30,41 @@ private val AGENT_CONTEXT_PATHS = "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + // Codex reads AGENTS.md from its home (CODEX_HOME, /root/.codex here) as global guidance. + "root/.codex/AGENTS.md", ) internal fun ensureAndCodeAgentContext( rootfs: File, context: Context, + userInstructions: String = "", ) { val agentContext = context.assets.open(AND_CODE_AGENT_CONTEXT_ASSET).use { input -> input.readBytes() } - installAndCodeAgentContext(rootfs, agentContext) + installAndCodeAgentContext(rootfs, agentContext, userInstructions) } /** - * Writes the AndCode environment blurb into each coding agent's instructions file (Claude Code's - * CLAUDE.md, Gemini's GEMINI.md, and OpenCode's instructions file). + * Appends the user's own instructions to the bundled blurb, so one rule applies to every agent. + * + * The user text is kept after the bundled part and under its own heading: the bundled blurb is + * AndCode's, and mixing the two made later edits to either one unreadable. Blank/whitespace-only + * text means "no addition" and leaves the bundled bytes untouched. + */ +internal fun composeAgentContext( + agentContext: ByteArray, + userInstructions: String, +): ByteArray { + val addition = userInstructions.trim() + if (addition.isEmpty()) return agentContext + return agentContext + "\n\n## User instructions\n\n$addition\n".toByteArray(Charsets.UTF_8) +} + +/** + * Writes the AndCode environment blurb into each coding agent's instructions file (OpenCode's + * instructions file, Claude Code's CLAUDE.md, Gemini's GEMINI.md and Codex's AGENTS.md). * * These are the exact files users write their own custom instructions into, and this runs on * every runtime start, so it must never clobber content the user has added. A path is only @@ -61,34 +80,37 @@ internal fun ensureAndCodeAgentContext( * This function is best-effort from top to bottom: it must never abort or throw out of runtime * startup, which calls it on every launch (four call sites in `LocalRuntimeInstaller`). Every * filesystem-touching step -- canonicalizing `rootfs` itself, the staging copy, the written-hashes - * sidecar, and each of the three instruction files -- is handled independently, and a filesystem + * sidecar, and each instruction file -- is handled independently, and a filesystem * problem on any single one of them is skipped rather than propagated: * - Canonicalizing `rootfs` can itself throw; that falls back to its absolute path rather than * aborting before any guard below even runs (see the fallback comment at the call site). * - The staging copy at [RUNTIME_CONTEXT_PATH] is only a convenience artifact nothing else reads, * so an unmanageable or unwritable path there is simply skipped. * - The written-hashes sidecar being unmanageable, unreadable, oversized, or unwritable does not - * stop the three instruction files below from being (re)installed. Any of those is treated as + * stop the instruction files below from being (re)installed. Any of those is treated as * an empty history: a target that already exists and differs from the current blurb is then * treated as user-edited and left alone, which is the safe direction. A sidecar that can't be * persisted afterwards simply means the write is retried on the next run; the install itself * still succeeds. - * - Each of the three instruction files is handled independently: hashing or writing one target - * can throw (an unreadable file, a parent path replaced with a file, permission errors) without - * affecting the other two, and without recording that target's hash as successfully written. + * - Each instruction file is handled independently: hashing or writing one target can throw + * (an unreadable file, a parent path replaced with a file, permission errors) without affecting + * the others, and without recording that target's hash as successfully written. * * The trade-off is that a failed install is silent: there is no signal back to the caller when a * path was skipped, by design, since surfacing or retrying failures is not worth risking runtime * startup over a best-effort convenience file. * - * The blurb's hash is computed directly from [agentContext] (see [sha256Hex]) rather than from + * The composed blurb's hash is computed directly from [agentContext] plus any user addition + * (see [composeAgentContext] and [sha256Hex]) rather than from * the staging file, so installing the instruction files never depends on that staging copy * existing. */ internal fun installAndCodeAgentContext( rootfs: File, agentContext: ByteArray, + userInstructions: String = "", ) { + val composedContext = composeAgentContext(agentContext, userInstructions) // Best-effort: File.canonicalFile can throw IOException on a filesystem loop or I/O error // around rootfs itself, which must not crash runtime startup before any guard below even // runs. Falling back to absoluteFile only ever makes manageablePathOrNull's rootfs-prefix @@ -102,7 +124,7 @@ internal fun installAndCodeAgentContext( } catch (e: IOException) { rootfs.absoluteFile } - val agentContextHash = sha256Hex(agentContext) + val agentContextHash = sha256Hex(composedContext) // Best-effort: this is only the app's own staging copy of the blurb; nothing below depends on // it existing, so neither an unmanageable path nor a failing write here may stop the real @@ -112,7 +134,7 @@ internal fun installAndCodeAgentContext( manageablePathOrNull(rootfsCanonical, File(rootfs, RUNTIME_CONTEXT_PATH))?.let { source -> try { source.parentFile?.mkdirs() - source.writeBytes(agentContext) + source.writeBytes(composedContext) } catch (e: IOException) { // Skip the staging copy -- see the comment above. } @@ -128,7 +150,7 @@ internal fun installAndCodeAgentContext( val target = manageablePathOrNull(rootfsCanonical, File(rootfs, relativePath)) ?: return@forEach // Best-effort per target: hashing or writing this one path can still throw (unreadable // file, a parent replaced with a file, permission errors) even though manageablePathOrNull - // passed moments ago. That must skip only this target, not abort the other two or runtime + // passed moments ago. That must skip only this target, not abort the others or runtime // startup, which is what the KDoc promises. If the write below fails partway, currentHash // is left null/stale and writtenHashes is never touched, so this target's hash is not // recorded as successfully written -- a later run will not mistake a failed write for @@ -149,7 +171,7 @@ internal fun installAndCodeAgentContext( } if (currentHash != agentContextHash) { target.parentFile?.mkdirs() - target.writeBytes(agentContext) + target.writeBytes(composedContext) } if (writtenHashes[relativePath] != agentContextHash) { writtenHashes[relativePath] = agentContextHash diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AntigravityRuntime.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AntigravityRuntime.kt index 0bb45feeb..1d65bc0e6 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AntigravityRuntime.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/AntigravityRuntime.kt @@ -70,6 +70,14 @@ class AntigravityRuntime( private val messageStore = AntigravityMessageStore(messagesFile, json) private val processes = ConcurrentHashMap() + /** + * One lock per session, so a waiting send for a chat does not serialize other chats. + * + * See [withSessionLock] for why a second send for the same session has to wait rather than kill + * the running turn. + */ + private val sessionLocks = ConcurrentHashMap() + /** See [AntigravityAbortTracker] for why an intentional kill must not be reported as a crash. */ private val abortTracker = AntigravityAbortTracker() @@ -232,181 +240,188 @@ class AntigravityRuntime( val runtime = installedRuntimeProvider() ?: error("Linux environment is not installed") require(isInstalled()) { "Antigravity is not installed" } AntigravityGuestSettings.repair(runtime) - val promptWithAttachments = - prepareAntigravityPrompt( - runtimeDirectory, - sessionId, - records[sessionId]?.lastStep ?: 0, - prompt, - attachments, - ) - // Normally unreachable now that the app always queues a send behind a running - // Antigravity turn (see RuntimeCapabilities.forcesQueue) - kept as a safety net for - // e.g. two clients racing the same session. Marking the kill as intentional here is - // what stops the superseded call's own send() below from reporting it as a crash. - processes.remove(sessionId)?.let { - abortTracker.markIntentional(sessionId) - terminate(it) - } - // PRoot/Android needs a short gap between agy launches while its shared guest state - // initializes. The old implementation held this gate until the whole response ended, - // which serialized unrelated sessions for minutes. Only the vulnerable startup window - // is shared; each session's already-started process can stream concurrently. - val args = - buildList { - add("--output-format") - add("stream-json") - if (conversationId != null) { - add("--conversation") - add(conversationId) + // A send for a session whose turn is still running waits here instead of killing it. + // The app normally queues (RuntimeCapabilities.forcesQueue), but the chat's own + // isRunning can be stale - a chat opened mid-turn used to look idle and send straight + // through - and terminating the in-flight one-shot process there discarded the turn + // the user was watching with no reply at all. Different sessions still run + // concurrently; only this session's next turn waits. + withSessionLock(sessionId) { + // Read under the lock: the previous turn persists the conversation id it + // discovered before releasing the lock, so a waiting send must not use the value + // it captured before the wait. + val effectiveConversationId = records[sessionId]?.conversationId ?: conversationId + // Also under the lock: attachment paths are keyed by lastStep, which only advances + // when the previous turn finishes. Preparing them before the wait would write this + // turn's files over the still-running turn's. + val promptWithAttachments = + prepareAntigravityPrompt( + runtimeDirectory, + sessionId, + records[sessionId]?.lastStep ?: 0, + prompt, + attachments, + ) + // PRoot/Android needs a short gap between agy launches while its shared guest state + // initializes. The old implementation held this gate until the whole response ended, + // which serialized unrelated sessions for minutes. Only the vulnerable startup window + // is shared; each session's already-started process can stream concurrently. + val args = + buildList { + add("--output-format") + add("stream-json") + if (effectiveConversationId != null) { + add("--conversation") + add(effectiveConversationId) + } + addAll(AntigravityModels.cliArgs(model, variant)) + addAll(permissionMode.cliArgs) + add("--print") + add(promptWithAttachments) } - addAll(AntigravityModels.cliArgs(model, variant)) - addAll(permissionMode.cliArgs) - add("--print") - add(promptWithAttachments) - } - val stderrLog = File(runtimeDirectory, "logs/agy-stderr.log").also { it.parentFile?.mkdirs() } - val process = - AntigravityProcessGate.acquireThenRelease(PROCESS_STARTUP_GRACE_MS) { - ProcessBuilder( - AntigravitySandboxLauncher.command( - runtime, - File(runtimeDirectory, "workspace").apply { - mkdirs() - }.absolutePath, - args, - false, + val stderrLog = File(runtimeDirectory, "logs/agy-stderr.log").also { it.parentFile?.mkdirs() } + val process = + AntigravityProcessGate.acquireThenRelease(PROCESS_STARTUP_GRACE_MS) { + ProcessBuilder( + AntigravitySandboxLauncher.command( + runtime, + File(runtimeDirectory, "workspace").apply { + mkdirs() + }.absolutePath, + args, + false, + ), + ) + .directory(runtimeDirectory) + // Diagnostics go to a log, not into stdout: a progress line on stderr would + // corrupt the NDJSON the parser reads line by line below. + .redirectError(ProcessBuilder.Redirect.appendTo(stderrLog)).apply { + environment().putAll( + AntigravitySandboxLauncher.environment( + runtime, + File(runtimeDirectory, "proot-tmp").apply { mkdirs() }, + githubToken(), + ), + ) + }.start() + // Registered before the gate's startup grace begins, so abort() and + // abortAll() can still see (and stop) a turn during those seconds. + .also { processes[sessionId] = it } + } ?: error("Antigravity is busy and the turn could not be scheduled") + val parser = AntigravityStreamJsonParser(sessionId, json) + try { + val record0 = records[sessionId] ?: AntigravitySessionRecord(sessionId, null, workspace) + val turnNow = System.currentTimeMillis() + // The turn's wall clock keeps the id unique per send: lastStep only advances + // once the turn finishes (below), so a death in between - the app being killed + // mid-turn, a read error on the stream - would replay the same id on the next + // send. Two user rows sharing one id then crashed the chat's LazyColumn the + // moment that conversation was opened (issue #311). + val userId = "$sessionId-user-${record0.lastStep}-$turnNow" + // Persist the user turn before the stream starts. The chat redraws from + // listMessages the moment it sees SessionIdle, and the composer's optimistic + // bubble is replaced by that snapshot - so a user turn that only lands at the + // end of the send would vanish from the screen (and never reappear on a failed + // result, which persisted nothing for it). + messageStore.append( + sessionId, + OpenCodeMessage( + OpenCodeMessageInfo(userId, sessionId, "user", OpenCodeTime(turnNow, turnNow, turnNow)), + // A part without an id is dropped when the chat maps the transcript for + // display, so an id-less part is invisible however well the run went. + buildList { + add(OpenCodePart(id = "$userId-text", type = "text", text = prompt)) + attachments.forEachIndexed { index, attachment -> + add( + OpenCodePart( + id = "$userId-file-$index", + sessionId = sessionId, + messageId = userId, + type = "file", + filename = attachment.filename, + mime = attachment.mime, + url = attachment.url, + ), + ) + } + }, ), ) - .directory(runtimeDirectory) - // Diagnostics go to a log, not into stdout: a progress line on stderr would - // corrupt the NDJSON the parser reads line by line below. - .redirectError(ProcessBuilder.Redirect.appendTo(stderrLog)).apply { - environment().putAll( - AntigravitySandboxLauncher.environment( - runtime, - File(runtimeDirectory, "proot-tmp").apply { mkdirs() }, - githubToken(), + persistMessages() + var discoveredConversationId: String? = null + var turnFinished = false + var turnError: String? = null + var finalText: String? = null + process.inputStream.bufferedReader().forEachLine { line -> + if (line.isBlank()) return@forEachLine + val parsed = parser.parse(line) + parsed.conversationId?.let { discoveredConversationId = it } + // Persist the assistant message before emitting its events. The chat's + // SessionIdle handler clears the live stream buffer and reloads the + // transcript with listMessages; if the turn is not on disk yet, that reload + // paints the previous turn and the just-streamed reply disappears - the + // one-turn lag seen on device. Claude Code avoids this by upserting before + // it emits, so the assistant reply (and its tool parts) land first here too. + parsed.messages.forEach { assistant -> + messageStore.append( + sessionId, + assistant.copy( + info = + assistant.info.copy( + model = model?.let { OpenCodeModelReference(AntigravityModels.PROVIDER_ID, it) }, + ), ), ) - }.start() - // Registered before the gate's startup grace begins, so abort() and - // abortAll() can still see (and stop) a turn during those seconds. - .also { processes[sessionId] = it } - } ?: error("Antigravity is busy and the turn could not be scheduled") - val parser = AntigravityStreamJsonParser(sessionId, json) - try { - val record0 = records[sessionId] ?: AntigravitySessionRecord(sessionId, null, workspace) - val turnNow = System.currentTimeMillis() - // The turn's wall clock keeps the id unique per send: lastStep only advances - // once the turn finishes (below), so a death in between - the app being killed - // mid-turn, a read error on the stream - would replay the same id on the next - // send. Two user rows sharing one id then crashed the chat's LazyColumn the - // moment that conversation was opened (issue #311). - val userId = "$sessionId-user-${record0.lastStep}-$turnNow" - // Persist the user turn before the stream starts. The chat redraws from - // listMessages the moment it sees SessionIdle, and the composer's optimistic - // bubble is replaced by that snapshot - so a user turn that only lands at the - // end of the send would vanish from the screen (and never reappear on a failed - // result, which persisted nothing for it). - messageStore.append( - sessionId, - OpenCodeMessage( - OpenCodeMessageInfo(userId, sessionId, "user", OpenCodeTime(turnNow, turnNow, turnNow)), - // A part without an id is dropped when the chat maps the transcript for - // display, so an id-less part is invisible however well the run went. - buildList { - add(OpenCodePart(id = "$userId-text", type = "text", text = prompt)) - attachments.forEachIndexed { index, attachment -> - add( - OpenCodePart( - id = "$userId-file-$index", - sessionId = sessionId, - messageId = userId, - type = "file", - filename = attachment.filename, - mime = attachment.mime, - url = attachment.url, - ), - ) - } - }, - ), - ) - persistMessages() - var discoveredConversationId: String? = null - var turnFinished = false - var turnError: String? = null - var finalText: String? = null - process.inputStream.bufferedReader().forEachLine { line -> - if (line.isBlank()) return@forEachLine - val parsed = parser.parse(line) - parsed.conversationId?.let { discoveredConversationId = it } - // Persist the assistant message before emitting its events. The chat's - // SessionIdle handler clears the live stream buffer and reloads the - // transcript with listMessages; if the turn is not on disk yet, that reload - // paints the previous turn and the just-streamed reply disappears - the - // one-turn lag seen on device. Claude Code avoids this by upserting before - // it emits, so the assistant reply (and its tool parts) land first here too. - parsed.messages.forEach { assistant -> - messageStore.append( - sessionId, - assistant.copy( - info = - assistant.info.copy( - model = model?.let { OpenCodeModelReference(AntigravityModels.PROVIDER_ID, it) }, - ), - ), + persistMessages() + } + parsed.events.forEach(events::tryEmit) + if (parsed.turnFinished) { + turnFinished = true + turnError = parsed.errorMessage + finalText = parsed.finalText + } + } + process.waitFor() + // Consumed unconditionally, even when the turn actually finished cleanly (an + // abort can race a completion that was already on its way): leaving the flag set + // would make an unrelated later crash on this same session silently swallowed as + // "clean idle" instead of surfacing as an error. + val wasKilledIntentionally = abortTracker.consumeIntentional(sessionId) + records[sessionId] = + record0.copy( + // Never invent a conversation id: --conversation must only be used with + // an id emitted by the official CLI, otherwise a cold resume can attach + // to an unrelated conversation. The id now comes straight from the stream's + // top-level conversation_id rather than being scraped out of the prose. + conversationId = discoveredConversationId ?: record0.conversationId, + updatedAt = System.currentTimeMillis(), + lastStep = record0.lastStep + 1, ) - persistMessages() + persistRecords() + if (turnFinished) { + // On a failed result the parser already emitted SessionError then SessionIdle; + // the user turn is persisted above, and there is no assistant reply to add. + backgroundScope.launch { refreshRateLimits() } + return@runCatching finalText.orEmpty() } - parsed.events.forEach(events::tryEmit) - if (parsed.turnFinished) { - turnFinished = true - turnError = parsed.errorMessage - finalText = parsed.finalText + if (wasKilledIntentionally) { + // Killed on purpose by the stop button - not a crash. The process's exit + // code is 137 (SIGKILL) either way, so this flag is the only thing that + // tells the two apart; idle is the honest state. + events.tryEmit(OpenCodeEvent.SessionIdle(sessionId)) + return@runCatching finalText.orEmpty() } - } - process.waitFor() - // Consumed unconditionally, even when the turn actually finished cleanly (an - // abort can race a completion that was already on its way): leaving the flag set - // would make an unrelated later crash on this same session silently swallowed as - // "clean idle" instead of surfacing as an error. - val wasKilledIntentionally = abortTracker.consumeIntentional(sessionId) - records[sessionId] = - record0.copy( - // Never invent a conversation id: --conversation must only be used with - // an id emitted by the official CLI, otherwise a cold resume can attach - // to an unrelated conversation. The id now comes straight from the stream's - // top-level conversation_id rather than being scraped out of the prose. - conversationId = discoveredConversationId ?: record0.conversationId, - updatedAt = System.currentTimeMillis(), - lastStep = record0.lastStep + 1, - ) - persistRecords() - if (turnFinished) { - // On a failed result the parser already emitted SessionError then SessionIdle; - // the user turn is persisted above, and there is no assistant reply to add. - backgroundScope.launch { refreshRateLimits() } - return@runCatching finalText.orEmpty() - } - if (wasKilledIntentionally) { - // Killed on purpose - the stop button, or a same-session supersede above - - // not a crash. The process's exit code is 137 (SIGKILL) either way, so this - // flag is the only thing that tells the two apart; idle is the honest state. + // No result event arrived: the CLI died mid-turn. Surface that as an error unless it + // somehow exited cleanly, in which case idle is the honest state. + require(process.exitValue() == 0) { "agy exited with ${process.exitValue()}" } events.tryEmit(OpenCodeEvent.SessionIdle(sessionId)) - return@runCatching finalText.orEmpty() - } - // No result event arrived: the CLI died mid-turn. Surface that as an error unless it - // somehow exited cleanly, in which case idle is the honest state. - require(process.exitValue() == 0) { "agy exited with ${process.exitValue()}" } - events.tryEmit(OpenCodeEvent.SessionIdle(sessionId)) - finalText.orEmpty() - } finally { - // A read/parse failure used to leave a live process and a stale map entry behind, - // which kept summarizeTitle() refusing forever once another session had one. - if (processes.remove(sessionId, process) && process.isAlive) { - runCatching { terminate(process) } + finalText.orEmpty() + } finally { + // A read/parse failure used to leave a live process and a stale map entry behind, + // which kept summarizeTitle() refusing forever once another session had one. + if (processes.remove(sessionId, process) && process.isAlive) { + runCatching { terminate(process) } + } } } }.onFailure { @@ -593,6 +608,31 @@ class AntigravityRuntime( answers: List>, ): Boolean = false + /** + * Serializes one session's sends without serializing different sessions. + * + * The launch gate only covers agy's startup window (see [AntigravityProcessGate]), so without + * this a second send for the same chat would start a second guest process for a turn that is + * still streaming. The wait is bounded; a turn that outlives it is reported as busy rather than + * hanging the send forever. Declared inline so the caller's `return@runCatching` paths still + * unwind through the unlock below. + */ + private inline fun withSessionLock( + sessionId: String, + block: () -> T, + ): T { + val created = java.util.concurrent.locks.ReentrantLock() + val lock = sessionLocks.putIfAbsent(sessionId, created) ?: created + if (!lock.tryLock(SESSION_LOCK_WAIT_MINUTES, java.util.concurrent.TimeUnit.MINUTES)) { + error("Antigravity is busy with this chat") + } + try { + return block() + } finally { + lock.unlock() + } + } + /** See [killProcessTree] for why a plain `destroy()`/`destroyForcibly()` is not enough. */ private fun terminate(process: Process) { killProcessTree(process) @@ -605,6 +645,7 @@ class AntigravityRuntime( const val USAGE_READ_TIMEOUT_MS = 30_000L const val TITLE_READ_TIMEOUT_MS = 45_000L const val PROCESS_STARTUP_GRACE_MS = 2_500L + const val SESSION_LOCK_WAIT_MINUTES = 30L const val TITLE_PROMPT_LIMIT = 2_000 const val TITLE_LENGTH = 40 } diff --git a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeInstaller.kt b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeInstaller.kt index 9b2ca6d40..9c98112f7 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeInstaller.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeInstaller.kt @@ -21,6 +21,13 @@ class LocalRuntimeInstaller( private val manifestReader: LocalRuntimeManifestReader = LocalRuntimeManifestReader(context), private val downloader: VerifiedRuntimeDownloader = VerifiedRuntimeDownloader(httpClient), private val accessCoordinator: LocalRuntimeAccessCoordinator = LocalRuntimeAccessCoordinator(), + /** + * The user's own addition to the shared agent context, read when the files are written. + * + * A provider rather than a value so a change made in Settings takes effect on the next + * runtime start without rebuilding the installer. + */ + private val userAgentInstructions: () -> String = { "" }, ) { private val json: Json = Json { @@ -143,7 +150,7 @@ class LocalRuntimeInstaller( null } if (antigravityRootfs != null) { - ensureAndCodeAgentContext(antigravityRootfs, context) + ensureAndCodeAgentContext(antigravityRootfs, context, userAgentInstructions()) copyCaCertificates(rootfs, antigravityRootfs) // Keep the Android-vision tool surface added for Claude/OpenCode available // to agy's Debian tool runner as well. The scripts still fail closed when adb @@ -156,7 +163,7 @@ class LocalRuntimeInstaller( // the whole environment directory, so without this the user is signed out of every // agent whenever another one is added or the runtime is reinstalled. carryOverHomeDirectory(File(active, "rootfs"), rootfs) - ensureAndCodeAgentContext(rootfs, context) + ensureAndCodeAgentContext(rootfs, context, userAgentInstructions()) onShared( 0.91f, context.getString( @@ -278,8 +285,8 @@ class LocalRuntimeInstaller( File(active, "antigravity-rootfs").takeIf { metadata.has(LocalAgent.ANTIGRAVITY) && it.isDirectory }, ) }?.also { installed -> - ensureAndCodeAgentContext(installed.rootfs, context) - installed.antigravityRootfs?.let { ensureAndCodeAgentContext(it, context) } + ensureAndCodeAgentContext(installed.rootfs, context, userAgentInstructions()) + installed.antigravityRootfs?.let { ensureAndCodeAgentContext(it, context, userAgentInstructions()) } } /** Metadata of the active install, without requiring the command suite to be extractable. */ diff --git a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt index c840fd7ec..633c28695 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/ui/AndCodeApp.kt @@ -349,6 +349,10 @@ fun AndCodeApp( }, onCodexFastModeChanged = app.preferences::setCodexFastMode, initialCodexFastMode = app.settings.codexFastMode, + initialSendBehavior = preferences.sendBehavior, + // A chat opened while its run is still in flight must look running, or the + // next send is treated as idle and interrupts (kills) that run. + isSessionRunning = { id -> id in app.activityRepository.state.value.activeSessionIds }, onSessionAborted = { sessionId -> app.activityRepository.markSessionAborted(sessionId) // Stopping the run answers the "this run has gone quiet" notice. @@ -387,6 +391,12 @@ fun AndCodeApp( }, ) val chatState by chatViewModel.uiState.collectAsState() + val sendBehavior by chatViewModel.sendBehavior.collectAsState() + // The setting is read once as the ViewModel starts, so a change made in Settings while the chat + // is alive has to be pushed in rather than waiting for the ViewModel to be recreated. + LaunchedEffect(preferences.sendBehavior) { + chatViewModel.setSendBehavior(preferences.sendBehavior) + } val appForeground by app.appForeground.foreground.collectAsState() // Where the live-reload watcher and the static preview read files from. Null on remote runtimes, @@ -1407,6 +1417,8 @@ fun AndCodeApp( onDismissPullRequest = chatViewModel::dismissPullRequest, autoAcceptPermissions = settingsState.autoAcceptPermissions, onToggleAutoAccept = settingsViewModel::setAutoAcceptPermissions, + sendBehavior = sendBehavior, + forcesQueue = selectedRuntime?.capabilities?.forcesQueue == true, enterToSend = preferences.enterToSend, autoExpandReasoning = preferences.autoExpandReasoning, onSendMessage = chatViewModel::sendMessage, diff --git a/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/Routes.kt b/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/Routes.kt index 2c676bde4..2a8ccc0f0 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/Routes.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/Routes.kt @@ -21,6 +21,7 @@ const val ROUTE_SETTINGS_MCP_ANTIGRAVITY = "settings-mcp-antigravity" const val ROUTE_SETTINGS_MCP_CODEX = "settings-mcp-codex" const val ROUTE_SETTINGS_MODEL_VISIBILITY = "settings-model-visibility" const val ROUTE_SETTINGS_SYSTEM_PROMPT = "settings-system-prompt" +const val ROUTE_SETTINGS_AGENT_INSTRUCTIONS = "settings-agent-instructions" const val ROUTE_SETTINGS_SERVER_INFO = "settings-server-info" const val ROUTE_SETTINGS_LEGAL = "settings-legal" const val ROUTE_SETTINGS_LEGAL_DOCUMENT = "settings-legal-document" diff --git a/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/SettingsNavGraph.kt b/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/SettingsNavGraph.kt index 52ea2c6c3..63e4930ce 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/SettingsNavGraph.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/ui/navigation/SettingsNavGraph.kt @@ -17,6 +17,7 @@ import com.yugahashimoto.andcode.core.UrlLauncher import com.yugahashimoto.andcode.data.settings.AppPreferences import com.yugahashimoto.andcode.data.settings.AppPreferencesRepository import com.yugahashimoto.andcode.feature.assistant.TtsPreview +import com.yugahashimoto.andcode.feature.settings.AgentInstructionsScreen import com.yugahashimoto.andcode.feature.settings.AgentSettingsScreen import com.yugahashimoto.andcode.feature.settings.AntigravityAgentSettingsScreen import com.yugahashimoto.andcode.feature.settings.ClaudeCodeAgentSettingsScreen @@ -114,6 +115,7 @@ fun NavGraphBuilder.settingsNavGraph( onSendBehaviorChange = { appPreferences.setSendBehavior(it) }, enterToSend = preferences().enterToSend, onEnterToSendChange = { appPreferences.setEnterToSend(it) }, + onOpenAgentInstructions = { navController.navigate(ROUTE_SETTINGS_AGENT_INSTRUCTIONS) }, autoArchiveStaleEnabled = preferences().autoArchiveStaleEnabled, onAutoArchiveStaleEnabledChange = appPreferences::setAutoArchiveStaleEnabled, autoArchiveStaleDays = preferences().autoArchiveStaleDays, @@ -383,6 +385,14 @@ fun NavGraphBuilder.settingsNavGraph( ) } + composable(ROUTE_SETTINGS_AGENT_INSTRUCTIONS) { + AgentInstructionsScreen( + savedInstructions = preferences().agentInstructions, + onSave = appPreferences::setAgentInstructions, + onBack = { navController.popBackStack() }, + ) + } + composable(ROUTE_SETTINGS_AGENT_ANTIGRAVITY) { AntigravityAgentSettingsScreen( antigravity = antigravity(), diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 1ef9f73b2..b0204602d 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -654,6 +654,14 @@ مقاطعة قائمة انتظار الإدخال يرسل الرسالة + قواعد الوكلاء المشتركة + قواعد الوكلاء المشتركة + تُمرَّر هذه التعليمات إلى OpenCode وClaude Code وAntigravity وCodex معًا. وتُطبَّق في المرة التالية التي يبدأ فيها الوكيل. + تعليماتك + مثال: إجابات قصيرة، وتشغيل الاختبارات قبل الانتهاء. + حفظ + سياق AndCode المدمج (للقراءة فقط) + تم الحفظ. تُطبَّق القواعد الجديدة في المرة التالية التي يبدأ فيها الوكيل. الجلسات أرشفة المحادثات غير النشطة تلقائيًا diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 8ccb6c1b2..5c9a65d12 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -648,6 +648,14 @@ Interrumpir Cola Enter envía el mensaje + Reglas compartidas para agentes + Reglas compartidas para agentes + Estas instrucciones se aplican a OpenCode, Claude Code, Antigravity y Codex a la vez. Se aplican la próxima vez que se inicie un agente. + Tus instrucciones + Por ejemplo: respuestas breves y ejecutar las pruebas antes de terminar. + Guardar + Contexto integrado de AndCode (solo lectura) + Guardado. Las nuevas reglas se aplican la próxima vez que se inicie un agente. Sesiones Archivar chats inactivos automáticamente diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e525d6854..35c23de9a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -648,6 +648,14 @@ Interrompre File d\'attente Entrée envoie le message + Règles partagées des agents + Règles partagées des agents + Ces instructions sont transmises à OpenCode, Claude Code, Antigravity et Codex en même temps. Elles s\'appliquent au prochain démarrage d\'un agent. + Vos instructions + Par exemple : des réponses courtes et lancer les tests avant de terminer. + Enregistrer + Contexte AndCode intégré (lecture seule) + Enregistré. Les nouvelles règles s\'appliquent au prochain démarrage d\'un agent. Sessions Archiver automatiquement les discussions inactives diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index adc9ea267..b840c7a4d 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -656,6 +656,14 @@ 割り込み キュー Enter で送信 + 共通ルール + 共通ルール + ここに書いた指示は OpenCode / Claude Code / Antigravity / Codex のすべてに渡されます。次回エージェント起動時に反映されます。 + 追加の指示 + 例: 回答は短く。終了前にテストを実行する。 + 保存 + AndCode の共通コンテキスト(読み取り専用) + 保存しました。次回エージェント起動時に反映されます。 セッション 未更新のチャットを自動アーカイブ diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ac8c50e73..7b715c2df 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -648,6 +648,14 @@ Interromper Fila Enter envia a mensagem + Regras compartilhadas dos agentes + Regras compartilhadas dos agentes + Estas instruções são passadas para OpenCode, Claude Code, Antigravity e Codex ao mesmo tempo. Elas passam a valer na próxima vez que um agente iniciar. + Suas instruções + Por exemplo: respostas curtas e rodar os testes antes de terminar. + Salvar + Contexto integrado do AndCode (somente leitura) + Salvo. As novas regras passam a valer na próxima vez que um agente iniciar. Sessões Arquivar chats inativos automaticamente diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6486c2ee3..862d68809 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -650,6 +650,14 @@ Прервать В очередь Enter отправляет сообщение + Общие правила для агентов + Общие правила для агентов + Эти инструкции передаются OpenCode, Claude Code, Antigravity и Codex одновременно. Они вступят в силу при следующем запуске агента. + Ваши инструкции + Например: отвечать кратко и запускать тесты перед завершением. + Сохранить + Встроенный контекст AndCode (только чтение) + Сохранено. Новые правила вступят в силу при следующем запуске агента. Сеансы Автоархивация неактивных чатов diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 430a9da1d..ddbc19e04 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -644,6 +644,14 @@ 中断 排队 回车键发送消息 + 共享智能体规则 + 共享智能体规则 + 这些指令会同时提供给 OpenCode、Claude Code、Antigravity 和 Codex。将在下次启动智能体时生效。 + 你的指令 + 例如:回答要简短,并在完成前运行测试。 + 保存 + AndCode 内置上下文(只读) + 已保存。新规则将在下次启动智能体时生效。 会话 自动归档不活跃的聊天 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eda1a5b19..db7de234c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -649,6 +649,14 @@ Interrupt Queue Enter sends message + Shared agent rules + Shared agent rules + These instructions are given to OpenCode, Claude Code, Antigravity and Codex together. They take effect the next time an agent starts. + Your instructions + For example: prefer short answers, and run the tests before finishing. + Save + Built-in AndCode context (read-only) + Saved. The new rules apply the next time an agent starts. Sessions Auto-archive inactive chats diff --git a/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt b/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt index 6cf5154c4..18a511f9b 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/feature/chat/ChatViewModelTest.kt @@ -1161,6 +1161,82 @@ class ChatViewModelTest { assertEquals(listOf("first", "second"), backend.sentPrompts.map { it.second.text }) } + /** + * A queued prompt used to vanish from the screen entirely, which read as if the send had been + * swallowed. It has to be visible while it waits, and the drain must not draw it a second time. + */ + @Test + fun `a forced-queue prompt is shown while it waits and is not duplicated when it drains`() = + runTest(dispatcher) { + val backend = FakeRuntimeTargetBackend(RuntimeCapabilities(forcesQueue = true)) + val viewModel = ChatViewModel(backend) + advanceUntilIdle() + + viewModel.sendMessage("first") + advanceUntilIdle() + viewModel.sendMessage("second") + advanceUntilIdle() + + assertEquals(listOf("first", "second"), viewModel.uiState.value.messages.filter { it.isUser }.map { it.text }) + assertEquals(listOf("first"), backend.sentPrompts.map { it.second.text }) + + backend.events.tryEmit(OpenCodeEvent.SessionIdle("s1")) + advanceUntilIdle() + + assertEquals(listOf("first", "second"), backend.sentPrompts.map { it.second.text }) + assertEquals(listOf("first", "second"), viewModel.uiState.value.messages.filter { it.isUser }.map { it.text }) + } + + /** + * A chat opened while its run is still in flight (started before this client opened it) looked + * idle, so a send there went straight through as an interrupt. On Antigravity that kills the + * one-shot process of the turn the user was watching, and both prompts are lost. + */ + @Test + fun `a send in a chat whose run is already in flight is queued, not interrupted`() = + runTest(dispatcher) { + val backend = FakeRuntimeTargetBackend(RuntimeCapabilities(forcesQueue = true)) + val viewModel = ChatViewModel(backend, isSessionRunning = { it == "s1" }) + advanceUntilIdle() + + viewModel.openSession("s1") + advanceUntilIdle() + assertTrue(viewModel.uiState.value.isRunning) + + viewModel.sendMessage("follow-up") + advanceUntilIdle() + + assertTrue(backend.sentPrompts.isEmpty()) + assertEquals(listOf("follow-up"), viewModel.uiState.value.messages.filter { it.isUser }.map { it.text }) + } + + /** + * Navigating away is not as strong as a run ending: the drawer keeps the spinner because the + * runtime still reports the session as active (and its own idle settles it later). Clearing it + * on navigation made an Antigravity run look idle until the next streamed token. + */ + @Test + fun `navigating away from a running chat does not report it finished`() = + runTest(dispatcher) { + val backend = FakeRuntimeTargetBackend(RuntimeCapabilities(forcesQueue = true)) + val runs = mutableListOf>() + val viewModel = + ChatViewModel( + backend, + onRunStateChanged = { id, running -> runs += id to running }, + ) + advanceUntilIdle() + + viewModel.sendMessage("long task") + advanceUntilIdle() + assertEquals(listOf("s1" to true), runs) + + viewModel.openSession("s2", "Another chat") + advanceUntilIdle() + + assertEquals(listOf("s1" to true), runs) + } + /** * OpenCode drops a prompt that arrives while a turn is still in flight: it stores the message * and hands it to a session runner that is already running, which attaches to the run instead of diff --git a/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeProcessLauncherTest.kt b/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeProcessLauncherTest.kt index d691b23e8..eb65b5212 100644 --- a/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeProcessLauncherTest.kt +++ b/app/src/test/java/com/yugahashimoto/andcode/runtime/local/LocalRuntimeProcessLauncherTest.kt @@ -57,12 +57,58 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> val context = File(rootfs, relativePath).readText() assertEquals(AGENT_CONTEXT_FIXTURE, context) } } + @Test + fun `user instructions are appended to every agent's context`() { + val rootfs = temporaryFolder.newFolder("rootfs-user-instructions") + + installAndCodeAgentContext( + rootfs, + AGENT_CONTEXT_FIXTURE.toByteArray(), + userInstructions = "Always answer in Japanese.", + ) + + val expected = "$AGENT_CONTEXT_FIXTURE\n\n## User instructions\n\nAlways answer in Japanese.\n" + listOf( + "root/.config/opencode/and-code-context.md", + "root/.claude/CLAUDE.md", + "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", + ).forEach { relativePath -> + assertEquals(expected, File(rootfs, relativePath).readText()) + } + } + + @Test + fun `blank user instructions leave the bundled context untouched`() { + val rootfs = temporaryFolder.newFolder("rootfs-blank-user-instructions") + + installAndCodeAgentContext( + rootfs, + AGENT_CONTEXT_FIXTURE.toByteArray(), + userInstructions = " \n ", + ) + + assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, "root/.claude/CLAUDE.md").readText()) + } + + @Test + fun `clearing user instructions restores the bundled context`() { + val rootfs = temporaryFolder.newFolder("rootfs-cleared-user-instructions") + + installAndCodeAgentContext(rootfs, AGENT_CONTEXT_FIXTURE.toByteArray(), "Old rule.") + installAndCodeAgentContext(rootfs, AGENT_CONTEXT_FIXTURE.toByteArray(), "") + + assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, "root/.claude/CLAUDE.md").readText()) + assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, "root/.codex/AGENTS.md").readText()) + } + @Test fun `user edits to an instructions file survive a later context refresh`() { val rootfs = temporaryFolder.newFolder("rootfs-user-edit") @@ -93,6 +139,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(updatedFixture, File(rootfs, relativePath).readText()) } @@ -170,6 +217,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -193,6 +241,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -215,6 +264,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -238,6 +288,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -245,7 +296,7 @@ class LocalRuntimeProcessLauncherTest { } @Test - fun `one target that cannot be written does not stop the other two from installing`() { + fun `one target that cannot be written does not stop the others from installing`() { val rootfs = temporaryFolder.newFolder("rootfs-target-unwritable") // Simulate an agent replacing CLAUDE.md's parent directory with a regular file before @@ -253,7 +304,7 @@ class LocalRuntimeProcessLauncherTest { // exist yet, and canonicalization of a missing leaf under an existing non-directory // succeeds lexically), but mkdirs() on the parent then fails and writeBytes() throws // FileSystemException (an IOException) because ".claude" is not a directory. That must - // skip only this target, not the opencode or gemini instruction files. + // skip only this target, not the other agents' instruction files. val claudeDir = File(rootfs, "root/.claude") claudeDir.parentFile.mkdirs() claudeDir.writeText("not a directory") @@ -263,6 +314,7 @@ class LocalRuntimeProcessLauncherTest { listOf( "root/.config/opencode/and-code-context.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -279,6 +331,10 @@ class LocalRuntimeProcessLauncherTest { "gemini's hash must be recorded as written", "root/.gemini/GEMINI.md" in recordedPaths, ) + assertTrue( + "codex's hash must be recorded as written", + "root/.codex/AGENTS.md" in recordedPaths, + ) assertFalse( "the failed CLAUDE.md write must not be recorded as successfully written", "root/.claude/CLAUDE.md" in recordedPaths, @@ -303,6 +359,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -324,6 +381,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ).forEach { relativePath -> assertEquals(AGENT_CONTEXT_FIXTURE, File(rootfs, relativePath).readText()) } @@ -333,6 +391,7 @@ class LocalRuntimeProcessLauncherTest { "root/.config/opencode/and-code-context.md", "root/.claude/CLAUDE.md", "root/.gemini/GEMINI.md", + "root/.codex/AGENTS.md", ), recordedPaths, )