mirror of
https://github.com/Monkopedia/rouse-context.git
synced 2026-11-19 15:28:35 +00:00
Add notifications module with NotificationModel state machine and Room audit persistence
Implements T-7: pure-function NotificationModel that maps SessionEvents to NotificationActions based on NotificationSettings (Summary/Every/Suppress modes, permission state). Adds Room-backed audit persistence via AuditDao/AuditDatabase with session queries, date range + provider filtering, and retention pruning. Also adds prerequisite interfaces: AuditListener and ToolCallEvent in mcp-core, TunnelState and TunnelError in tunnel. Adds Room and KSP to version catalog. 23 unit tests passing (17 NotificationModel + 6 AuditDao via Robolectric). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
3dbc894801
commit
52276b1e72
22 changed files with 992 additions and 0 deletions
|
|
@ -2,4 +2,5 @@ plugins {
|
|||
alias(libs.plugins.android.application) apply false
|
||||
alias(libs.plugins.android.library) apply false
|
||||
alias(libs.plugins.kotlin.android) apply false
|
||||
alias(libs.plugins.ksp) apply false
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ lifecycle = "2.9.0"
|
|||
firebase-bom = "33.10.0"
|
||||
health-connect = "1.1.0-alpha12"
|
||||
acme4j = "3.5.0"
|
||||
room = "2.7.1"
|
||||
ksp = "2.1.10-1.0.31"
|
||||
|
||||
[libraries]
|
||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||
|
|
@ -21,8 +23,13 @@ firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.r
|
|||
firebase-messaging = { group = "com.google.firebase", name = "firebase-messaging-ktx" }
|
||||
health-connect = { group = "androidx.health.connect", name = "connect-client", version.ref = "health-connect" }
|
||||
acme4j-client = { group = "org.shredzone.acme4j", name = "acme4j-client", version.ref = "acme4j" }
|
||||
room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
|
||||
room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
|
||||
room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
|
||||
room-testing = { group = "androidx.room", name = "room-testing", version.ref = "room" }
|
||||
|
||||
[plugins]
|
||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||
android-library = { id = "com.android.library", version.ref = "agp" }
|
||||
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
package com.rousecontext.mcp.core
|
||||
|
||||
/**
|
||||
* Callback interface for logging MCP tool calls.
|
||||
* Implementations persist or display audit records.
|
||||
*/
|
||||
interface AuditListener {
|
||||
suspend fun onToolCall(event: ToolCallEvent)
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
package com.rousecontext.mcp.core
|
||||
|
||||
/**
|
||||
* Record of a single MCP tool invocation.
|
||||
*/
|
||||
data class ToolCallEvent(
|
||||
val sessionId: String,
|
||||
val toolName: String,
|
||||
val provider: String,
|
||||
val timestampMillis: Long,
|
||||
val durationMillis: Long,
|
||||
val success: Boolean,
|
||||
val errorMessage: String? = null,
|
||||
)
|
||||
41
notifications/build.gradle.kts
Normal file
41
notifications/build.gradle.kts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.rousecontext.notifications"
|
||||
compileSdk = 35
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 29
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = "17"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":tunnel"))
|
||||
implementation(project(":mcp-core"))
|
||||
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.room.runtime)
|
||||
implementation(libs.room.ktx)
|
||||
ksp(libs.room.compiler)
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.1")
|
||||
testImplementation("org.robolectric:robolectric:4.14.1")
|
||||
testImplementation("androidx.test:core:1.6.1")
|
||||
testImplementation(libs.room.testing)
|
||||
}
|
||||
2
notifications/src/main/AndroidManifest.xml
Normal file
2
notifications/src/main/AndroidManifest.xml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest />
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
import android.app.Notification
|
||||
import android.content.Context
|
||||
import androidx.core.app.NotificationCompat
|
||||
|
||||
/**
|
||||
* Creates the ongoing foreground service notification.
|
||||
*/
|
||||
fun createForegroundNotification(
|
||||
context: Context,
|
||||
message: String = "Connected",
|
||||
): Notification =
|
||||
NotificationCompat.Builder(context, NotificationChannels.FOREGROUND_CHANNEL_ID)
|
||||
.setContentTitle("Rouse Context")
|
||||
.setContentText(message)
|
||||
.setSmallIcon(android.R.drawable.ic_menu_manage)
|
||||
.setOngoing(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.build()
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
/**
|
||||
* Actions the notification state machine emits.
|
||||
* The [NotificationAdapter] translates these into Android NotificationManager calls.
|
||||
*/
|
||||
sealed interface NotificationAction {
|
||||
/** Show or update the ongoing foreground service notification. */
|
||||
data class ShowForeground(val message: String) : NotificationAction
|
||||
|
||||
/** Post a session summary after disconnect. */
|
||||
data class PostSummary(val toolCallCount: Int) : NotificationAction
|
||||
|
||||
/** Post a warning (e.g. disconnect with no tool calls). */
|
||||
data class PostWarning(val message: String) : NotificationAction
|
||||
|
||||
/** Post an error notification. */
|
||||
data class PostError(
|
||||
val message: String,
|
||||
val streamId: Int? = null,
|
||||
) : NotificationAction
|
||||
|
||||
/** Post a per-tool-call usage notification. */
|
||||
data class PostToolUsage(val toolName: String, val provider: String) : NotificationAction
|
||||
|
||||
/** Post an informational notification. */
|
||||
data class PostInfo(val message: String) : NotificationAction
|
||||
|
||||
/** Post a high-priority security alert. */
|
||||
data class PostAlert(val message: String) : NotificationAction
|
||||
}
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import androidx.core.app.NotificationCompat
|
||||
|
||||
/**
|
||||
* Translates [NotificationAction]s into Android [NotificationManager] calls.
|
||||
*/
|
||||
class NotificationAdapter(private val context: Context) {
|
||||
|
||||
private val manager = context.getSystemService(NotificationManager::class.java)
|
||||
private var nextId = FIRST_DYNAMIC_ID
|
||||
|
||||
/**
|
||||
* Execute a list of notification actions.
|
||||
*/
|
||||
fun execute(actions: List<NotificationAction>) {
|
||||
actions.forEach { execute(it) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a single notification action.
|
||||
*/
|
||||
fun execute(action: NotificationAction) {
|
||||
when (action) {
|
||||
is NotificationAction.ShowForeground -> {
|
||||
val notification = createForegroundNotification(context, action.message)
|
||||
manager.notify(FOREGROUND_ID, notification)
|
||||
}
|
||||
|
||||
is NotificationAction.PostSummary -> {
|
||||
val notification = buildSessionNotification(
|
||||
"Session Complete",
|
||||
"${action.toolCallCount} tool call${if (action.toolCallCount == 1) "" else "s"} processed",
|
||||
)
|
||||
manager.notify(nextId(), notification)
|
||||
}
|
||||
|
||||
is NotificationAction.PostWarning -> {
|
||||
val notification = buildSessionNotification("Warning", action.message)
|
||||
manager.notify(nextId(), notification)
|
||||
}
|
||||
|
||||
is NotificationAction.PostError -> {
|
||||
val text = if (action.streamId != null) {
|
||||
"Stream ${action.streamId}: ${action.message}"
|
||||
} else {
|
||||
action.message
|
||||
}
|
||||
val notification = buildErrorNotification(text)
|
||||
manager.notify(nextId(), notification)
|
||||
}
|
||||
|
||||
is NotificationAction.PostToolUsage -> {
|
||||
val notification = buildSessionNotification(
|
||||
"Tool Call",
|
||||
"${action.toolName} (${action.provider})",
|
||||
)
|
||||
manager.notify(nextId(), notification)
|
||||
}
|
||||
|
||||
is NotificationAction.PostInfo -> {
|
||||
val notification = buildSessionNotification("Info", action.message)
|
||||
manager.notify(nextId(), notification)
|
||||
}
|
||||
|
||||
is NotificationAction.PostAlert -> {
|
||||
val notification = buildAlertNotification(action.message)
|
||||
manager.notify(nextId(), notification)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildSessionNotification(title: String, text: String) =
|
||||
NotificationCompat.Builder(context, NotificationChannels.SESSION_CHANNEL_ID)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setSmallIcon(android.R.drawable.ic_menu_manage)
|
||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||
.setAutoCancel(true)
|
||||
.build()
|
||||
|
||||
private fun buildErrorNotification(text: String) =
|
||||
NotificationCompat.Builder(context, NotificationChannels.ERROR_CHANNEL_ID)
|
||||
.setContentTitle("Error")
|
||||
.setContentText(text)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_alert)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setAutoCancel(true)
|
||||
.build()
|
||||
|
||||
private fun buildAlertNotification(text: String) =
|
||||
NotificationCompat.Builder(context, NotificationChannels.ALERT_CHANNEL_ID)
|
||||
.setContentTitle("Security Alert")
|
||||
.setContentText(text)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_alert)
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setAutoCancel(true)
|
||||
.build()
|
||||
|
||||
private fun nextId(): Int = nextId++
|
||||
|
||||
companion object {
|
||||
const val FOREGROUND_ID = 1
|
||||
private const val FIRST_DYNAMIC_ID = 100
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* Notification channel definitions and setup.
|
||||
*/
|
||||
object NotificationChannels {
|
||||
const val FOREGROUND_CHANNEL_ID = "rouse_foreground"
|
||||
const val SESSION_CHANNEL_ID = "rouse_session"
|
||||
const val ERROR_CHANNEL_ID = "rouse_error"
|
||||
const val ALERT_CHANNEL_ID = "rouse_alert"
|
||||
|
||||
/**
|
||||
* Create all notification channels. Safe to call multiple times;
|
||||
* existing channels are not modified.
|
||||
*/
|
||||
fun createAll(context: Context) {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
|
||||
val channels = listOf(
|
||||
NotificationChannel(
|
||||
FOREGROUND_CHANNEL_ID,
|
||||
"Foreground Service",
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
).apply {
|
||||
description = "Ongoing notification while the MCP server is active"
|
||||
},
|
||||
NotificationChannel(
|
||||
SESSION_CHANNEL_ID,
|
||||
"Session Activity",
|
||||
NotificationManager.IMPORTANCE_DEFAULT,
|
||||
).apply {
|
||||
description = "Session summaries and tool call notifications"
|
||||
},
|
||||
NotificationChannel(
|
||||
ERROR_CHANNEL_ID,
|
||||
"Errors",
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
description = "Connection and certificate errors"
|
||||
},
|
||||
NotificationChannel(
|
||||
ALERT_CHANNEL_ID,
|
||||
"Security Alerts",
|
||||
NotificationManager.IMPORTANCE_HIGH,
|
||||
).apply {
|
||||
description = "Security-related alerts requiring attention"
|
||||
},
|
||||
)
|
||||
|
||||
channels.forEach { manager.createNotificationChannel(it) }
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
/**
|
||||
* Pure-function notification state machine.
|
||||
*
|
||||
* Given a [SessionEvent] and current [NotificationSettings], returns a list of
|
||||
* [NotificationAction]s to execute. Contains no Android framework dependencies.
|
||||
*/
|
||||
object NotificationModel {
|
||||
|
||||
/**
|
||||
* Compute the notification actions for a given event and settings.
|
||||
*
|
||||
* The foreground notification is always emitted regardless of mode/permission,
|
||||
* because it is required by the Android foreground service contract.
|
||||
* All other notifications respect the mode and permission settings.
|
||||
*/
|
||||
fun onEvent(
|
||||
event: SessionEvent,
|
||||
settings: NotificationSettings,
|
||||
): List<NotificationAction> {
|
||||
// Permission denied forces suppress for everything except foreground
|
||||
val effectiveMode = if (settings.permissionGranted) {
|
||||
settings.mode
|
||||
} else {
|
||||
NotificationMode.Suppress
|
||||
}
|
||||
|
||||
return when (event) {
|
||||
is SessionEvent.MuxConnected -> listOf(
|
||||
NotificationAction.ShowForeground("Connected"),
|
||||
)
|
||||
|
||||
is SessionEvent.MuxDisconnected -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
if (event.toolCallCount > 0) {
|
||||
add(NotificationAction.PostSummary(event.toolCallCount))
|
||||
} else {
|
||||
add(NotificationAction.PostWarning("Session ended with no tool calls"))
|
||||
}
|
||||
}
|
||||
|
||||
is SessionEvent.StreamOpened -> listOf(
|
||||
NotificationAction.ShowForeground(
|
||||
"Connected \u2022 ${event.streamCount} active stream${plural(event.streamCount)}",
|
||||
),
|
||||
)
|
||||
|
||||
is SessionEvent.StreamClosed -> listOf(
|
||||
NotificationAction.ShowForeground(
|
||||
"Connected \u2022 ${event.streamCount} active stream${plural(event.streamCount)}",
|
||||
),
|
||||
)
|
||||
|
||||
is SessionEvent.ErrorOccurred -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
add(NotificationAction.PostError(event.message, event.streamId))
|
||||
}
|
||||
|
||||
is SessionEvent.ToolCallCompleted -> buildList {
|
||||
if (effectiveMode != NotificationMode.Every) return@buildList
|
||||
add(
|
||||
NotificationAction.PostToolUsage(
|
||||
event.event.toolName,
|
||||
event.event.provider,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
is SessionEvent.CertRenewalStarted -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
add(NotificationAction.PostInfo("Certificate renewal started"))
|
||||
}
|
||||
|
||||
is SessionEvent.CertRenewalFailed -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
add(NotificationAction.PostError("Certificate renewal failed: ${event.message}"))
|
||||
}
|
||||
|
||||
is SessionEvent.CertExpired -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
add(NotificationAction.PostError("Certificate expired"))
|
||||
}
|
||||
|
||||
is SessionEvent.RateLimited -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
add(NotificationAction.PostInfo("Rate limited. Retry after ${event.retryAfterMillis}ms"))
|
||||
}
|
||||
|
||||
is SessionEvent.SecurityAlert -> buildList {
|
||||
if (effectiveMode == NotificationMode.Suppress) return@buildList
|
||||
add(NotificationAction.PostAlert(event.message))
|
||||
}
|
||||
|
||||
is SessionEvent.PermissionChanged -> emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
private fun plural(count: Int): String = if (count == 1) "" else "s"
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
/**
|
||||
* User-configurable notification preferences.
|
||||
*
|
||||
* @property mode Controls which notifications are shown beyond the required foreground notification.
|
||||
* @property permissionGranted Whether the POST_NOTIFICATIONS permission is granted (Android 13+).
|
||||
*/
|
||||
data class NotificationSettings(
|
||||
val mode: NotificationMode = NotificationMode.Summary,
|
||||
val permissionGranted: Boolean = true,
|
||||
)
|
||||
|
||||
/**
|
||||
* Notification verbosity modes.
|
||||
*/
|
||||
enum class NotificationMode {
|
||||
/** Post a summary notification after each session disconnect. */
|
||||
Summary,
|
||||
|
||||
/** Post a notification for every individual tool call. */
|
||||
Every,
|
||||
|
||||
/** Suppress all optional notifications; only show the required foreground notification. */
|
||||
Suppress,
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
import com.rousecontext.mcp.core.ToolCallEvent
|
||||
|
||||
/**
|
||||
* Events that the notification state machine responds to.
|
||||
* Maps tunnel lifecycle + MCP tool calls + system events into a unified stream.
|
||||
*/
|
||||
sealed interface SessionEvent {
|
||||
data object MuxConnected : SessionEvent
|
||||
data class MuxDisconnected(val toolCallCount: Int) : SessionEvent
|
||||
data class StreamOpened(val streamCount: Int) : SessionEvent
|
||||
data class StreamClosed(val streamCount: Int) : SessionEvent
|
||||
|
||||
data class ErrorOccurred(
|
||||
val message: String,
|
||||
val streamId: Int? = null,
|
||||
) : SessionEvent
|
||||
|
||||
data class ToolCallCompleted(val event: ToolCallEvent) : SessionEvent
|
||||
|
||||
data object CertRenewalStarted : SessionEvent
|
||||
data class CertRenewalFailed(val message: String) : SessionEvent
|
||||
data object CertExpired : SessionEvent
|
||||
|
||||
data class RateLimited(val retryAfterMillis: Long) : SessionEvent
|
||||
data class SecurityAlert(val message: String) : SessionEvent
|
||||
data class PermissionChanged(val granted: Boolean) : SessionEvent
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
package com.rousecontext.notifications.audit
|
||||
|
||||
import androidx.room.Dao
|
||||
import androidx.room.Insert
|
||||
import androidx.room.Query
|
||||
|
||||
/**
|
||||
* Data access object for audit entries.
|
||||
*/
|
||||
@Dao
|
||||
interface AuditDao {
|
||||
|
||||
@Insert
|
||||
suspend fun insert(entry: AuditEntry): Long
|
||||
|
||||
@Query("SELECT * FROM audit_entries WHERE sessionId = :sessionId ORDER BY timestampMillis ASC")
|
||||
suspend fun queryBySession(sessionId: String): List<AuditEntry>
|
||||
|
||||
@Query(
|
||||
"SELECT * FROM audit_entries " +
|
||||
"WHERE timestampMillis >= :startMillis AND timestampMillis <= :endMillis " +
|
||||
"AND (:provider IS NULL OR provider = :provider) " +
|
||||
"ORDER BY timestampMillis ASC",
|
||||
)
|
||||
suspend fun queryByDateRange(
|
||||
startMillis: Long,
|
||||
endMillis: Long,
|
||||
provider: String? = null,
|
||||
): List<AuditEntry>
|
||||
|
||||
@Query("DELETE FROM audit_entries WHERE timestampMillis < :cutoffMillis")
|
||||
suspend fun deleteOlderThan(cutoffMillis: Long): Int
|
||||
|
||||
@Query("SELECT COUNT(*) FROM audit_entries")
|
||||
suspend fun count(): Int
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package com.rousecontext.notifications.audit
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Database
|
||||
import androidx.room.Room
|
||||
import androidx.room.RoomDatabase
|
||||
|
||||
/**
|
||||
* Room database for audit log persistence.
|
||||
*/
|
||||
@Database(entities = [AuditEntry::class], version = 1, exportSchema = false)
|
||||
abstract class AuditDatabase : RoomDatabase() {
|
||||
|
||||
abstract fun auditDao(): AuditDao
|
||||
|
||||
companion object {
|
||||
private const val DB_NAME = "rouse_audit.db"
|
||||
|
||||
fun create(context: Context): AuditDatabase =
|
||||
Room.databaseBuilder(context.applicationContext, AuditDatabase::class.java, DB_NAME)
|
||||
.build()
|
||||
|
||||
/**
|
||||
* Create an in-memory database for testing.
|
||||
*/
|
||||
fun createInMemory(context: Context): AuditDatabase =
|
||||
Room.inMemoryDatabaseBuilder(context.applicationContext, AuditDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package com.rousecontext.notifications.audit
|
||||
|
||||
import androidx.room.Entity
|
||||
import androidx.room.PrimaryKey
|
||||
|
||||
/**
|
||||
* Room entity representing a single MCP tool call audit record.
|
||||
*/
|
||||
@Entity(tableName = "audit_entries")
|
||||
data class AuditEntry(
|
||||
@PrimaryKey(autoGenerate = true)
|
||||
val id: Long = 0,
|
||||
val sessionId: String,
|
||||
val toolName: String,
|
||||
val provider: String,
|
||||
val timestampMillis: Long,
|
||||
val durationMillis: Long,
|
||||
val success: Boolean,
|
||||
val errorMessage: String? = null,
|
||||
)
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package com.rousecontext.notifications.audit
|
||||
|
||||
import com.rousecontext.mcp.core.AuditListener
|
||||
import com.rousecontext.mcp.core.ToolCallEvent
|
||||
|
||||
/**
|
||||
* [AuditListener] implementation that persists tool call events to Room.
|
||||
*/
|
||||
class RoomAuditListener(private val dao: AuditDao) : AuditListener {
|
||||
|
||||
override suspend fun onToolCall(event: ToolCallEvent) {
|
||||
dao.insert(
|
||||
AuditEntry(
|
||||
sessionId = event.sessionId,
|
||||
toolName = event.toolName,
|
||||
provider = event.provider,
|
||||
timestampMillis = event.timestampMillis,
|
||||
durationMillis = event.durationMillis,
|
||||
success = event.success,
|
||||
errorMessage = event.errorMessage,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,266 @@
|
|||
package com.rousecontext.notifications
|
||||
|
||||
import com.rousecontext.mcp.core.ToolCallEvent
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class NotificationModelTest {
|
||||
|
||||
private val summarySettings = NotificationSettings(
|
||||
mode = NotificationMode.Summary,
|
||||
permissionGranted = true,
|
||||
)
|
||||
|
||||
private val everySettings = NotificationSettings(
|
||||
mode = NotificationMode.Every,
|
||||
permissionGranted = true,
|
||||
)
|
||||
|
||||
private val suppressSettings = NotificationSettings(
|
||||
mode = NotificationMode.Suppress,
|
||||
permissionGranted = true,
|
||||
)
|
||||
|
||||
// --- MuxConnected ---
|
||||
|
||||
@Test
|
||||
fun `MuxConnected emits ShowForeground`() {
|
||||
val actions = NotificationModel.onEvent(SessionEvent.MuxConnected, summarySettings)
|
||||
assertEquals(1, actions.size)
|
||||
assertTrue(actions[0] is NotificationAction.ShowForeground)
|
||||
}
|
||||
|
||||
// --- MuxDisconnected ---
|
||||
|
||||
@Test
|
||||
fun `MuxDisconnected with tool calls in Summary mode emits PostSummary`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.MuxDisconnected(toolCallCount = 5),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val summary = actions[0] as NotificationAction.PostSummary
|
||||
assertEquals(5, summary.toolCallCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `MuxDisconnected with zero tool calls emits PostWarning`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.MuxDisconnected(toolCallCount = 0),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
assertTrue(actions[0] is NotificationAction.PostWarning)
|
||||
}
|
||||
|
||||
// --- StreamOpened / StreamClosed ---
|
||||
|
||||
@Test
|
||||
fun `StreamOpened updates foreground with stream count`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.StreamOpened(streamCount = 3),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val fg = actions[0] as NotificationAction.ShowForeground
|
||||
assertTrue(fg.message.contains("3"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `StreamClosed updates foreground with stream count`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.StreamClosed(streamCount = 1),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val fg = actions[0] as NotificationAction.ShowForeground
|
||||
assertTrue(fg.message.contains("1"))
|
||||
// Singular form for count of 1
|
||||
assertTrue(fg.message.contains("stream") && !fg.message.contains("streams"))
|
||||
}
|
||||
|
||||
// --- ErrorOccurred ---
|
||||
|
||||
@Test
|
||||
fun `ErrorOccurred connection-level emits PostError`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.ErrorOccurred("Relay unreachable"),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val error = actions[0] as NotificationAction.PostError
|
||||
assertEquals("Relay unreachable", error.message)
|
||||
assertEquals(null, error.streamId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ErrorOccurred stream-level emits PostError with stream context`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.ErrorOccurred("TLS failed", streamId = 7),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val error = actions[0] as NotificationAction.PostError
|
||||
assertEquals(7, error.streamId)
|
||||
}
|
||||
|
||||
// --- ToolCallCompleted ---
|
||||
|
||||
@Test
|
||||
fun `ToolCallCompleted in Every mode emits PostToolUsage`() {
|
||||
val event = ToolCallEvent(
|
||||
sessionId = "s1",
|
||||
toolName = "get_steps",
|
||||
provider = "health",
|
||||
timestampMillis = 1000L,
|
||||
durationMillis = 50L,
|
||||
success = true,
|
||||
)
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.ToolCallCompleted(event),
|
||||
everySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val usage = actions[0] as NotificationAction.PostToolUsage
|
||||
assertEquals("get_steps", usage.toolName)
|
||||
assertEquals("health", usage.provider)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ToolCallCompleted in Summary mode emits nothing`() {
|
||||
val event = ToolCallEvent(
|
||||
sessionId = "s1",
|
||||
toolName = "get_steps",
|
||||
provider = "health",
|
||||
timestampMillis = 1000L,
|
||||
durationMillis = 50L,
|
||||
success = true,
|
||||
)
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.ToolCallCompleted(event),
|
||||
summarySettings,
|
||||
)
|
||||
assertTrue(actions.isEmpty())
|
||||
}
|
||||
|
||||
// --- Suppress mode ---
|
||||
|
||||
@Test
|
||||
fun `Suppress mode emits no optional notifications`() {
|
||||
val events = listOf(
|
||||
SessionEvent.MuxDisconnected(toolCallCount = 3),
|
||||
SessionEvent.ErrorOccurred("fail"),
|
||||
SessionEvent.CertRenewalStarted,
|
||||
SessionEvent.CertRenewalFailed("timeout"),
|
||||
SessionEvent.CertExpired,
|
||||
SessionEvent.RateLimited(60_000L),
|
||||
SessionEvent.SecurityAlert("suspicious"),
|
||||
)
|
||||
|
||||
events.forEach { event ->
|
||||
val actions = NotificationModel.onEvent(event, suppressSettings)
|
||||
assertTrue(
|
||||
"Expected no actions for $event in Suppress mode, got $actions",
|
||||
actions.isEmpty(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Suppress mode still shows foreground notifications`() {
|
||||
val connectActions = NotificationModel.onEvent(SessionEvent.MuxConnected, suppressSettings)
|
||||
assertEquals(1, connectActions.size)
|
||||
assertTrue(connectActions[0] is NotificationAction.ShowForeground)
|
||||
|
||||
val streamActions = NotificationModel.onEvent(
|
||||
SessionEvent.StreamOpened(streamCount = 2),
|
||||
suppressSettings,
|
||||
)
|
||||
assertEquals(1, streamActions.size)
|
||||
assertTrue(streamActions[0] is NotificationAction.ShowForeground)
|
||||
}
|
||||
|
||||
// --- Permission denied forces suppress ---
|
||||
|
||||
@Test
|
||||
fun `Permission denied forces suppress for optional notifications`() {
|
||||
val deniedSettings = NotificationSettings(
|
||||
mode = NotificationMode.Every,
|
||||
permissionGranted = false,
|
||||
)
|
||||
|
||||
// Optional notification suppressed
|
||||
val event = ToolCallEvent(
|
||||
sessionId = "s1",
|
||||
toolName = "get_steps",
|
||||
provider = "health",
|
||||
timestampMillis = 1000L,
|
||||
durationMillis = 50L,
|
||||
success = true,
|
||||
)
|
||||
val toolActions = NotificationModel.onEvent(
|
||||
SessionEvent.ToolCallCompleted(event),
|
||||
deniedSettings,
|
||||
)
|
||||
assertTrue(toolActions.isEmpty())
|
||||
|
||||
// Foreground still works
|
||||
val fgActions = NotificationModel.onEvent(SessionEvent.MuxConnected, deniedSettings)
|
||||
assertEquals(1, fgActions.size)
|
||||
assertTrue(fgActions[0] is NotificationAction.ShowForeground)
|
||||
}
|
||||
|
||||
// --- Certificate events ---
|
||||
|
||||
@Test
|
||||
fun `CertRenewalStarted emits PostInfo`() {
|
||||
val actions = NotificationModel.onEvent(SessionEvent.CertRenewalStarted, summarySettings)
|
||||
assertEquals(1, actions.size)
|
||||
assertTrue(actions[0] is NotificationAction.PostInfo)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `CertRenewalFailed emits PostError`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.CertRenewalFailed("ACME timeout"),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val error = actions[0] as NotificationAction.PostError
|
||||
assertTrue(error.message.contains("ACME timeout"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `CertExpired emits PostError`() {
|
||||
val actions = NotificationModel.onEvent(SessionEvent.CertExpired, summarySettings)
|
||||
assertEquals(1, actions.size)
|
||||
assertTrue(actions[0] is NotificationAction.PostError)
|
||||
}
|
||||
|
||||
// --- RateLimited ---
|
||||
|
||||
@Test
|
||||
fun `RateLimited emits PostInfo with retry info`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.RateLimited(retryAfterMillis = 30_000L),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val info = actions[0] as NotificationAction.PostInfo
|
||||
assertTrue(info.message.contains("30000"))
|
||||
}
|
||||
|
||||
// --- SecurityAlert ---
|
||||
|
||||
@Test
|
||||
fun `SecurityAlert emits PostAlert`() {
|
||||
val actions = NotificationModel.onEvent(
|
||||
SessionEvent.SecurityAlert("Unauthorized access attempt"),
|
||||
summarySettings,
|
||||
)
|
||||
assertEquals(1, actions.size)
|
||||
val alert = actions[0] as NotificationAction.PostAlert
|
||||
assertEquals("Unauthorized access attempt", alert.message)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
package com.rousecontext.notifications.audit
|
||||
|
||||
import android.content.Context
|
||||
import androidx.room.Room
|
||||
import androidx.test.core.app.ApplicationProvider
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
class AuditDaoTest {
|
||||
|
||||
private lateinit var database: AuditDatabase
|
||||
private lateinit var dao: AuditDao
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val context = ApplicationProvider.getApplicationContext<Context>()
|
||||
database = Room.inMemoryDatabaseBuilder(context, AuditDatabase::class.java)
|
||||
.allowMainThreadQueries()
|
||||
.build()
|
||||
dao = database.auditDao()
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
database.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `insert and query by sessionId`() = runBlocking {
|
||||
val entry = createEntry(sessionId = "session-1", toolName = "get_steps")
|
||||
dao.insert(entry)
|
||||
dao.insert(createEntry(sessionId = "session-2", toolName = "get_sleep"))
|
||||
|
||||
val results = dao.queryBySession("session-1")
|
||||
assertEquals(1, results.size)
|
||||
assertEquals("get_steps", results[0].toolName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `query by sessionId returns results ordered by timestamp`() = runBlocking {
|
||||
dao.insert(createEntry(sessionId = "s1", timestampMillis = 3000L, toolName = "third"))
|
||||
dao.insert(createEntry(sessionId = "s1", timestampMillis = 1000L, toolName = "first"))
|
||||
dao.insert(createEntry(sessionId = "s1", timestampMillis = 2000L, toolName = "second"))
|
||||
|
||||
val results = dao.queryBySession("s1")
|
||||
assertEquals(3, results.size)
|
||||
assertEquals("first", results[0].toolName)
|
||||
assertEquals("second", results[1].toolName)
|
||||
assertEquals("third", results[2].toolName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `query by date range`() = runBlocking {
|
||||
dao.insert(createEntry(timestampMillis = 1000L, toolName = "before"))
|
||||
dao.insert(createEntry(timestampMillis = 5000L, toolName = "in-range"))
|
||||
dao.insert(createEntry(timestampMillis = 10000L, toolName = "after"))
|
||||
|
||||
val results = dao.queryByDateRange(startMillis = 3000L, endMillis = 7000L)
|
||||
assertEquals(1, results.size)
|
||||
assertEquals("in-range", results[0].toolName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `query by date range with provider filter`() = runBlocking {
|
||||
dao.insert(
|
||||
createEntry(timestampMillis = 5000L, provider = "health", toolName = "get_steps"),
|
||||
)
|
||||
dao.insert(
|
||||
createEntry(timestampMillis = 5000L, provider = "files", toolName = "read_file"),
|
||||
)
|
||||
|
||||
val allResults = dao.queryByDateRange(
|
||||
startMillis = 1000L,
|
||||
endMillis = 10000L,
|
||||
)
|
||||
assertEquals(2, allResults.size)
|
||||
|
||||
val healthOnly = dao.queryByDateRange(
|
||||
startMillis = 1000L,
|
||||
endMillis = 10000L,
|
||||
provider = "health",
|
||||
)
|
||||
assertEquals(1, healthOnly.size)
|
||||
assertEquals("get_steps", healthOnly[0].toolName)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `retention pruning deletes old entries`() = runBlocking {
|
||||
val thirtyDaysMs = 30L * 24 * 60 * 60 * 1000
|
||||
val now = System.currentTimeMillis()
|
||||
val old = now - thirtyDaysMs - 1000 // 30 days + 1 second ago
|
||||
val recent = now - 1000 // 1 second ago
|
||||
|
||||
dao.insert(createEntry(timestampMillis = old, toolName = "old"))
|
||||
dao.insert(createEntry(timestampMillis = recent, toolName = "recent"))
|
||||
|
||||
val deleted = dao.deleteOlderThan(now - thirtyDaysMs)
|
||||
assertEquals(1, deleted)
|
||||
|
||||
val remaining = dao.count()
|
||||
assertEquals(1, remaining)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty state returns empty list and zero count`() = runBlocking {
|
||||
val bySession = dao.queryBySession("nonexistent")
|
||||
assertTrue(bySession.isEmpty())
|
||||
|
||||
val byDate = dao.queryByDateRange(0L, Long.MAX_VALUE)
|
||||
assertTrue(byDate.isEmpty())
|
||||
|
||||
val count = dao.count()
|
||||
assertEquals(0, count)
|
||||
}
|
||||
|
||||
private fun createEntry(
|
||||
sessionId: String = "test-session",
|
||||
toolName: String = "test_tool",
|
||||
provider: String = "test-provider",
|
||||
timestampMillis: Long = System.currentTimeMillis(),
|
||||
durationMillis: Long = 100L,
|
||||
success: Boolean = true,
|
||||
errorMessage: String? = null,
|
||||
) = AuditEntry(
|
||||
sessionId = sessionId,
|
||||
toolName = toolName,
|
||||
provider = provider,
|
||||
timestampMillis = timestampMillis,
|
||||
durationMillis = durationMillis,
|
||||
success = success,
|
||||
errorMessage = errorMessage,
|
||||
)
|
||||
}
|
||||
|
|
@ -26,3 +26,4 @@ include(":app")
|
|||
include(":tunnel")
|
||||
include(":mcp-core")
|
||||
include(":mcp-health")
|
||||
include(":notifications")
|
||||
|
|
|
|||
17
tunnel/src/main/java/com/rousecontext/tunnel/TunnelError.kt
Normal file
17
tunnel/src/main/java/com/rousecontext/tunnel/TunnelError.kt
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
package com.rousecontext.tunnel
|
||||
|
||||
/**
|
||||
* Errors that can occur during tunnel operation.
|
||||
*/
|
||||
sealed interface TunnelError {
|
||||
val message: String
|
||||
|
||||
/** Connection-level error (relay unreachable, TLS handshake failed, etc.) */
|
||||
data class ConnectionError(override val message: String) : TunnelError
|
||||
|
||||
/** Stream-level error (single MCP session failed within a mux connection) */
|
||||
data class StreamError(
|
||||
override val message: String,
|
||||
val streamId: Int,
|
||||
) : TunnelError
|
||||
}
|
||||
13
tunnel/src/main/java/com/rousecontext/tunnel/TunnelState.kt
Normal file
13
tunnel/src/main/java/com/rousecontext/tunnel/TunnelState.kt
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
package com.rousecontext.tunnel
|
||||
|
||||
/**
|
||||
* Observable state of the tunnel connection lifecycle.
|
||||
*/
|
||||
sealed interface TunnelState {
|
||||
data object Idle : TunnelState
|
||||
data object Connecting : TunnelState
|
||||
data object MuxConnected : TunnelState
|
||||
data object MuxDisconnected : TunnelState
|
||||
data class StreamOpened(val streamCount: Int) : TunnelState
|
||||
data class StreamClosed(val streamCount: Int) : TunnelState
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue