From 5c3b24e6a7f0972cccd5037d70287132c38556be Mon Sep 17 00:00:00 2001 From: Yu-ga <74749461+yuga-hashimoto@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:59:11 +0000 Subject: [PATCH 1/3] fix(chat): keep queued prompts visible and running state accurate Antigravity runs each turn as a one-shot process, so a send while it is running is queued rather than interrupting. That path dropped the message from the screen entirely, which read as if the send had been swallowed. Draw the bubble when it is queued and send it without adding a second copy when the queue drains.\n\nAlso: open a chat whose run is still in flight as running, so a send there queues behind it instead of killing the process; keep a navigated-away run's drawer spinner until the runtime reports its own idle; and wire the send-behavior setting into the chat, which had been read only at its default. --- .../andcode/di/ViewModelModule.kt | 1 + .../andcode/feature/chat/ChatHomeScreen.kt | 25 ++- .../andcode/feature/chat/ChatViewModel.kt | 177 ++++++++++++++---- .../runtime/local/AntigravityRuntime.kt | 23 ++- .../yugahashimoto/andcode/ui/AndCodeApp.kt | 12 ++ .../andcode/feature/chat/ChatViewModelTest.kt | 76 ++++++++ 6 files changed, 269 insertions(+), 45 deletions(-) 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..fd5193eb8 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,7 @@ 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, // 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 e783e883f..3bf972591 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) { @@ -1089,6 +1123,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. @@ -1109,12 +1147,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 { @@ -1126,7 +1165,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, ) @@ -1386,7 +1430,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(), + ), + ) } } @@ -1412,6 +1463,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() @@ -1448,7 +1510,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 } @@ -1475,6 +1537,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. @@ -1483,24 +1556,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, @@ -1597,6 +1669,7 @@ class ChatViewModel( _uiState.value.messages, pendingPreviewsByFilename, retainIds, + retainUserTexts = pendingQueuedTexts(), ) if (uiMessages.isNotEmpty() && uiMessages != _uiState.value.messages) { _uiState.update { it.copy(messages = uiMessages) } @@ -1639,6 +1712,7 @@ class ChatViewModel( _uiState.value.messages, pendingPreviewsByFilename, retainedIds, + retainUserTexts = pendingQueuedTexts(), ) _uiState.update { it.copy( @@ -1650,6 +1724,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 -> @@ -1677,6 +1755,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) { @@ -1703,21 +1789,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, @@ -1797,6 +1887,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) } @@ -1827,12 +1918,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 -> @@ -2324,6 +2419,7 @@ class ChatViewModel( messages.mapNotNull(::toUiMessage), it.messages, retainIds = retainedIds, + retainUserTexts = pendingQueuedTexts(), ), ) } @@ -2527,6 +2623,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 -> @@ -2535,6 +2635,7 @@ class ChatViewModel( messages.mapNotNull(::toUiMessage), _uiState.value.messages, retainIds = retainIds, + retainUserTexts = retainUserTexts, ) if (uiMessages.isNotEmpty()) { _uiState.update { it.copy(messages = uiMessages) } @@ -2676,6 +2777,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 @@ -2706,7 +2813,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() { @@ -2795,6 +2903,7 @@ class ChatViewModel( messages.mapNotNull(::toUiMessage), it.messages, retainIds = retainedIds, + retainUserTexts = pendingQueuedTexts(), ), ) } 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 8590f60ab..b865a8c73 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 @@ -234,18 +234,21 @@ class AntigravityRuntime( 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) - } + // A send for a session that still has a process running waits on the gate below + // 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. The gate + // serializes the whole launch, so the waiting send starts once this one finishes. // Concurrent agy launches hang on the PRoot/Android deployment (see // AntigravityProcessGate), so a send queues behind any in-flight launch and the two // run one at a time instead of racing each other into a deadlock. AntigravityProcessGate.serialize { + // The record is authoritative once the gate is free: a send that waited here + // read the session before the previous turn had a chance to persist the + // conversation id it discovered, so without this it would start a brand-new + // guest conversation and lose the chat's context. + val effectiveConversationId = records[sessionId]?.conversationId ?: conversationId // `--print` takes the prompt as its value, so it must come last with the prompt // immediately after it. Every other flag goes first: with `--print` leading, the CLI // took the *next* token as the prompt, so a message sent with any flag set asked the @@ -254,9 +257,9 @@ class AntigravityRuntime( buildList { add("--output-format") add("stream-json") - if (conversationId != null) { + if (effectiveConversationId != null) { add("--conversation") - add(conversationId) + add(effectiveConversationId) } addAll(AntigravityModels.cliArgs(model, variant)) addAll(permissionMode.cliArgs) 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 f2f598af2..3876c9ff1 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, @@ -1399,6 +1409,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/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 From b78f0baa5762d34c14a7ba070679142116f966b3 Mon Sep 17 00:00:00 2001 From: Yu-ga <74749461+yuga-hashimoto@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:59:15 +0000 Subject: [PATCH 2/3] feat(settings): share one set of agent rules across every agent The common AndCode context is written into each agent's native instruction file, but there was no way to see or extend it from the app and Codex was not covered at all. Add root/.codex/AGENTS.md to the installed targets, and add a Settings screen that shows the bundled context and stores the user's own addition. The addition is appended once and written to OpenCode, Claude Code, Antigravity and Codex together on the next runtime start. --- .../andcode/AndCodeApplication.kt | 1 + .../connection/SecureSettingsRepository.kt | 11 ++ .../data/settings/AppPreferencesRepository.kt | 8 ++ .../com/yugahashimoto/andcode/di/AppModule.kt | 2 + .../settings/AgentInstructionsScreen.kt | 114 ++++++++++++++++++ .../feature/settings/SettingsScreenV2.kt | 7 ++ .../runtime/local/AndCodeAgentContext.kt | 48 ++++++-- .../runtime/local/LocalRuntimeInstaller.kt | 15 ++- .../andcode/ui/navigation/Routes.kt | 1 + .../andcode/ui/navigation/SettingsNavGraph.kt | 10 ++ app/src/main/res/values-ar/strings.xml | 8 ++ app/src/main/res/values-es/strings.xml | 8 ++ app/src/main/res/values-fr/strings.xml | 8 ++ app/src/main/res/values-ja/strings.xml | 8 ++ app/src/main/res/values-pt-rBR/strings.xml | 8 ++ app/src/main/res/values-ru/strings.xml | 8 ++ app/src/main/res/values-zh-rCN/strings.xml | 8 ++ app/src/main/res/values/strings.xml | 8 ++ .../local/LocalRuntimeProcessLauncherTest.kt | 63 +++++++++- 19 files changed, 325 insertions(+), 19 deletions(-) create mode 100644 app/src/main/java/com/yugahashimoto/andcode/feature/settings/AgentInstructionsScreen.kt diff --git a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt index 653b4f5b1..ca2810393 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/AndCodeApplication.kt @@ -293,6 +293,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 f3682e002..fa84ec26f 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 @@ -452,6 +452,16 @@ class SecureSettingsRepository(context: Context) : RuntimeConnectionStore, Unrea 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. * @@ -599,6 +609,7 @@ class SecureSettingsRepository(context: Context) : RuntimeConnectionStore, Unrea 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 7e0a386df..70e7537a7 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/di/AppModule.kt @@ -76,11 +76,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/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/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/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 21f0db457..68848f273 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 fd5aa544b..51fa480e9 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 994478e44..07bef1265 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 6b872d81e..e7cd2aef7 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 1518394a3..4231491ca 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 9f8d99b5e..1c4406280 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 74091c63c..e4e1903b5 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 b06c40eab..8a715aed8 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/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, ) From 9de1fb155434b38efb33ea35b0cd9e6deaacb3a5 Mon Sep 17 00:00:00 2001 From: Yu-ga <74749461+yuga-hashimoto@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:08:19 +0000 Subject: [PATCH 3/3] refactor: address pre-PR review feedback - Pass isSessionRunning through the Koin ChatViewModel binding too, so both construction paths stay in step.\n- Do not re-add a drained queued bubble if the connection dropped and the send fell into the offline branch.\n- Correct the Antigravity kill comment now that a same-session supersede no longer kills the process. --- .../java/com/yugahashimoto/andcode/di/ViewModelModule.kt | 1 + .../com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt | 2 +- .../andcode/runtime/local/AntigravityRuntime.kt | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) 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 fd5193eb8..fd65799bd 100644 --- a/app/src/main/java/com/yugahashimoto/andcode/di/ViewModelModule.kt +++ b/app/src/main/java/com/yugahashimoto/andcode/di/ViewModelModule.kt @@ -28,6 +28,7 @@ val viewModelModule = 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/ChatViewModel.kt b/app/src/main/java/com/yugahashimoto/andcode/feature/chat/ChatViewModel.kt index 3bf972591..17731fcc3 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 @@ -1527,7 +1527,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(), 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 b865a8c73..c7f1d81d7 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 @@ -388,9 +388,9 @@ class AntigravityRuntime( return@serialize 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. + // 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@serialize finalText.orEmpty() }