Keep settings and delivery updates together
Preserve the reviewed grouped Settings page while fixing its embedded phone safe area, and land the accompanying notification, walkthrough, terminal, and documentation updates captured by this run.
This commit is contained in:
@@ -12,6 +12,11 @@
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
|
||||
<!-- Reconnects are alarms that fire during Doze; exact timing needs this
|
||||
grant (Android 12+, user-revocable), otherwise idle-tolerant alarms.
|
||||
The short connect hold uses a partial wake lock. -->
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK"/>
|
||||
<!-- "Find servers on this network" browses _pipelines._tcp with NSD;
|
||||
Wi-Fi drops multicast without a multicast lock, held only while a
|
||||
scan runs (lib/features/onboarding/discovery/). -->
|
||||
@@ -69,6 +74,11 @@
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Persistent connection to the user's self-hosted Pipelines server for instant notifications"/>
|
||||
</service>
|
||||
<!-- Periodic check that restarts the notification service if it is down. -->
|
||||
<service
|
||||
android:name=".notify.NotificationWatchdog"
|
||||
android:exported="false"
|
||||
android:permission="android.permission.BIND_JOB_SERVICE"/>
|
||||
<receiver
|
||||
android:name=".notify.NotificationDismissReceiver"
|
||||
android:exported="false"/>
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import android.content.Context
|
||||
import android.os.PowerManager
|
||||
|
||||
/**
|
||||
* A short partial wake lock held while the service opens its socket, so the
|
||||
* CPU stays awake through the handshake. The timeout bounds it if no answer
|
||||
* comes; [release] runs as soon as the socket opens or fails.
|
||||
*/
|
||||
class ConnectWakeLock(context: Context) {
|
||||
private val lock = context.getSystemService(PowerManager::class.java)
|
||||
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "pipelines:connect")
|
||||
.apply { setReferenceCounted(false) }
|
||||
|
||||
fun hold() {
|
||||
lock.acquire(HOLD_MILLIS)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (lock.isHeld) lock.release()
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val HOLD_MILLIS = 30_000L
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
|
||||
/** One entry of the connection log: when, what happened, and the error or HTTP code. */
|
||||
data class ConnectionEvent(
|
||||
val timeMillis: Long,
|
||||
val event: String,
|
||||
val error: String?,
|
||||
val code: Int?,
|
||||
)
|
||||
|
||||
/**
|
||||
* The last [CAPACITY] connection events, kept in the service's preferences so
|
||||
* Settings can show why delivery stalled. Newest first. Error text is trimmed;
|
||||
* the session cookie never reaches the log.
|
||||
*/
|
||||
class ConnectionLog(
|
||||
private val store: LedgerStore,
|
||||
private val clock: () -> Long = System::currentTimeMillis,
|
||||
) {
|
||||
/** Read-modify-write: the main thread (task removal) and the service thread both log. */
|
||||
@Synchronized
|
||||
fun record(event: String, error: String? = null, code: Int? = null) {
|
||||
val entry = ConnectionEvent(clock(), event, error?.take(MAX_ERROR_LENGTH), code)
|
||||
store.putString(KEY, encode((listOf(entry) + entries()).take(CAPACITY)))
|
||||
}
|
||||
|
||||
fun entries(): List<ConnectionEvent> = decode(store.getString(KEY))
|
||||
|
||||
companion object {
|
||||
const val CAPACITY = 50
|
||||
const val KEY = "connection.log"
|
||||
private const val MAX_ERROR_LENGTH = 200
|
||||
|
||||
private fun encode(events: List<ConnectionEvent>): String {
|
||||
val array = JSONArray()
|
||||
for (event in events) {
|
||||
array.put(
|
||||
JSONObject()
|
||||
.put("t", event.timeMillis)
|
||||
.put("e", event.event)
|
||||
.apply {
|
||||
event.error?.let { put("x", it) }
|
||||
event.code?.let { put("c", it) }
|
||||
},
|
||||
)
|
||||
}
|
||||
return array.toString()
|
||||
}
|
||||
|
||||
/** A corrupt log reads as empty rather than breaking Settings. */
|
||||
private fun decode(raw: String?): List<ConnectionEvent> {
|
||||
if (raw.isNullOrEmpty()) return emptyList()
|
||||
return try {
|
||||
val array = JSONArray(raw)
|
||||
(0 until array.length()).map { index ->
|
||||
val item = array.getJSONObject(index)
|
||||
ConnectionEvent(
|
||||
timeMillis = item.getLong("t"),
|
||||
event = item.getString("e"),
|
||||
error = if (item.has("x")) item.getString("x") else null,
|
||||
code = if (item.has("c")) item.getInt("c") else null,
|
||||
)
|
||||
}
|
||||
} catch (_: JSONException) {
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
-7
@@ -27,21 +27,16 @@ class NotificationPresenter(private val context: Context) {
|
||||
DeliveryStatus.CONNECTED -> "Pipelines is connected"
|
||||
DeliveryStatus.WAITING_FOR_NETWORK -> "Pipelines is waiting for a network"
|
||||
DeliveryStatus.CONNECTING -> "Pipelines is connecting…"
|
||||
DeliveryStatus.SIGN_IN_REQUIRED -> "Pipelines needs you to sign in"
|
||||
else -> "Pipelines is reconnecting…"
|
||||
}
|
||||
val open = PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
return builder(CONNECTION_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setContentTitle(text)
|
||||
.setContentText("Delivering notifications from your server")
|
||||
.setOngoing(true)
|
||||
.setShowWhen(false)
|
||||
.setContentIntent(open)
|
||||
.setContentIntent(openApp())
|
||||
.setCategory(Notification.CATEGORY_SERVICE)
|
||||
.build()
|
||||
}
|
||||
@@ -50,6 +45,30 @@ class NotificationPresenter(private val context: Context) {
|
||||
manager.notify(CONNECTION_ID, connectionNotification(status))
|
||||
}
|
||||
|
||||
/** Posted when the server refuses the session; cleared once a connection opens. */
|
||||
fun signInRequired() {
|
||||
ensureChannel(ACCOUNT_CHANNEL, "Sign-in", NotificationManager.IMPORTANCE_DEFAULT, null)
|
||||
val notification = builder(ACCOUNT_CHANNEL)
|
||||
.setSmallIcon(R.drawable.ic_stat_pipelines)
|
||||
.setContentTitle("Sign in to Pipelines again to keep notifications")
|
||||
.setContentText("Notifications are paused until you sign in.")
|
||||
.setAutoCancel(true)
|
||||
.setContentIntent(openApp())
|
||||
.build()
|
||||
manager.notify(SIGN_IN_ID, notification)
|
||||
}
|
||||
|
||||
fun clearSignIn() {
|
||||
manager.cancel(SIGN_IN_ID)
|
||||
}
|
||||
|
||||
private fun openApp(): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
fun show(notification: ServerNotification) {
|
||||
val id = DeliveryLedger.notificationId(notification.id)
|
||||
val channel = channelFor(notification)
|
||||
@@ -182,6 +201,9 @@ class NotificationPresenter(private val context: Context) {
|
||||
companion object {
|
||||
const val CONNECTION_ID = 1
|
||||
const val CONNECTION_CHANNEL = "pipelines.connection"
|
||||
/** The "sign in again" notice; ids up to RESERVED_IDS are the service's own. */
|
||||
const val SIGN_IN_ID = 2
|
||||
const val ACCOUNT_CHANNEL = "pipelines.account"
|
||||
const val EXTRA_NOTIFICATION_ID = "net.awan.pipelines.notification_id"
|
||||
|
||||
private val KIND_LABELS = mapOf(
|
||||
|
||||
+104
-10
@@ -24,6 +24,10 @@ import java.util.concurrent.TimeUnit
|
||||
* engine runs here. It subscribes with the replay cursor, posts each pushed
|
||||
* notification, mirrors cross-device clears and sends the user's own clears.
|
||||
*
|
||||
* Reconnects are alarms (ReconnectAlarms), so they fire during Doze; a
|
||||
* periodic NotificationWatchdog restarts the service if it is down. A refused
|
||||
* session (HTTP 401/403) stops the retry loop until a fresh cookie arrives.
|
||||
*
|
||||
* All state is confined to [handler]'s thread; OkHttp and connectivity
|
||||
* callbacks post onto it.
|
||||
*/
|
||||
@@ -31,6 +35,8 @@ class NotificationService : Service() {
|
||||
private lateinit var settings: ServiceSettings
|
||||
private lateinit var ledger: DeliveryLedger
|
||||
private lateinit var presenter: NotificationPresenter
|
||||
private lateinit var log: ConnectionLog
|
||||
private lateinit var wakeLock: ConnectWakeLock
|
||||
private lateinit var thread: HandlerThread
|
||||
private lateinit var handler: Handler
|
||||
private val client = OkHttpClient.Builder()
|
||||
@@ -48,7 +54,8 @@ class NotificationService : Service() {
|
||||
private var networkAvailable = true
|
||||
private var currentNetwork: Network? = null
|
||||
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||
private val reconnect = Runnable { connect() }
|
||||
/** A reconnect alarm is pending for the socket that is down. */
|
||||
private var reconnectPending = false
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
@@ -57,6 +64,8 @@ class NotificationService : Service() {
|
||||
settings = ServiceSettings(this)
|
||||
ledger = DeliveryLedger(settings)
|
||||
presenter = NotificationPresenter(this)
|
||||
log = ConnectionLog(settings)
|
||||
wakeLock = ConnectWakeLock(this)
|
||||
thread = HandlerThread("pipelines-notifications").also { it.start() }
|
||||
handler = Handler(thread.looper)
|
||||
goForeground(DeliveryStatus.CONNECTING)
|
||||
@@ -66,16 +75,36 @@ class NotificationService : Service() {
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
val action = intent?.action
|
||||
// Alarms and the watchdog may start the service from the background;
|
||||
// it must be foreground promptly, so do that before queuing the work.
|
||||
goForeground(settings.status.let { if (it == DeliveryStatus.OFF) DeliveryStatus.CONNECTING else it })
|
||||
handler.post {
|
||||
when {
|
||||
!settings.enabled || !settings.configured -> stopEverything()
|
||||
action == ACTION_FLUSH -> flushClears()
|
||||
action == ACTION_WATCHDOG -> if (isDown()) {
|
||||
log.record("watchdog_restart")
|
||||
restart()
|
||||
}
|
||||
action == ACTION_RECONNECT -> if (socket == null && settings.status != DeliveryStatus.SIGN_IN_REQUIRED) connect()
|
||||
action == ACTION_RESTART || socket == null -> restart()
|
||||
}
|
||||
}
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
/**
|
||||
* The app was swiped away. The foreground service keeps running, so this
|
||||
* only queues a watchdog check shortly after, in case the process is lost.
|
||||
*/
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
log.record("task_removed")
|
||||
if (settings.enabled && settings.configured) {
|
||||
ReconnectAlarms.schedule(this, TASK_REMOVED_CHECK_MILLIS, ACTION_WATCHDOG)
|
||||
}
|
||||
super.onTaskRemoved(rootIntent)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
running = null
|
||||
networkCallback?.let {
|
||||
@@ -87,6 +116,7 @@ class NotificationService : Service() {
|
||||
socket?.close(1000, "service stopped")
|
||||
socket = null
|
||||
}
|
||||
wakeLock.release()
|
||||
thread.quitSafely()
|
||||
if (settings.status != DeliveryStatus.UNCONFIGURED) setStatus(DeliveryStatus.OFF, notify = false)
|
||||
super.onDestroy()
|
||||
@@ -109,22 +139,33 @@ class NotificationService : Service() {
|
||||
generation++
|
||||
socket?.close(1000, "disabled")
|
||||
socket = null
|
||||
cancelReconnect()
|
||||
wakeLock.release()
|
||||
log.record("stopped")
|
||||
setStatus(if (settings.configured) DeliveryStatus.OFF else DeliveryStatus.UNCONFIGURED, notify = false)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
/**
|
||||
* Delivery is meant to be running but no socket is open or on its way.
|
||||
* Waiting for the network and a refused session are deliberate states.
|
||||
*/
|
||||
private fun isDown(): Boolean =
|
||||
socket == null && !reconnectPending &&
|
||||
settings.status != DeliveryStatus.SIGN_IN_REQUIRED &&
|
||||
settings.status != DeliveryStatus.WAITING_FOR_NETWORK
|
||||
|
||||
/** Server changed, credentials changed, or the first start: reopen now. */
|
||||
private fun restart() {
|
||||
if (ledger.bindServer(settings.serverId)) presenter.cancelAll()
|
||||
handler.removeCallbacks(reconnect)
|
||||
backoff.reset()
|
||||
endpointIndex = 0
|
||||
connect()
|
||||
}
|
||||
|
||||
private fun connect() {
|
||||
handler.removeCallbacks(reconnect)
|
||||
cancelReconnect()
|
||||
generation++
|
||||
socket?.cancel()
|
||||
socket = null
|
||||
@@ -139,9 +180,12 @@ class NotificationService : Service() {
|
||||
}.build()
|
||||
} catch (error: IllegalArgumentException) {
|
||||
Log.w(TAG, "invalid endpoint $endpoint", error)
|
||||
log.record("invalid_endpoint", endpoint)
|
||||
return scheduleReconnect()
|
||||
}
|
||||
setStatus(if (backoff.attempt == 0) DeliveryStatus.CONNECTING else DeliveryStatus.RECONNECTING)
|
||||
log.record("connecting", endpoint)
|
||||
wakeLock.hold()
|
||||
val current = generation
|
||||
socket = client.newWebSocket(request, Listener(current))
|
||||
}
|
||||
@@ -151,15 +195,46 @@ class NotificationService : Service() {
|
||||
socket?.cancel()
|
||||
socket = null
|
||||
subscribeId = null
|
||||
if (!networkAvailable) return setStatus(DeliveryStatus.WAITING_FOR_NETWORK)
|
||||
wakeLock.release()
|
||||
if (!networkAvailable) {
|
||||
cancelReconnect()
|
||||
return setStatus(DeliveryStatus.WAITING_FOR_NETWORK)
|
||||
}
|
||||
setStatus(DeliveryStatus.RECONNECTING)
|
||||
// Rotate through the server's trusted aliases on each failure.
|
||||
endpointIndex++
|
||||
handler.postDelayed(reconnect, backoff.next())
|
||||
val delay = backoff.next()
|
||||
reconnectPending = true
|
||||
ReconnectAlarms.schedule(this, delay, ACTION_RECONNECT)
|
||||
log.record("retry_scheduled", "in ${delay / 1000}s")
|
||||
}
|
||||
|
||||
private fun cancelReconnect() {
|
||||
reconnectPending = false
|
||||
ReconnectAlarms.cancel(this, ACTION_RECONNECT)
|
||||
}
|
||||
|
||||
/**
|
||||
* The server refused the session cookie. Retrying cannot succeed, so the
|
||||
* loop stops here; a fresh cookie from the app restarts it.
|
||||
*/
|
||||
private fun signInRequired(code: Int) {
|
||||
generation++
|
||||
socket?.cancel()
|
||||
socket = null
|
||||
subscribeId = null
|
||||
wakeLock.release()
|
||||
cancelReconnect()
|
||||
log.record("sign_in_required", "HTTP $code", code)
|
||||
setStatus(DeliveryStatus.SIGN_IN_REQUIRED)
|
||||
presenter.signInRequired()
|
||||
}
|
||||
|
||||
private fun onOpen(webSocket: WebSocket) {
|
||||
backoff.reset()
|
||||
wakeLock.release()
|
||||
presenter.clearSignIn()
|
||||
log.record("connected")
|
||||
val id = "notify-${++sequence}"
|
||||
subscribeId = id
|
||||
webSocket.send(NotificationProtocol.subscribe(id, ledger.cursor))
|
||||
@@ -179,6 +254,7 @@ class NotificationService : Service() {
|
||||
is NotificationFrame.Cleared -> presenter.cancel(frame.ids)
|
||||
is NotificationFrame.Refused -> {
|
||||
Log.w(TAG, "subscribe_notifications refused: ${frame.error}")
|
||||
log.record("refused", "${frame.error}")
|
||||
scheduleReconnect()
|
||||
}
|
||||
NotificationFrame.Ignored -> Unit
|
||||
@@ -212,13 +288,16 @@ class NotificationService : Service() {
|
||||
val previous = currentNetwork
|
||||
currentNetwork = network
|
||||
networkAvailable = true
|
||||
log.record("network_available")
|
||||
// A new default network invalidates the old socket's route;
|
||||
// a returning network retries at once instead of waiting
|
||||
// out the backoff.
|
||||
// out the backoff. A refused session waits for a cookie.
|
||||
val moved = previous != null && previous != network
|
||||
val idle = settings.status == DeliveryStatus.WAITING_FOR_NETWORK ||
|
||||
settings.status == DeliveryStatus.RECONNECTING
|
||||
if (settings.configured && (moved || previous == null || idle)) {
|
||||
if (settings.configured && settings.status != DeliveryStatus.SIGN_IN_REQUIRED &&
|
||||
(moved || previous == null || idle)
|
||||
) {
|
||||
backoff.reset()
|
||||
connect()
|
||||
}
|
||||
@@ -230,6 +309,7 @@ class NotificationService : Service() {
|
||||
if (network != currentNetwork) return@post
|
||||
currentNetwork = null
|
||||
networkAvailable = false
|
||||
log.record("network_lost")
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
@@ -249,17 +329,27 @@ class NotificationService : Service() {
|
||||
webSocket.close(1000, null)
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current { scheduleReconnect() }
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current {
|
||||
Log.i(TAG, "socket failed (${response?.code}): ${t.message}")
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = current {
|
||||
log.record("closed", "close $code ${reason}".trim())
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = current {
|
||||
val code = response?.code
|
||||
Log.i(TAG, "socket failed ($code): ${t.message}")
|
||||
log.record("failed", t.message ?: t.javaClass.simpleName, code)
|
||||
if (ReconnectPolicy.isAuthRejection(code) && code != null) signInRequired(code)
|
||||
else scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "PipelinesNotify"
|
||||
const val ACTION_RESTART = "net.awan.pipelines.notify.RESTART"
|
||||
const val ACTION_FLUSH = "net.awan.pipelines.notify.FLUSH"
|
||||
const val ACTION_RECONNECT = "net.awan.pipelines.notify.RECONNECT"
|
||||
const val ACTION_WATCHDOG = "net.awan.pipelines.notify.WATCHDOG"
|
||||
private const val TASK_REMOVED_CHECK_MILLIS = 2_000L
|
||||
|
||||
@Volatile
|
||||
var running: NotificationService? = null
|
||||
@@ -277,6 +367,7 @@ class NotificationService : Service() {
|
||||
return try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
|
||||
else context.startService(intent)
|
||||
NotificationWatchdog.schedule(context)
|
||||
true
|
||||
} catch (error: Exception) {
|
||||
// Android 12+ refuses a foreground start from some background
|
||||
@@ -287,6 +378,9 @@ class NotificationService : Service() {
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
ReconnectAlarms.cancel(context, ACTION_RECONNECT)
|
||||
ReconnectAlarms.cancel(context, ACTION_WATCHDOG)
|
||||
NotificationWatchdog.cancel(context)
|
||||
context.stopService(Intent(context, NotificationService::class.java))
|
||||
}
|
||||
}
|
||||
|
||||
+15
-4
@@ -52,10 +52,9 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
|
||||
return
|
||||
}
|
||||
val changed = settings.configure(serverId, endpoints, cookie)
|
||||
val running = NotificationService.running != null
|
||||
if (changed || !running) {
|
||||
NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null)
|
||||
}
|
||||
// A null action still restarts a service whose socket is down,
|
||||
// which is how a refused session resumes with a fresh cookie.
|
||||
NotificationService.start(activity, if (changed) NotificationService.ACTION_RESTART else null)
|
||||
result.success(status())
|
||||
}
|
||||
"setEnabled" -> {
|
||||
@@ -69,6 +68,7 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
|
||||
}
|
||||
result.success(status())
|
||||
}
|
||||
"connectionEvents" -> result.success(connectionEvents())
|
||||
"requestBatteryExemption" -> {
|
||||
result.success(requestBatteryExemption())
|
||||
}
|
||||
@@ -92,6 +92,17 @@ class NotificationServiceChannel(private val activity: Activity, messenger: Bina
|
||||
)
|
||||
}
|
||||
|
||||
/** The last connection events, newest first, for Settings' diagnosis. */
|
||||
private fun connectionEvents(): List<Map<String, Any>> =
|
||||
ConnectionLog(settings).entries().map { event ->
|
||||
buildMap {
|
||||
put("time", event.timeMillis)
|
||||
put("event", event.event)
|
||||
event.error?.let { put("error", it) }
|
||||
event.code?.let { put("code", it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun batteryExempt(): Boolean =
|
||||
activity.getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(activity.packageName)
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import android.app.job.JobInfo
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobScheduler
|
||||
import android.app.job.JobService
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* A periodic check that the notification service is alive and connected while
|
||||
* delivery is on. If the process was killed, or the socket is down with no
|
||||
* reconnect pending, it starts the service again. JobScheduler defers jobs in
|
||||
* Doze, so the reconnect alarms remain the primary path; this is the net under
|
||||
* them.
|
||||
*/
|
||||
class NotificationWatchdog : JobService() {
|
||||
override fun onStartJob(params: JobParameters?): Boolean {
|
||||
val settings = ServiceSettings(this)
|
||||
if (settings.enabled && settings.configured) {
|
||||
NotificationService.start(this, NotificationService.ACTION_WATCHDOG)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun onStopJob(params: JobParameters?): Boolean = true
|
||||
|
||||
companion object {
|
||||
private const val JOB_ID = 4201
|
||||
private const val PERIOD_MILLIS = 15 * 60_000L
|
||||
|
||||
fun schedule(context: Context) {
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
if (scheduler.getPendingJob(JOB_ID) != null) return
|
||||
val job = JobInfo.Builder(JOB_ID, ComponentName(context, NotificationWatchdog::class.java))
|
||||
.setPeriodic(PERIOD_MILLIS)
|
||||
.setPersisted(true)
|
||||
.build()
|
||||
scheduler.schedule(job)
|
||||
}
|
||||
|
||||
fun cancel(context: Context) {
|
||||
context.getSystemService(JobScheduler::class.java).cancel(JOB_ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import android.app.AlarmManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.SystemClock
|
||||
|
||||
/**
|
||||
* Wakes the notification service when a reconnect, restart or watchdog check
|
||||
* is due. A Handler delay pauses while the device dozes; an alarm does not.
|
||||
* Each action has one pending alarm: scheduling again replaces it.
|
||||
*/
|
||||
object ReconnectAlarms {
|
||||
fun schedule(context: Context, delayMillis: Long, action: String) {
|
||||
val manager = context.getSystemService(AlarmManager::class.java)
|
||||
val at = SystemClock.elapsedRealtime() + delayMillis
|
||||
val pending = pendingFor(context, action)
|
||||
val exact = ReconnectPolicy.alarmMode(exactPermitted(context)) ==
|
||||
ReconnectPolicy.AlarmMode.EXACT_WHILE_IDLE
|
||||
try {
|
||||
if (exact) {
|
||||
manager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending)
|
||||
} else {
|
||||
manager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending)
|
||||
}
|
||||
} catch (_: SecurityException) {
|
||||
// The exact-alarm grant was revoked between the check and the call.
|
||||
manager.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, at, pending)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancel(context: Context, action: String) {
|
||||
val existing = lookup(context, action) ?: return
|
||||
context.getSystemService(AlarmManager::class.java).cancel(existing)
|
||||
existing.cancel()
|
||||
}
|
||||
|
||||
fun exactPermitted(context: Context): Boolean =
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
|
||||
context.getSystemService(AlarmManager::class.java).canScheduleExactAlarms()
|
||||
|
||||
/**
|
||||
* Schedule and cancel must build the same kind of PendingIntent (a
|
||||
* foreground-service one on Android 8+), or a cancel matches nothing.
|
||||
* An alarm may start the service from the background; on Android 8+ that
|
||||
* must be a foreground start, which the service then satisfies.
|
||||
*/
|
||||
private fun pendingFor(context: Context, action: String): PendingIntent =
|
||||
checkNotNull(build(context, action, PendingIntent.FLAG_UPDATE_CURRENT)) {
|
||||
"FLAG_UPDATE_CURRENT always yields a PendingIntent"
|
||||
}
|
||||
|
||||
private fun lookup(context: Context, action: String): PendingIntent? =
|
||||
build(context, action, PendingIntent.FLAG_NO_CREATE)
|
||||
|
||||
private fun build(context: Context, action: String, mode: Int): PendingIntent? {
|
||||
val intent = Intent(context, NotificationService::class.java).setAction(action)
|
||||
val flags = PendingIntent.FLAG_IMMUTABLE or mode
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
PendingIntent.getForegroundService(context, requestCode(action), intent, flags)
|
||||
} else {
|
||||
PendingIntent.getService(context, requestCode(action), intent, flags)
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestCode(action: String): Int = action.hashCode()
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
/** Decisions the service makes on a failed socket, kept free of Android types. */
|
||||
object ReconnectPolicy {
|
||||
/**
|
||||
* HTTP 401/403 on the websocket handshake: the session cookie is no longer
|
||||
* accepted. Retrying cannot succeed, so the service waits for a fresh cookie.
|
||||
*/
|
||||
fun isAuthRejection(code: Int?): Boolean = code == 401 || code == 403
|
||||
|
||||
/**
|
||||
* Exact alarms need SCHEDULE_EXACT_ALARM (Android 12+, user-revocable). When
|
||||
* it is not granted the reconnect still fires during Doze, just inexactly.
|
||||
*/
|
||||
fun alarmMode(exactPermitted: Boolean): AlarmMode =
|
||||
if (exactPermitted) AlarmMode.EXACT_WHILE_IDLE else AlarmMode.WHILE_IDLE
|
||||
|
||||
enum class AlarmMode { EXACT_WHILE_IDLE, WHILE_IDLE }
|
||||
}
|
||||
@@ -11,6 +11,8 @@ enum class DeliveryStatus(val wire: String) {
|
||||
CONNECTED("connected"),
|
||||
RECONNECTING("reconnecting"),
|
||||
WAITING_FOR_NETWORK("waiting_for_network"),
|
||||
/** The server refused the session; delivery resumes when the app hands over a fresh cookie. */
|
||||
SIGN_IN_REQUIRED("sign_in_required"),
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ConnectionLogTest {
|
||||
private class MemoryStore : LedgerStore {
|
||||
val values = mutableMapOf<String, String>()
|
||||
override fun getString(key: String) = values[key]
|
||||
override fun putString(key: String, value: String?) {
|
||||
if (value == null) values.remove(key) else values[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
private class Clock(var now: Long = 1_000L) {
|
||||
fun tick(): Long = now++
|
||||
}
|
||||
|
||||
@Test
|
||||
fun keepsTheLastFiftyEventsNewestFirst() {
|
||||
val store = MemoryStore()
|
||||
val clock = Clock()
|
||||
val log = ConnectionLog(store, clock::tick)
|
||||
repeat(ConnectionLog.CAPACITY + 10) { index -> log.record("event-$index") }
|
||||
val entries = log.entries()
|
||||
assertEquals(ConnectionLog.CAPACITY, entries.size)
|
||||
assertEquals("event-59", entries.first().event)
|
||||
assertEquals("event-10", entries.last().event)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun errorAndCodeSurviveAReload() {
|
||||
val store = MemoryStore()
|
||||
ConnectionLog(store) { 42L }.record("failed", "Expected HTTP 101", 403)
|
||||
val entry = ConnectionLog(store).entries().single()
|
||||
assertEquals(42L, entry.timeMillis)
|
||||
assertEquals("failed", entry.event)
|
||||
assertEquals("Expected HTTP 101", entry.error)
|
||||
assertEquals(403, entry.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun eventsWithoutErrorOrCodeReadBackAsNull() {
|
||||
val store = MemoryStore()
|
||||
ConnectionLog(store).record("connected")
|
||||
val entry = ConnectionLog(store).entries().single()
|
||||
assertNull(entry.error)
|
||||
assertNull(entry.code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun longErrorTextIsTrimmed() {
|
||||
val store = MemoryStore()
|
||||
ConnectionLog(store).record("failed", "x".repeat(500))
|
||||
val error = ConnectionLog(store).entries().single().error!!
|
||||
assertEquals(200, error.length)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun corruptLogReadsAsEmptyInsteadOfThrowing() {
|
||||
val store = MemoryStore()
|
||||
store.values[ConnectionLog.KEY] = "not json"
|
||||
assertTrue(ConnectionLog(store).entries().isEmpty())
|
||||
ConnectionLog(store).record("connected")
|
||||
assertEquals("connected", ConnectionLog(store).entries().single().event)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package net.awan.pipelines_app.notify
|
||||
|
||||
import net.awan.pipelines_app.notify.ReconnectPolicy.AlarmMode
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class ReconnectPolicyTest {
|
||||
@Test
|
||||
fun http401And403StopTheRetryLoop() {
|
||||
assertTrue(ReconnectPolicy.isAuthRejection(401))
|
||||
assertTrue(ReconnectPolicy.isAuthRejection(403))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun otherFailuresKeepRetrying() {
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(null))
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(500))
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(503))
|
||||
assertFalse(ReconnectPolicy.isAuthRejection(404))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun exactAlarmsWhenPermittedOtherwiseIdleTolerant() {
|
||||
assertEquals(AlarmMode.EXACT_WHILE_IDLE, ReconnectPolicy.alarmMode(true))
|
||||
assertEquals(AlarmMode.WHILE_IDLE, ReconnectPolicy.alarmMode(false))
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import '../features/terminal/terminal_machines.dart';
|
||||
import '../features/terminal/terminal_surface.dart';
|
||||
import '../features/terminal/terminal_toggle_button.dart';
|
||||
import '../features/terminal/terminal_window.dart';
|
||||
import '../shell/list_detail_policy.dart';
|
||||
import '../shell/windows/window_manager.dart';
|
||||
|
||||
/// The app's machine terminals: one hub over every connected machine (the
|
||||
@@ -66,6 +67,14 @@ class AppTerminals {
|
||||
/// The bar button showing or hiding the terminal.
|
||||
Widget toggle() => TerminalToggleButton(layout: layout);
|
||||
|
||||
/// The Chat tab's shell-bar button. Only a wide layout shows the shell bar
|
||||
/// over an open chat, so only there is it kept. A narrow layout has none:
|
||||
/// its open chat's own bar carries the terminal (see
|
||||
/// `terminalChatBarAction`), and a chat list's bar has none (the shortcut
|
||||
/// still shows the terminal).
|
||||
Widget? barToggle(BuildContext context) =>
|
||||
showsListBesideDetail(context) ? toggle() : null;
|
||||
|
||||
void dispose() {
|
||||
floating?.dispose();
|
||||
hub.dispose();
|
||||
|
||||
@@ -28,6 +28,9 @@ import '../features/runs/ui/run_search_selection.dart';
|
||||
import '../features/search/domain/search_target.dart';
|
||||
import '../features/settings/settings_screen.dart';
|
||||
import '../features/settings/settings_store.dart';
|
||||
import '../features/walkthrough/first_run_walkthrough.dart';
|
||||
import '../features/walkthrough/walkthrough_gate.dart';
|
||||
import '../features/walkthrough/walkthrough_store.dart';
|
||||
import '../features/updates/app_updates.dart';
|
||||
import '../features/updates/launch_update.dart';
|
||||
import '../features/updates/launch_update_dialog.dart';
|
||||
@@ -579,6 +582,10 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
_attentionCount.value = count;
|
||||
}
|
||||
|
||||
/// The device's first-run walkthrough record (per device, not per server).
|
||||
final WalkthroughStore _walkthroughStore =
|
||||
const SharedPreferencesWalkthroughStore();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => widget.servers == null
|
||||
? MyApp.router(routerConfig: _config)
|
||||
@@ -820,13 +827,14 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
final runsRoute = tab(AppDestination.runs);
|
||||
final chatRoute = tab(AppDestination.chat);
|
||||
return AdaptiveShell(
|
||||
// The terminal button sits on the Chat tab only; the keyboard
|
||||
// The terminal button sits on the Chat tab's shell bar on wide layouts;
|
||||
// a narrow layout has it in the chat's own bar instead. The keyboard
|
||||
// shortcut still toggles the terminal everywhere.
|
||||
barActions: [
|
||||
// Shown on every tab while the app has floating windows.
|
||||
WindowsMenuButton(manager: _windows),
|
||||
if (_destinationOf(route.kind) == AppDestination.chat)
|
||||
_terminals.toggle(),
|
||||
?_terminals.barToggle(context),
|
||||
],
|
||||
attentionCount: counts.attention,
|
||||
runningRunCount: counts.running,
|
||||
@@ -837,32 +845,40 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
_bodyRoutes[AppDestination.pipelines] ?? AppRoute.pipelines,
|
||||
),
|
||||
destinationBodies: {
|
||||
AppDestination.pipelines: (_) => PipelinesDestination(
|
||||
session: _session,
|
||||
server: widget.server,
|
||||
active: _destinationOf(route.kind) == AppDestination.pipelines,
|
||||
legacyPendingEndpoints: widget.legacyPendingEndpoints,
|
||||
refreshToken: _pipelinesRefresh,
|
||||
onRunStarted: _runStarted,
|
||||
onViewPipelineRuns: (id) =>
|
||||
_delegate.goTo(AppRoute.runsForPipeline(id)),
|
||||
onOpenSchedules: _delegate.openSchedules,
|
||||
onOpenSettings: () => _delegate.goTo(AppRoute.settings),
|
||||
// The open pipeline is part of the route, so Back steps out of it.
|
||||
onSelectionChanged: (id) {
|
||||
final current = _delegate.route;
|
||||
if (current.kind != AppRouteKind.pipelines) return;
|
||||
if (id == null) {
|
||||
if (current.pipelineId != null) {
|
||||
_delegate.goTo(AppRoute.pipelines);
|
||||
AppDestination.pipelines: (_) => FirstRunWalkthroughGate(
|
||||
store: _walkthroughStore,
|
||||
enabled: _destinationOf(route.kind) == AppDestination.pipelines,
|
||||
serverScope: _navigationScope,
|
||||
connection: _session,
|
||||
connected: () => _session.connected,
|
||||
gateway: _session.client,
|
||||
child: PipelinesDestination(
|
||||
session: _session,
|
||||
server: widget.server,
|
||||
active: _destinationOf(route.kind) == AppDestination.pipelines,
|
||||
legacyPendingEndpoints: widget.legacyPendingEndpoints,
|
||||
refreshToken: _pipelinesRefresh,
|
||||
onRunStarted: _runStarted,
|
||||
onViewPipelineRuns: (id) =>
|
||||
_delegate.goTo(AppRoute.runsForPipeline(id)),
|
||||
onOpenSchedules: _delegate.openSchedules,
|
||||
onOpenSettings: () => _delegate.goTo(AppRoute.settings),
|
||||
// The open pipeline is part of the route, so Back steps out of it.
|
||||
onSelectionChanged: (id) {
|
||||
final current = _delegate.route;
|
||||
if (current.kind != AppRouteKind.pipelines) return;
|
||||
if (id == null) {
|
||||
if (current.pipelineId != null) {
|
||||
_delegate.goTo(AppRoute.pipelines);
|
||||
}
|
||||
} else if (current.pipelineId != id) {
|
||||
_delegate.goTo(AppRoute.pipeline(id));
|
||||
}
|
||||
} else if (current.pipelineId != id) {
|
||||
_delegate.goTo(AppRoute.pipeline(id));
|
||||
}
|
||||
},
|
||||
initialPipelineId: pipelinesRoute.pipelineId,
|
||||
initialVersion: pipelinesRoute.version,
|
||||
initialStageKey: pipelinesRoute.stageKey,
|
||||
},
|
||||
initialPipelineId: pipelinesRoute.pipelineId,
|
||||
initialVersion: pipelinesRoute.version,
|
||||
initialStageKey: pipelinesRoute.stageKey,
|
||||
),
|
||||
),
|
||||
// The one place a field or artifact hit's selection can be resolved: the
|
||||
// run detail owns the recorded visit and Summary section.
|
||||
@@ -918,7 +934,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
),
|
||||
// Settings is a page of the Pipelines tab (its bar's gear), not a
|
||||
// tab; the shell shows it with Back to Pipelines.
|
||||
AppDestination.settings: (_) => SettingsScreen(
|
||||
AppDestination.settings: (context) => SettingsScreen(
|
||||
terminalLayout: _terminals.layout,
|
||||
client: _session.client,
|
||||
// A phone signs in at the web login; a browser has its own.
|
||||
@@ -933,6 +949,9 @@ class _PipelinesAppState extends State<PipelinesApp>
|
||||
notifications: _notifications,
|
||||
deliveryService: _deliveryService,
|
||||
deliveryServiceController: _deliveryController,
|
||||
// The Help and about row replays the first-run walkthrough. It only
|
||||
// shows it; the device's seen record is left alone.
|
||||
onShowWalkthrough: () => unawaited(showFirstRunWalkthrough(context)),
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,54 +1,11 @@
|
||||
part of 'screen.dart';
|
||||
|
||||
/// How many chats the visit remembers for Ctrl+Tab over a single pane.
|
||||
const chatRecentSessionLimit = 8;
|
||||
|
||||
/// Keys the Chat destination answers from anywhere in it, also while the
|
||||
/// sidebar or a toolbar owns focus: a bare `/` puts the keyboard in the open
|
||||
/// chat's composer, and Ctrl+Tab over a single pane returns to the chat shown
|
||||
/// before it (and back again). Both are handled before the focus tree, like
|
||||
/// the workspace's pane cycling, and leave other destinations, popups,
|
||||
/// dialogs and any focused text field alone.
|
||||
/// chat's composer. It is handled before the focus tree, like the workspace's
|
||||
/// pane cycling, and leaves other destinations, popups, dialogs and any
|
||||
/// focused text field alone.
|
||||
mixin _ChatScreenKeys on State<ChatScreen>, _ChatScreenWorkspace {
|
||||
void _open(JsonMap session, {bool focusComposer});
|
||||
|
||||
/// The chats this visit has shown in the workspace, most recent first; the
|
||||
/// active one leads it. In memory only: a reopened app starts afresh.
|
||||
final List<String> _recentSessions = [];
|
||||
|
||||
/// Moves the active pane's chat to the front. Called on every workspace
|
||||
/// change, including a restored layout, so the chat opened before the
|
||||
/// current one is always the second entry.
|
||||
@override
|
||||
void _noteRecentSession() {
|
||||
final id = _workspace.activePane?.sessionId;
|
||||
if (id == null || id.isEmpty || _recentSessions.firstOrNull == id) return;
|
||||
_recentSessions
|
||||
..remove(id)
|
||||
..insert(0, id);
|
||||
if (_recentSessions.length > chatRecentSessionLimit) {
|
||||
_recentSessions.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops [id]: a closed chat, or one `/new` moved to a fresh session.
|
||||
void _forgetRecentSession(String id) => _recentSessions.remove(id);
|
||||
|
||||
/// Drops every remembered chat: ids belong to one server.
|
||||
@override
|
||||
void _forgetRecentSessions() => _recentSessions.clear();
|
||||
|
||||
/// Over a single pane, opens the chat shown before the active one with its
|
||||
/// composer focused; false when this visit has shown no other chat.
|
||||
@override
|
||||
bool _toggleRecentChat() {
|
||||
final current = _workspace.activePane?.sessionId;
|
||||
final previous = _recentSessions.where((id) => id != current).firstOrNull;
|
||||
if (previous == null) return false;
|
||||
_open(_rowFor(previous) ?? {'id': previous}, focusComposer: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Whether the shown destination is Chat with no popup, dialog or other
|
||||
/// route over it, so a key pressed now is meant for the open chat.
|
||||
@override
|
||||
|
||||
@@ -5,9 +5,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
Map<String, JsonMap> get _openedSessions;
|
||||
ChatComposerFocusRequests get _composerFocus;
|
||||
bool _chatOwnsKeyboard();
|
||||
bool _toggleRecentChat();
|
||||
void _noteRecentSession();
|
||||
void _forgetRecentSessions();
|
||||
JsonMap? _rowFor(String id);
|
||||
void _back();
|
||||
bool get _pageOpen;
|
||||
@@ -130,7 +127,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
_workspaceBinding = null;
|
||||
if (_workspaceScope != null && scope != _workspaceScope) {
|
||||
_workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!);
|
||||
_forgetRecentSessions();
|
||||
_workspaceVisible = false;
|
||||
_usedWorkspace = true;
|
||||
_sidebarMode = ChatSidebarMode.expanded;
|
||||
@@ -152,29 +148,29 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
String? _publishedWorkspaceSession;
|
||||
String _workspaceSignature = '';
|
||||
|
||||
/// Ctrl+Tab cycles retained panes even when the sidebar or toolbar owns
|
||||
/// focus. Over a single pane it swaps in the chat shown before this one
|
||||
/// instead, and back again (see [_toggleRecentChat]). Command+Tab stays
|
||||
/// with the operating system's application switcher. While the app's
|
||||
/// terminal is shown, Ctrl+Tab moves between its tabs instead. While a
|
||||
/// floating chat window holds the keyboard, Ctrl+Tab cycles those windows
|
||||
/// (see [ChatWindows]).
|
||||
/// Ctrl+Tab cycles the floating chat windows while any is shown, from the
|
||||
/// tiling as well (see [ChatWindows]). With none shown it cycles the
|
||||
/// retained panes, even when the sidebar or toolbar owns focus, and over a
|
||||
/// single pane it does nothing: it never brings up a chat that is not
|
||||
/// visible in the tiling. Command+Tab stays with the operating system's
|
||||
/// application switcher. While the app's terminal is shown, Ctrl+Tab moves
|
||||
/// between its tabs instead. A floating window that is not a chat, or any
|
||||
/// other window holding the keyboard, keeps the key.
|
||||
bool _cycleChatKey(KeyEvent event) {
|
||||
final keyboard = HardwareKeyboard.instance;
|
||||
if (event is! KeyDownEvent ||
|
||||
TerminalScope.peek(context)?.claimsTabKeys == true ||
|
||||
keyboardWindow()?.entry.kind == chatWindowKind ||
|
||||
keyboardWindow() != null ||
|
||||
event.logicalKey != LogicalKeyboardKey.tab ||
|
||||
!keyboard.isControlPressed ||
|
||||
keyboard.isMetaPressed ||
|
||||
keyboard.isAltPressed ||
|
||||
!_workspaceVisible ||
|
||||
_workspace.paneCount == 0 ||
|
||||
!_chatOwnsKeyboard()) {
|
||||
return false;
|
||||
}
|
||||
if (widget.windows?.raiseTopFromTiling() ?? false) return true;
|
||||
if (!_workspaceVisible || _workspace.paneCount < 2) return false;
|
||||
final panes = _workspace.panes;
|
||||
if (panes.length == 1 && _toggleRecentChat()) return true;
|
||||
final active = panes.indexWhere(
|
||||
(pane) => pane.id == _workspace.activePaneId,
|
||||
);
|
||||
@@ -199,7 +195,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
|
||||
|
||||
void _workspaceChanged() {
|
||||
if (!mounted) return;
|
||||
_noteRecentSession();
|
||||
if (_workspaceBinding?.isRestoring == true) return;
|
||||
final signature =
|
||||
'${_workspace.activePaneId}:${_workspace.panes.map((p) => '${p.id}=${p.sessionId}').join(',')}';
|
||||
|
||||
@@ -1476,6 +1476,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
onPressed: _toggleFiles,
|
||||
materialIcon: _filesVisible ? Icons.folder : Icons.folder_outlined,
|
||||
),
|
||||
// A narrow layout's terminal button, beside Files; wide keeps the
|
||||
// shell bar's.
|
||||
?terminalChatBarAction(context),
|
||||
],
|
||||
moreActions: [
|
||||
?widget.sidebarControl,
|
||||
|
||||
@@ -159,7 +159,6 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
_workspace.open(initial);
|
||||
_workspaceVisible = true;
|
||||
_publishedWorkspaceSession = initial;
|
||||
_noteRecentSession();
|
||||
}
|
||||
_workspace.addListener(_workspaceChanged);
|
||||
_bindWorkspacePersistence();
|
||||
@@ -238,7 +237,6 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
void _openBySelection(JsonMap session) =>
|
||||
_open(session, focusComposer: chatSelectionFocusesComposer(session));
|
||||
|
||||
@override
|
||||
void _open(JsonMap session, {bool focusComposer = false}) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty) return;
|
||||
@@ -285,7 +283,6 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
/// A model switch accepted here in this visit moved with the chat.
|
||||
void _followNewSession(String previousId, JsonMap session, String notice) {
|
||||
_runtime.movedToSession(previousId, session, notice);
|
||||
_forgetRecentSession(previousId);
|
||||
_workspace.replaceSession(previousId, '${session['id'] ?? ''}');
|
||||
if (_workspace.paneCount == 0) _open(session);
|
||||
}
|
||||
@@ -293,7 +290,6 @@ class _ChatScreenState extends State<ChatScreen>
|
||||
/// `/close` was accepted: the conversation leaves, back to the list, which
|
||||
/// re-reads the closed row.
|
||||
void _closed(String sessionId) {
|
||||
_forgetRecentSession(sessionId);
|
||||
for (final pane
|
||||
in _workspace.panes
|
||||
.where((pane) => pane.sessionId == sessionId)
|
||||
|
||||
@@ -194,6 +194,7 @@ class ChatWindows {
|
||||
/// session list, which nothing else reads while the Chat destination is
|
||||
/// not built.
|
||||
void _rowsChanged() {
|
||||
_noteOpenOrder();
|
||||
final ids = {for (final w in windows) w.contentId};
|
||||
if (ids.isEmpty || !ready) return;
|
||||
final sessions = runtime.sessions;
|
||||
@@ -232,7 +233,7 @@ class ChatWindows {
|
||||
}
|
||||
|
||||
/// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the
|
||||
/// keyboard: the next (previous) visible chat window, in stacking order and
|
||||
/// keyboard: the next (previous) shown chat window, in open order and
|
||||
/// wrapping, comes to the top. The window host then gives it the keyboard,
|
||||
/// its composer. Left alone when another window or the tiling has the
|
||||
/// keyboard, when the terminal claims tab keys, or with one window.
|
||||
@@ -245,16 +246,47 @@ class ChatWindows {
|
||||
_terminalClaimsTabs()) {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
final target = chatWindowAfter(
|
||||
windows.where(manager.isVisible).toList(),
|
||||
scope.entry.id,
|
||||
step,
|
||||
);
|
||||
final target = chatWindowAfter(shownInOpenOrder(), scope.entry.id, step);
|
||||
if (target == null) return KeyEventResult.ignored;
|
||||
manager.raise(target.id);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
/// The ids of the chat windows in the order they were opened; a window
|
||||
/// restored from a saved layout keeps its saved place. Raising a window
|
||||
/// changes the stacking order, not this one, so the Ctrl+Tab cycle is
|
||||
/// stable. Kept in step on every change of the windows (see [_rowsChanged]).
|
||||
final List<String> _openOrder = [];
|
||||
|
||||
void _noteOpenOrder() {
|
||||
final ids = {for (final w in windows) w.id};
|
||||
_openOrder.removeWhere((id) => !ids.contains(id));
|
||||
for (final w in windows) {
|
||||
if (!_openOrder.contains(w.id)) _openOrder.add(w.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// The shown chat windows (not minimised, their group shown), in open order.
|
||||
List<WindowEntry> shownInOpenOrder() {
|
||||
_noteOpenOrder();
|
||||
final shown = {
|
||||
for (final w in windows)
|
||||
if (manager.isVisible(w)) w.id: w,
|
||||
};
|
||||
return [for (final id in _openOrder) ?shown[id]];
|
||||
}
|
||||
|
||||
/// Ctrl+Tab from the tiling or the chat list while chat windows are shown:
|
||||
/// the top-most shown chat window comes to the top and its composer takes
|
||||
/// the keyboard. False, doing nothing, when no chat window is shown.
|
||||
bool raiseTopFromTiling() {
|
||||
final top = windows.where(manager.isVisible).lastOrNull;
|
||||
if (top == null) return false;
|
||||
manager.raise(top.id);
|
||||
kind.focusContent(top);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool _terminalClaimsTabs() {
|
||||
final context = FocusManager.instance.primaryFocus?.context;
|
||||
return context != null &&
|
||||
|
||||
@@ -4,8 +4,10 @@ import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'host_platform_stub.dart' if (dart.library.io) 'host_platform_io.dart';
|
||||
import 'notification_service_events.dart';
|
||||
import 'notification_service_status.dart';
|
||||
|
||||
export 'notification_service_events.dart';
|
||||
export 'notification_service_status.dart';
|
||||
|
||||
/// The app's handle on Android background delivery: a native foreground
|
||||
@@ -35,6 +37,9 @@ abstract interface class NotificationServiceBridge {
|
||||
|
||||
/// Opens Android's "ignore battery optimisations" prompt.
|
||||
Future<bool> requestBatteryExemption();
|
||||
|
||||
/// The service's recent connection events, newest first (at most 50).
|
||||
Future<List<NotificationConnectionEvent>> connectionEvents();
|
||||
}
|
||||
|
||||
/// The bridge for this platform. One instance owns the channel's handler.
|
||||
@@ -104,6 +109,16 @@ class MethodChannelNotificationServiceBridge
|
||||
@override
|
||||
Future<bool> requestBatteryExemption() async =>
|
||||
await _channel.invokeMethod<bool>('requestBatteryExemption') ?? false;
|
||||
|
||||
@override
|
||||
Future<List<NotificationConnectionEvent>> connectionEvents() async {
|
||||
final reply = await _channel.invokeListMethod<Object?>('connectionEvents');
|
||||
return [
|
||||
for (final item in reply ?? const <Object?>[])
|
||||
if (item is Map<Object?, Object?>)
|
||||
NotificationConnectionEvent.fromMap(item),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Web, iOS and desktop: no background service; nothing is pretended.
|
||||
@@ -136,4 +151,8 @@ class UnsupportedNotificationServiceBridge
|
||||
|
||||
@override
|
||||
Future<bool> requestBatteryExemption() async => false;
|
||||
|
||||
@override
|
||||
Future<List<NotificationConnectionEvent>> connectionEvents() async =>
|
||||
const [];
|
||||
}
|
||||
|
||||
@@ -21,22 +21,52 @@ class NotificationServiceController extends ChangeNotifier {
|
||||
|
||||
late final StreamSubscription<NotificationServiceStatus> _changes;
|
||||
NotificationServiceStatus? _status;
|
||||
List<NotificationConnectionEvent> _events = const [];
|
||||
bool _busy = false;
|
||||
String _error = '';
|
||||
bool _disposed = false;
|
||||
|
||||
NotificationServiceStatus? get status => _status;
|
||||
|
||||
/// The service's connection log, newest first.
|
||||
List<NotificationConnectionEvent> get events => _events;
|
||||
bool get busy => _busy;
|
||||
String get error => _error;
|
||||
|
||||
bool _askedForExemption = false;
|
||||
|
||||
Future<void> load() => _run(bridge.status);
|
||||
|
||||
/// Opens Settings: reads the status and, when delivery is already on but the
|
||||
/// battery exemption is missing (existing users, upgrades), asks for it once
|
||||
/// per controller. The warning row stays if the prompt is declined.
|
||||
Future<void> open() async {
|
||||
await load();
|
||||
final current = _status;
|
||||
if (current != null &&
|
||||
current.enabled &&
|
||||
!current.batteryExempt &&
|
||||
!_askedForExemption) {
|
||||
_askedForExemption = true;
|
||||
await allowBackgroundDelivery();
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-reads after returning from a system screen (permission, battery).
|
||||
/// Never prompts again: a declined prompt is shown as the warning row.
|
||||
Future<void> refresh() => load();
|
||||
|
||||
/// Switching delivery on first asks for the battery exemption, so the
|
||||
/// service starts with the prompt answered: delivery should not pause while
|
||||
/// the phone is idle.
|
||||
Future<void> setEnabled(bool enabled) => _run(() async {
|
||||
if (enabled && _status?.notificationsAllowed == false) {
|
||||
await requestNotificationPermission?.call();
|
||||
if (enabled) {
|
||||
if (_status?.notificationsAllowed == false) {
|
||||
await requestNotificationPermission?.call();
|
||||
}
|
||||
if (_status?.batteryExempt == false) {
|
||||
await bridge.requestBatteryExemption();
|
||||
}
|
||||
}
|
||||
return bridge.setEnabled(enabled);
|
||||
});
|
||||
@@ -58,6 +88,7 @@ class NotificationServiceController extends ChangeNotifier {
|
||||
_notify();
|
||||
try {
|
||||
_status = await action();
|
||||
_events = await bridge.connectionEvents();
|
||||
} catch (error) {
|
||||
_error = 'Background delivery is unavailable: $error';
|
||||
} finally {
|
||||
@@ -69,6 +100,17 @@ class NotificationServiceController extends ChangeNotifier {
|
||||
void _apply(NotificationServiceStatus status) {
|
||||
_status = status;
|
||||
_notify();
|
||||
// The service logs its own transitions; re-read so the log stays current.
|
||||
unawaited(_refreshEvents());
|
||||
}
|
||||
|
||||
Future<void> _refreshEvents() async {
|
||||
try {
|
||||
_events = await bridge.connectionEvents();
|
||||
} catch (error) {
|
||||
_error = 'Background delivery is unavailable: $error';
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
/// One entry of the background service's connection log, as Settings shows
|
||||
/// it for diagnosis. The service keeps the newest events first.
|
||||
class NotificationConnectionEvent {
|
||||
const NotificationConnectionEvent({
|
||||
required this.time,
|
||||
required this.event,
|
||||
this.error,
|
||||
this.code,
|
||||
});
|
||||
|
||||
final DateTime time;
|
||||
|
||||
/// The service's wire name for what happened, e.g. `failed`.
|
||||
final String event;
|
||||
final String? error;
|
||||
|
||||
/// The HTTP status of a failed handshake, when there was one.
|
||||
final int? code;
|
||||
|
||||
factory NotificationConnectionEvent.fromMap(Map<Object?, Object?> map) =>
|
||||
NotificationConnectionEvent(
|
||||
time: DateTime.fromMillisecondsSinceEpoch(
|
||||
(map['time'] as num?)?.toInt() ?? 0,
|
||||
),
|
||||
event: map['event'] as String? ?? 'unknown',
|
||||
error: map['error'] as String?,
|
||||
code: (map['code'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
/// A short, plain name for the event.
|
||||
String get title => switch (event) {
|
||||
'connecting' => 'Opening socket',
|
||||
'connected' => 'Socket opened',
|
||||
'closed' => 'Socket closed',
|
||||
'failed' => 'Socket failed',
|
||||
'retry_scheduled' => 'Retry scheduled',
|
||||
'sign_in_required' => 'Session refused',
|
||||
'refused' => 'Subscribe refused',
|
||||
'network_available' => 'Network available',
|
||||
'network_lost' => 'Network lost',
|
||||
'invalid_endpoint' => 'Invalid address',
|
||||
'watchdog_restart' => 'Watchdog restart',
|
||||
'task_removed' => 'App closed from recents',
|
||||
'stopped' => 'Stopped',
|
||||
_ => event,
|
||||
};
|
||||
|
||||
/// The HTTP code and error text, when there are any.
|
||||
String? get detail {
|
||||
final parts = [
|
||||
if (code != null) 'HTTP $code',
|
||||
if (error != null && error!.isNotEmpty) error!,
|
||||
];
|
||||
return parts.isEmpty ? null : parts.join(' · ');
|
||||
}
|
||||
|
||||
/// Local time as `MM-DD HH:MM:SS`.
|
||||
String get timeLabel {
|
||||
String two(int value) => value.toString().padLeft(2, '0');
|
||||
final local = time.toLocal();
|
||||
return '${two(local.month)}-${two(local.day)} '
|
||||
'${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@ enum DeliveryState {
|
||||
connecting('connecting'),
|
||||
connected('connected'),
|
||||
reconnecting('reconnecting'),
|
||||
waitingForNetwork('waiting_for_network');
|
||||
waitingForNetwork('waiting_for_network'),
|
||||
signInRequired('sign_in_required');
|
||||
|
||||
const DeliveryState(this.wire);
|
||||
|
||||
@@ -59,6 +60,8 @@ class NotificationServiceStatus {
|
||||
DeliveryState.connecting => 'Connecting…',
|
||||
DeliveryState.reconnecting => 'Reconnecting…',
|
||||
DeliveryState.waitingForNetwork => 'Waiting for a network',
|
||||
DeliveryState.signInRequired =>
|
||||
'Sign in to Pipelines again to keep notifications',
|
||||
DeliveryState.unconfigured => 'Starts after the app connects to a server',
|
||||
DeliveryState.off => enabled ? 'Not running' : 'Off',
|
||||
};
|
||||
|
||||
@@ -16,11 +16,24 @@ const deviceDeliveryNote =
|
||||
'quiet "Pipelines is connected" notification while it runs.';
|
||||
const deviceDeliveryBatteryLabel = 'Allow background delivery';
|
||||
const deviceDeliveryNotificationsLabel = 'Allow notifications';
|
||||
const deviceDeliveryWarningTitle = 'Delivery can pause while idle';
|
||||
const deviceDeliveryWarningText =
|
||||
'Android may pause Pipelines in the background, so notifications can '
|
||||
'arrive late. Allow background delivery above.';
|
||||
const deviceDeliverySamsungNote =
|
||||
'Samsung phones: also add Pipelines under Settings › Battery › '
|
||||
'Background usage limits › Never sleeping apps.';
|
||||
const deviceDeliveryLogTitle = 'Connection log';
|
||||
const deviceDeliveryLogEmpty = 'No connection events yet';
|
||||
|
||||
abstract final class DeviceDeliveryKeys {
|
||||
static const toggle = ValueKey<String>('settings.deviceDelivery.toggle');
|
||||
static const status = ValueKey<String>('settings.deviceDelivery.status');
|
||||
static const battery = ValueKey<String>('settings.deviceDelivery.battery');
|
||||
static const batteryWarning = ValueKey<String>(
|
||||
'settings.deviceDelivery.batteryWarning',
|
||||
);
|
||||
static const log = ValueKey<String>('settings.deviceDelivery.log');
|
||||
static const permission = ValueKey<String>(
|
||||
'settings.deviceDelivery.permission',
|
||||
);
|
||||
@@ -66,7 +79,7 @@ class _SettingsDeviceDeliverySectionState
|
||||
void initState() {
|
||||
super.initState();
|
||||
_lifecycle;
|
||||
unawaited(_controller.load());
|
||||
unawaited(_controller.open());
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -136,7 +149,45 @@ class _SettingsDeviceDeliverySectionState
|
||||
enabled: !status.batteryExempt && !_controller.busy,
|
||||
onTap: () => unawaited(_controller.allowBackgroundDelivery()),
|
||||
),
|
||||
if (status != null && enabled && !status.batteryExempt)
|
||||
SettingsRow(
|
||||
key: DeviceDeliveryKeys.batteryWarning,
|
||||
leading: Icon(
|
||||
Icons.warning_amber_rounded,
|
||||
color: settingsErrorColor(context),
|
||||
),
|
||||
title: const Text(deviceDeliveryWarningTitle),
|
||||
subtitle: Text(
|
||||
'$deviceDeliveryWarningText\n$deviceDeliverySamsungNote',
|
||||
),
|
||||
),
|
||||
if (status != null)
|
||||
ExpansionTile(
|
||||
key: DeviceDeliveryKeys.log,
|
||||
title: const Text(deviceDeliveryLogTitle),
|
||||
children: _logRows(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _logRows() {
|
||||
final events = _controller.events;
|
||||
if (events.isEmpty) {
|
||||
return const <Widget>[ListTile(title: Text(deviceDeliveryLogEmpty))];
|
||||
}
|
||||
return [
|
||||
for (final event in events)
|
||||
ListTile(
|
||||
dense: true,
|
||||
title: Text(event.title),
|
||||
subtitle: Text(
|
||||
[
|
||||
event.timeLabel,
|
||||
if (event.detail != null) event.detail!,
|
||||
].join('\n'),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,15 +184,26 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final content = SafeArea(
|
||||
bottom: false,
|
||||
child: SettingsSearchPage(sections: _pageSections()),
|
||||
);
|
||||
if (widget.embedded) return content;
|
||||
final page = SettingsSearchPage(sections: _pageSections());
|
||||
if (widget.embedded) {
|
||||
// The shell's floating tab bar sits over this body, and the body reads
|
||||
// the bar's height as its bottom padding. The page's rows are controls
|
||||
// and text, so they stop at the bar's top edge instead of scrolling
|
||||
// under the glass where they cannot be read. The reserved space is
|
||||
// removed from the page's own inset so it is not counted twice.
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.paddingOf(context).bottom),
|
||||
child: MediaQuery.removePadding(
|
||||
context: context,
|
||||
removeBottom: true,
|
||||
child: SafeArea(bottom: false, child: page),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: const SegmentedBar(title: 'Settings'),
|
||||
body: content,
|
||||
body: SafeArea(bottom: false, child: page),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@ import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../shell/list_detail_policy.dart';
|
||||
import '../../ui/adaptive/segmented_bar_overflow.dart';
|
||||
import '../chat/ui/sessions/chat_adaptive.dart';
|
||||
import 'terminal_hub.dart';
|
||||
import 'terminal_scope.dart';
|
||||
import 'terminal_toggle_button.dart';
|
||||
|
||||
/// The first time the terminal is shown in an app run it starts one
|
||||
/// terminal, as New terminal does (it shows the machine's login prompt),
|
||||
@@ -49,6 +52,23 @@ void openInTerminal(
|
||||
);
|
||||
}
|
||||
|
||||
/// The open chat's own bar button that shows or hides the terminal, on a
|
||||
/// narrow layout. It is a plain [ChatBarAction] like Files and More, so it
|
||||
/// matches them in style, size and states. A wide layout returns null: its
|
||||
/// shell bar keeps the terminal button over the list column. Null too with
|
||||
/// no terminal surface.
|
||||
Widget? terminalChatBarAction(BuildContext context) {
|
||||
if (showsListBesideDetail(context)) return null;
|
||||
final actions = TerminalScope.maybeOf(context);
|
||||
if (actions == null) return null;
|
||||
return ChatBarAction(
|
||||
label: TerminalToggleButton.label,
|
||||
identifier: 'chat-terminal-toggle',
|
||||
onPressed: actions.toggle,
|
||||
materialIcon: Icons.terminal,
|
||||
);
|
||||
}
|
||||
|
||||
/// The chat actions menu's "Open in terminal" for the chat's folder, or
|
||||
/// null when the app has no terminal surface or the chat no folder.
|
||||
Widget? terminalOpenMenuAction(
|
||||
|
||||
@@ -6,6 +6,9 @@ import 'terminal_shortcuts.dart';
|
||||
|
||||
/// The shell bar's Terminal button: shows or hides the terminal (also
|
||||
/// Alt+T, Ctrl+T, Cmd+T and Ctrl+`, where the platform delivers them).
|
||||
///
|
||||
/// It is a plain bar IconButton like Files and More: no selected tint, so
|
||||
/// its shown state is announced to assistive technology only.
|
||||
class TerminalToggleButton extends StatelessWidget {
|
||||
const TerminalToggleButton({super.key, required this.layout});
|
||||
|
||||
@@ -22,12 +25,14 @@ class TerminalToggleButton extends StatelessWidget {
|
||||
listenable: layout,
|
||||
builder: (context, _) {
|
||||
final shown = layout.visible;
|
||||
return IconButton(
|
||||
key: const ValueKey('shell.terminal'),
|
||||
tooltip: label,
|
||||
isSelected: shown,
|
||||
onPressed: actions.toggle,
|
||||
icon: const Icon(Icons.terminal),
|
||||
return Semantics(
|
||||
toggled: shown,
|
||||
child: IconButton(
|
||||
key: const ValueKey('shell.terminal'),
|
||||
tooltip: label,
|
||||
onPressed: actions.toggle,
|
||||
icon: const Icon(Icons.terminal),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../ui/adaptive/app_popups.dart';
|
||||
import 'walkthrough_harness_command.dart';
|
||||
import 'walkthrough_steps.dart';
|
||||
|
||||
/// Opens the walkthrough as a Material details sheet on phones and a dialog on
|
||||
/// wide windows. [onClosed] runs once however it closes (Skip, Done, the close
|
||||
/// button or a tap outside), so the caller can record it as seen.
|
||||
Future<void> showFirstRunWalkthrough(
|
||||
BuildContext context, {
|
||||
Future<void> Function()? onClosed,
|
||||
}) async {
|
||||
await showAppDetails<void>(
|
||||
context,
|
||||
maxWidth: 560,
|
||||
builder: (sheet) =>
|
||||
FirstRunWalkthrough(onClose: () => Navigator.of(sheet).pop()),
|
||||
);
|
||||
await onClosed?.call();
|
||||
}
|
||||
|
||||
/// The four-page stepper: Back and Next between pages, Skip on every page and
|
||||
/// Done on the last. Every control is a standard Material button; the layout
|
||||
/// wraps rather than clipping at large text scales.
|
||||
class FirstRunWalkthrough extends StatefulWidget {
|
||||
const FirstRunWalkthrough({
|
||||
super.key,
|
||||
required this.onClose,
|
||||
this.steps = walkthroughSteps,
|
||||
});
|
||||
|
||||
/// Called by Skip, Done and the close button.
|
||||
final VoidCallback onClose;
|
||||
final List<WalkthroughStep> steps;
|
||||
|
||||
@override
|
||||
State<FirstRunWalkthrough> createState() => _FirstRunWalkthroughState();
|
||||
}
|
||||
|
||||
class _FirstRunWalkthroughState extends State<FirstRunWalkthrough> {
|
||||
int _index = 0;
|
||||
|
||||
bool get _last => _index == widget.steps.length - 1;
|
||||
|
||||
void _back() => setState(() => _index = _index > 0 ? _index - 1 : 0);
|
||||
|
||||
void _next() => setState(() => _index = _last ? _index : _index + 1);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final step = widget.steps[_index];
|
||||
final theme = Theme.of(context);
|
||||
final content = Semantics(
|
||||
scopesRoute: true,
|
||||
namesRoute: true,
|
||||
explicitChildNodes: true,
|
||||
label: 'Pipelines walkthrough',
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 8, 24, 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'Step ${_index + 1} of ${widget.steps.length}',
|
||||
key: const ValueKey<String>('walkthrough.progress'),
|
||||
style: theme.textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
LinearProgressIndicator(value: (_index + 1) / widget.steps.length),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Icon(step.icon, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
step.title,
|
||||
key: ValueKey<String>('walkthrough.title.$_index'),
|
||||
style: theme.textTheme.headlineSmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(step.body, style: theme.textTheme.bodyLarge),
|
||||
for (final point in step.points) ...<Widget>[
|
||||
const SizedBox(height: 8),
|
||||
_Point(text: point),
|
||||
],
|
||||
if (step.showsHarnessCommand) ...<Widget>[
|
||||
const SizedBox(height: 16),
|
||||
const WalkthroughHarnessCommand(),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
_Footer(
|
||||
last: _last,
|
||||
canGoBack: _index > 0,
|
||||
onBack: _back,
|
||||
onNext: _last ? widget.onClose : _next,
|
||||
onSkip: widget.onClose,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
// A wide window wraps the sheet's content in its own scroll view; a phone
|
||||
// sheet does not, so the page scrolls here at large text scales.
|
||||
return usesDesktopPopups(context)
|
||||
? content
|
||||
: SingleChildScrollView(child: content);
|
||||
}
|
||||
}
|
||||
|
||||
class _Point extends StatelessWidget {
|
||||
const _Point({required this.text});
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 2),
|
||||
child: Icon(Icons.circle, size: 6),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(text, style: Theme.of(context).textTheme.bodyMedium),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _Footer extends StatelessWidget {
|
||||
const _Footer({
|
||||
required this.last,
|
||||
required this.canGoBack,
|
||||
required this.onBack,
|
||||
required this.onNext,
|
||||
required this.onSkip,
|
||||
});
|
||||
|
||||
final bool last;
|
||||
final bool canGoBack;
|
||||
final VoidCallback onBack;
|
||||
final VoidCallback onNext;
|
||||
final VoidCallback onSkip;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: <Widget>[
|
||||
TextButton(
|
||||
key: const ValueKey<String>('walkthrough.skip'),
|
||||
onPressed: onSkip,
|
||||
child: const Text('Skip'),
|
||||
),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: <Widget>[
|
||||
TextButton(
|
||||
key: const ValueKey<String>('walkthrough.back'),
|
||||
onPressed: canGoBack ? onBack : null,
|
||||
child: const Text('Back'),
|
||||
),
|
||||
FilledButton(
|
||||
key: const ValueKey<String>('walkthrough.next'),
|
||||
onPressed: onNext,
|
||||
child: Text(last ? 'Done' : 'Next'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'first_run_walkthrough.dart';
|
||||
import 'walkthrough_store.dart';
|
||||
|
||||
/// Reports whether the server has no pipelines, runs or chats yet. Returns null
|
||||
/// when any of the three lists cannot be read, so an unreadable server never
|
||||
/// triggers the walkthrough.
|
||||
Future<bool?> serverHasNoWorkYet(ApiGateway? gateway) async {
|
||||
if (gateway == null) return null;
|
||||
try {
|
||||
final replies = await Future.wait(<Future<JsonMap>>[
|
||||
gateway.call('list_pipelines', {'include_archived': true}),
|
||||
gateway.call('list_runs'),
|
||||
gateway.call('chat_sessions'),
|
||||
]);
|
||||
final lists = <Object?>[
|
||||
replies[0]['pipelines'],
|
||||
replies[1]['runs'],
|
||||
replies[2]['chat_sessions'],
|
||||
];
|
||||
if (lists.any((list) => list is! List)) return null;
|
||||
return lists.every((list) => (list as List).isEmpty);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Offers the walkthrough from the Pipelines page, which is the first screen a
|
||||
/// new user sees. It is offered when:
|
||||
///
|
||||
/// * the device has not finished or skipped it yet (first launch, once); or
|
||||
/// * the device already has, and the connected server has no pipelines, runs
|
||||
/// or chats, and that server has not been offered it before.
|
||||
///
|
||||
/// The server check needs a connected session. While disconnected it waits, and
|
||||
/// it runs again on each new connection until the server answers. A check that
|
||||
/// cannot read the server leaves the gate open to retry; a decided check (the
|
||||
/// walkthrough shown, or the server has work) ends it for this mount.
|
||||
///
|
||||
/// Nothing is shown while the store cannot be read, because an unavailable
|
||||
/// store reports "seen". The check runs only while [enabled] (the Pipelines tab
|
||||
/// is the one showing).
|
||||
class FirstRunWalkthroughGate extends StatefulWidget {
|
||||
const FirstRunWalkthroughGate({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.store,
|
||||
required this.enabled,
|
||||
required this.serverScope,
|
||||
required this.connection,
|
||||
required this.connected,
|
||||
this.gateway,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final WalkthroughStore store;
|
||||
|
||||
/// Whether the Pipelines page is the one showing.
|
||||
final bool enabled;
|
||||
|
||||
/// The connected server's scope, recorded when the walkthrough is offered.
|
||||
final String serverScope;
|
||||
|
||||
/// Notifies when the connection may have changed; the gate re-reads
|
||||
/// [connected] on each notification.
|
||||
final Listenable connection;
|
||||
|
||||
/// Whether the server session is connected right now.
|
||||
final bool Function() connected;
|
||||
|
||||
/// The connected server's gateway, used for the empty-server check.
|
||||
final ApiGateway? gateway;
|
||||
|
||||
@override
|
||||
State<FirstRunWalkthroughGate> createState() =>
|
||||
_FirstRunWalkthroughGateState();
|
||||
}
|
||||
|
||||
class _FirstRunWalkthroughGateState extends State<FirstRunWalkthroughGate> {
|
||||
/// The offer is decided for this mount: shown, or nothing left to offer.
|
||||
bool _decided = false;
|
||||
|
||||
/// An offer is in flight.
|
||||
bool _running = false;
|
||||
|
||||
/// A new connection arrived while an offer was in flight.
|
||||
bool _connectedAgain = false;
|
||||
late bool _wasConnected;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_wasConnected = widget.connected();
|
||||
widget.connection.addListener(_onConnectionChanged);
|
||||
_scheduleIfEnabled();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(FirstRunWalkthroughGate oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.connection != widget.connection) {
|
||||
oldWidget.connection.removeListener(_onConnectionChanged);
|
||||
widget.connection.addListener(_onConnectionChanged);
|
||||
}
|
||||
_scheduleIfEnabled();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.connection.removeListener(_onConnectionChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Acts only on a disconnected-to-connected transition, so frequent session
|
||||
/// notifications while connected never repeat the server check.
|
||||
void _onConnectionChanged() {
|
||||
final connected = widget.connected();
|
||||
final became = connected && !_wasConnected;
|
||||
_wasConnected = connected;
|
||||
if (!became || _decided) return;
|
||||
if (_running) {
|
||||
_connectedAgain = true;
|
||||
return;
|
||||
}
|
||||
_scheduleIfEnabled();
|
||||
}
|
||||
|
||||
void _scheduleIfEnabled() {
|
||||
if (_decided || _running || !widget.enabled) return;
|
||||
_running = true;
|
||||
// A connection can arrive between frames; the post-frame callback needs a
|
||||
// frame, so request one explicitly.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!_active) {
|
||||
// Pipelines is hidden (or the gate is gone): release the flag so a
|
||||
// later enable reschedules the offer through didUpdateWidget.
|
||||
_running = false;
|
||||
return;
|
||||
}
|
||||
unawaited(_runOffer());
|
||||
});
|
||||
WidgetsBinding.instance.ensureVisualUpdate();
|
||||
}
|
||||
|
||||
/// The gate may offer only while mounted and while the Pipelines page is the
|
||||
/// one showing. Checked after every await and before every show.
|
||||
bool get _active => mounted && widget.enabled;
|
||||
|
||||
Future<void> _runOffer() async {
|
||||
try {
|
||||
await _offer();
|
||||
} finally {
|
||||
_running = false;
|
||||
final again = _connectedAgain;
|
||||
_connectedAgain = false;
|
||||
if (again && !_decided) _scheduleIfEnabled();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _offer() async {
|
||||
final seen = await widget.store.isSeen();
|
||||
if (!_active) return;
|
||||
if (!seen) {
|
||||
_decided = true;
|
||||
await _showIfActive();
|
||||
return;
|
||||
}
|
||||
if (await widget.store.wasOffered(widget.serverScope)) {
|
||||
if (!_active) return;
|
||||
_decided = true;
|
||||
return;
|
||||
}
|
||||
// Wait for a connection; the connection listener runs the check again.
|
||||
if (!widget.connected()) return;
|
||||
final empty = await serverHasNoWorkYet(widget.gateway);
|
||||
if (!_active) return;
|
||||
// Unreadable: stay open so the next connection retries the check.
|
||||
if (empty == null) return;
|
||||
_decided = true;
|
||||
if (!empty) return;
|
||||
await widget.store.markOffered(widget.serverScope);
|
||||
await _showIfActive();
|
||||
}
|
||||
|
||||
Future<void> _showIfActive() async {
|
||||
if (!_active) return;
|
||||
await _show();
|
||||
}
|
||||
|
||||
Future<void> _show() async {
|
||||
await showFirstRunWalkthrough(context, onClosed: widget.store.markSeen);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => widget.child;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'walkthrough_steps.dart';
|
||||
|
||||
/// The harness page's command: an agent picker and the one command it selects,
|
||||
/// with a single copy button for that command.
|
||||
class WalkthroughHarnessCommand extends StatefulWidget {
|
||||
const WalkthroughHarnessCommand({super.key});
|
||||
|
||||
@override
|
||||
State<WalkthroughHarnessCommand> createState() =>
|
||||
_WalkthroughHarnessCommandState();
|
||||
}
|
||||
|
||||
class _WalkthroughHarnessCommandState extends State<WalkthroughHarnessCommand> {
|
||||
String _agent = harnessAgents.first;
|
||||
bool _copied = false;
|
||||
|
||||
Future<void> _copy(String command) async {
|
||||
try {
|
||||
await Clipboard.setData(ClipboardData(text: command));
|
||||
} catch (_) {
|
||||
// The command stays selectable, so a failed copy never claims success.
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() => _copied = true);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final command = harnessSetupCommand(_agent);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
Text('Agent', style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: <Widget>[
|
||||
for (final agent in harnessAgents)
|
||||
ChoiceChip(
|
||||
key: ValueKey<String>('walkthrough.agent.$agent'),
|
||||
label: Text(agent),
|
||||
selected: agent == _agent,
|
||||
onSelected: (_) => setState(() {
|
||||
_agent = agent;
|
||||
_copied = false;
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: scheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 12, right: 4),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: SelectableText(
|
||||
command,
|
||||
key: const ValueKey<String>('walkthrough.command'),
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const ValueKey<String>('walkthrough.copy'),
|
||||
tooltip: _copied ? 'Command copied' : 'Copy command',
|
||||
onPressed: () => _copy(command),
|
||||
icon: Icon(_copied ? Icons.check : Icons.copy_outlined),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// One page of the first-run walkthrough. Pure content: no widgets, so the
|
||||
/// copy can be checked without pumping a tree.
|
||||
class WalkthroughStep {
|
||||
const WalkthroughStep({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.body,
|
||||
this.points = const <String>[],
|
||||
this.showsHarnessCommand = false,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String body;
|
||||
|
||||
/// Short labelled facts shown under the body, one per line.
|
||||
final List<String> points;
|
||||
|
||||
/// Whether this page shows the harness setup command picker.
|
||||
final bool showsHarnessCommand;
|
||||
}
|
||||
|
||||
/// The agents `pipelines harness setup` accepts, in the order they are offered.
|
||||
const harnessAgents = <String>['claude', 'codex', 'opencode', 'pi'];
|
||||
|
||||
/// The command for [agent], exactly as a terminal should run it.
|
||||
String harnessSetupCommand(String agent) => 'pipelines harness setup $agent';
|
||||
|
||||
/// The four walkthrough pages, in order.
|
||||
const walkthroughSteps = <WalkthroughStep>[
|
||||
WalkthroughStep(
|
||||
icon: Icons.hub_outlined,
|
||||
title: 'Welcome to Pipelines',
|
||||
body:
|
||||
'Pipelines runs reusable AI workflows and holds chats with coding '
|
||||
'agents. Both live on your server, so start by connecting this app '
|
||||
'to it.',
|
||||
points: <String>[
|
||||
'Pipelines: workflows you define once and run again.',
|
||||
'Chats: conversations with coding agents on the server.',
|
||||
'Connect: open Settings, then Connection, enter the Server URL and '
|
||||
'choose Connect.',
|
||||
],
|
||||
),
|
||||
WalkthroughStep(
|
||||
icon: Icons.build_circle_outlined,
|
||||
title: 'Set up an agent harness',
|
||||
body:
|
||||
'A harness lets Pipelines drive a coding agent. Choose the agent you '
|
||||
'use, then run its setup command in a terminal.',
|
||||
showsHarnessCommand: true,
|
||||
),
|
||||
WalkthroughStep(
|
||||
icon: Icons.play_circle_outline,
|
||||
title: 'Start a run',
|
||||
body:
|
||||
'Pipelines shows your workflows. Runs shows every run with its '
|
||||
'progress and results.',
|
||||
points: <String>[
|
||||
'Pipelines tab: open a workflow and fill in its inputs.',
|
||||
'Runs tab: follow a run as it works, then read what it produced.',
|
||||
'Choose Run on a workflow to start one.',
|
||||
],
|
||||
),
|
||||
WalkthroughStep(
|
||||
icon: Icons.forum_outlined,
|
||||
title: 'Chat with an agent',
|
||||
body:
|
||||
'The Chat tab lists your conversations. Open one to read the thread '
|
||||
'and reply.',
|
||||
points: <String>[
|
||||
'Float: pop a chat into its own window while you work elsewhere.',
|
||||
'Terminal: open a terminal beside the Chat tab for direct commands.',
|
||||
'New chat starts a conversation with an agent.',
|
||||
],
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,118 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// The device-level key for "the first-run walkthrough was finished or skipped".
|
||||
/// It is per device, not per server, so a new server never repeats it.
|
||||
const String walkthroughSeenKey = 'pipelines.next.firstRunWalkthrough.v1';
|
||||
|
||||
/// The key listing the server scopes that were already offered the walkthrough
|
||||
/// because they had no pipelines, runs or chats yet.
|
||||
const String walkthroughOfferedKey = 'pipelines.next.walkthroughOffered.v1';
|
||||
|
||||
/// The persistence seam for the walkthrough. A store that cannot be read or
|
||||
/// written reports "seen" and "offered", so an unavailable store never nags.
|
||||
abstract interface class WalkthroughStore {
|
||||
Future<bool> isSeen();
|
||||
|
||||
Future<void> markSeen();
|
||||
|
||||
Future<bool> wasOffered(String serverScope);
|
||||
|
||||
Future<void> markOffered(String serverScope);
|
||||
}
|
||||
|
||||
Future<SharedPreferences?> _openPreferences() async {
|
||||
try {
|
||||
return await SharedPreferences.getInstance();
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// `shared_preferences`-backed storage under the `pipelines.next` keys.
|
||||
///
|
||||
/// [open] is the seam for an unavailable platform store (tests pass one that
|
||||
/// yields null); production opens the real preferences.
|
||||
class SharedPreferencesWalkthroughStore implements WalkthroughStore {
|
||||
const SharedPreferencesWalkthroughStore({this.open = _openPreferences});
|
||||
|
||||
final Future<SharedPreferences?> Function() open;
|
||||
|
||||
Future<SharedPreferences?> _preferences() => open();
|
||||
|
||||
@override
|
||||
Future<bool> isSeen() async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return true;
|
||||
try {
|
||||
return preferences.getBool(walkthroughSeenKey) ?? false;
|
||||
} catch (_) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> markSeen() async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return;
|
||||
try {
|
||||
await preferences.setBool(walkthroughSeenKey, true);
|
||||
} catch (_) {
|
||||
// Nothing to report: the walkthrough is still dismissed for this run.
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> wasOffered(String serverScope) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return true;
|
||||
try {
|
||||
final offered = preferences.getStringList(walkthroughOfferedKey);
|
||||
return offered?.contains(serverScope) ?? false;
|
||||
} catch (_) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> markOffered(String serverScope) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return;
|
||||
try {
|
||||
final offered = <String>{
|
||||
...?preferences.getStringList(walkthroughOfferedKey),
|
||||
serverScope,
|
||||
};
|
||||
await preferences.setStringList(walkthroughOfferedKey, offered.toList());
|
||||
} catch (_) {
|
||||
// A failed write only means the offer may show again later.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for tests and previews. It never touches the platform
|
||||
/// store, so a fixture cannot mark a real device as seen.
|
||||
class MemoryWalkthroughStore implements WalkthroughStore {
|
||||
MemoryWalkthroughStore({this.seen = false, Set<String>? offered})
|
||||
: _offered = {...?offered};
|
||||
|
||||
/// Whether the walkthrough is marked seen.
|
||||
bool seen;
|
||||
final Set<String> _offered;
|
||||
|
||||
/// The server scopes already offered the walkthrough.
|
||||
Set<String> get offered => Set.unmodifiable(_offered);
|
||||
|
||||
@override
|
||||
Future<bool> isSeen() async => seen;
|
||||
|
||||
@override
|
||||
Future<void> markSeen() async => seen = true;
|
||||
|
||||
@override
|
||||
Future<bool> wasOffered(String serverScope) async =>
|
||||
_offered.contains(serverScope);
|
||||
|
||||
@override
|
||||
Future<void> markOffered(String serverScope) async =>
|
||||
_offered.add(serverScope);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
# Android background delivery: survive Doze, sign-in, battery, diagnosis
|
||||
|
||||
Stage 01-implement, run 20261112-0157. Source only; not committed, not installed.
|
||||
|
||||
## What changed
|
||||
|
||||
- **Reconnects are alarms, not handler delays.** `ReconnectAlarms` schedules
|
||||
`setExactAndAllowWhileIdle` when `canScheduleExactAlarms()`, otherwise
|
||||
`setAndAllowWhileIdle`. The alarm PendingIntent is a foreground-service intent
|
||||
to `NotificationService` (`ACTION_RECONNECT`). The `Handler.postDelayed`
|
||||
reconnect is gone.
|
||||
- **Watchdog.** `NotificationWatchdog` (JobScheduler, periodic 15 min,
|
||||
persisted) restarts the service when delivery is enabled and the socket is
|
||||
down with no reconnect pending. It does not restart while signed out or
|
||||
waiting for a network. Also scheduled by `NotificationService.start`.
|
||||
- **Connect wake lock.** `ConnectWakeLock` holds a partial wake lock for 30 s
|
||||
from `connect()` until the socket opens or fails.
|
||||
- **Swipe away.** `onTaskRemoved` logs and queues a watchdog check 2 s later.
|
||||
- **Battery exemption.** `SettingsDeviceDeliverySection` shows a persistent
|
||||
warning row while delivery is on and the exemption is missing, with the
|
||||
Samsung "Never sleeping apps" note. `setEnabled(true)` requests the
|
||||
exemption before starting the service. Opening Settings with delivery already
|
||||
on and the exemption missing asks once per open (`NotificationServiceController.open`);
|
||||
resume refreshes never ask again.
|
||||
- **HTTP 401/403.** The retry loop stops, status becomes `sign_in_required`,
|
||||
and a "Sign in to Pipelines again to keep notifications" notice is posted
|
||||
(channel `pipelines.account`, id 2). `configure` with a fresh cookie restarts
|
||||
the service.
|
||||
- **Connection log.** `ConnectionLog` keeps the last 50 events (time, event,
|
||||
error, HTTP code) in the service preferences. The channel method
|
||||
`connectionEvents` returns them. Settings shows them in an expandable
|
||||
"Connection log" row.
|
||||
|
||||
## Files
|
||||
|
||||
- Kotlin (new): `ReconnectPolicy.kt`, `ReconnectAlarms.kt`,
|
||||
`NotificationWatchdog.kt`, `ConnectWakeLock.kt`, `ConnectionLog.kt`
|
||||
- Kotlin (changed): `NotificationService.kt`, `NotificationPresenter.kt`,
|
||||
`NotificationServiceChannel.kt`, `ServiceSettings.kt`, `AndroidManifest.xml`
|
||||
(WAKE_LOCK, SCHEDULE_EXACT_ALARM, watchdog service)
|
||||
- Kotlin tests (new): `ConnectionLogTest.kt` (5), `ReconnectPolicyTest.kt` (3)
|
||||
- Dart (new): `lib/features/notification_service/notification_service_events.dart`
|
||||
- Dart (changed): `notification_service_bridge.dart`,
|
||||
`notification_service_controller.dart`, `notification_service_status.dart`,
|
||||
`lib/features/settings/settings_device_delivery_section.dart`
|
||||
- Dart tests (changed): `test/features/settings/settings_device_delivery_section_test.dart`
|
||||
(+8 cases), `test/features/notification_service/notification_service_bridge_test.dart`
|
||||
(+3 cases), `test/features/notification_service/fake_notification_service.dart`
|
||||
|
||||
## Focused results
|
||||
|
||||
- Kotlin: `gradle :app:testDebugUnitTest --tests 'net.awan.pipelines_app.notify.*'`
|
||||
BUILD SUCCESSFUL. 28 of 28 pass: ConnectionLogTest 5, ReconnectPolicyTest 3,
|
||||
DeliveryLedgerTest 8, NotificationProtocolTest 12. Includes main-source compile.
|
||||
- Flutter: `tool/memwatch/full.sh` on the four files below, PASS 35 passed,
|
||||
0 failed (run twice, once after formatting):
|
||||
- test/features/settings/settings_device_delivery_section_test.dart
|
||||
- test/features/notification_service/notification_service_bridge_test.dart
|
||||
- test/features/notification_service/notification_service_handoff_test.dart
|
||||
- test/features/attention/notify/notification_delivery_test.dart
|
||||
- `tool/analyze.sh`: clean (run twice).
|
||||
|
||||
## Affected UI states (for ui-review, not captured here)
|
||||
|
||||
- Delivery on, exemption missing: warning row visible with Samsung note.
|
||||
- Delivery on, exemption granted: warning row gone; battery row says "Allowed".
|
||||
- Delivery off: no battery row, no warning row.
|
||||
- Status "Sign in to Pipelines again to keep notifications".
|
||||
- Connection log collapsed, expanded with events, expanded empty
|
||||
("No connection events yet"). Expansion needs an interactive check.
|
||||
|
||||
## Limitations and decisions
|
||||
|
||||
- **Not verified on a device.** Doze timing, alarm delivery, the
|
||||
foreground-start exemption from alarms and the watchdog job, the swipe
|
||||
restart, and the sign-in notice were not run. The Fold was not touched.
|
||||
- **Exact alarms.** SCHEDULE_EXACT_ALARM is declared, but the app does not
|
||||
send the user to grant it. Without the grant, reconnects use
|
||||
idle-tolerant alarms.
|
||||
- **Upgrade users are prompted when Settings opens, not at app start.** The
|
||||
exemption is requested on switch-on, and on opening Settings while delivery
|
||||
is on and the exemption is missing. The prompt is not fired from app start
|
||||
because the section is the only place with the request context. A user who
|
||||
declines is prompted again the next time Settings opens, then sees the
|
||||
warning row. Users who never open Settings are not prompted.
|
||||
- **JobScheduler is deferred in Doze**, so the watchdog is a backstop; the
|
||||
alarms are the primary path.
|
||||
- NotificationService.kt is 387 lines (aim is under 250; it was 293 before).
|
||||
The reconnect alarms, watchdog, wake lock and log are in separate files,
|
||||
but the socket state machine remains in the service; splitting it further is
|
||||
a follow-up.
|
||||
@@ -30,14 +30,25 @@ every destination and come back at app start without Chat being opened.
|
||||
terminal). On macOS Ctrl+Y in a terminal always goes to the shell.
|
||||
- **Focus**: a window that shows or comes to the top puts the keyboard in its
|
||||
composer; hiding the last window gives it back to what had it.
|
||||
- **Cycle**: while a floating chat window's content holds the keyboard (a
|
||||
composer, a Files page inside it), Ctrl+Tab brings the next visible chat
|
||||
window to the top and Ctrl+Shift+Tab the previous one, wrapping round. The
|
||||
order is the stacking order, bottom to top, and the window's composer takes
|
||||
the keyboard. Command+Tab stays with the system. With the tiling focused,
|
||||
Ctrl+Tab still cycles its panes; while the terminal claims tab keys (shown)
|
||||
it switches terminal tabs. Alt+` (`windowCycleShortcut`) still cycles every
|
||||
kind of window, not only chats.
|
||||
- **Cycle**: Ctrl+Tab and Ctrl+Shift+Tab move between the chats the user can
|
||||
see, and never bring up one that is not shown.
|
||||
- **While any chat window is shown** (not minimised, its group shown), the
|
||||
keys cycle those windows only, from wherever the keyboard is in Chat: a
|
||||
window's composer, a Files page inside it, or the tiling (the chat list
|
||||
included). From a window, the next (previous) shown window in open order
|
||||
comes to the top, wrapping round. From the tiling, Ctrl+Tab takes the
|
||||
top-most shown window to the top first. Either way the window's composer
|
||||
takes the keyboard. Open order is the order the windows were opened (a
|
||||
restored window keeps its saved place), so a raise does not change the
|
||||
cycle; the stacking order does change on a raise.
|
||||
- **With no chat window shown**, Ctrl+Tab cycles the tiled panes only and
|
||||
the keys focus the chosen pane's composer. With one tiled pane it does
|
||||
nothing. A chat shown before, or a minimised or floating chat, is never
|
||||
swapped in.
|
||||
- Command+Tab stays with the system. While the terminal claims tab keys
|
||||
(shown) Ctrl+Tab switches terminal tabs. A keyboard held by another window
|
||||
(a run, terminal) is left to that window. Alt+` (`windowCycleShortcut`)
|
||||
still cycles every kind of window, not only chats.
|
||||
- **Popups**: sheets, dialogs, menus and tooltips opened from a floating chat
|
||||
are above every window. Files opens as a page inside the window, and a file
|
||||
opened from it stays in the window. Because the window's own title bar names
|
||||
@@ -69,17 +80,36 @@ every destination and come back at app start without Chat being opened.
|
||||
|
||||
## Checks
|
||||
|
||||
- Focused, 2026-11-12, `tool/memwatch/full.sh` with
|
||||
`test/features/chat/chat_floating_pane_test.dart` and
|
||||
`test/features/terminal/terminal_chat_tab_test.dart`: 16 passed, 0 failed.
|
||||
New in the first: Ctrl+Tab and Ctrl+Shift+Tab over three floating chats
|
||||
(order, wrap, composer focus, Command+Tab ignored); with the tiling focused
|
||||
Ctrl+Tab moves the active pane and leaves the windows alone, and with one
|
||||
window focused it does nothing; a terminal that claims tab keys keeps
|
||||
Ctrl+Tab over a focused chat window.
|
||||
- `tool/analyze.sh` on the changed paths: clean.
|
||||
- Affected states: two or more floating chats; one floating chat; tiling
|
||||
focused; a window focused with the terminal shown (claimed); Command+Tab.
|
||||
- Focused, 2026-11-12, `tool/memwatch/full.sh` over
|
||||
`test/features/chat/chat_floating_pane_test.dart`,
|
||||
`test/features/chat/chat_keyboard_focus_test.dart`,
|
||||
`test/features/chat/chat_control_tab_test.dart`,
|
||||
`test/features/chat/windows/chat_windows_test.dart` and
|
||||
`test/features/terminal/terminal_chat_tab_test.dart`: 38 passed, 0 failed.
|
||||
Related Ctrl+Tab users, `tool/memwatch/full.sh` over
|
||||
`test/shell/destination_shortcuts_test.dart`,
|
||||
`test/shell/tab_history_back_test.dart`, `test/shell/search_escape_test.dart`
|
||||
and `test/features/chat/shell/chat_shell_terminal_test.dart`: 26 passed,
|
||||
0 failed.
|
||||
- New in the first file: Ctrl+Tab and Ctrl+Shift+Tab over three floating chats
|
||||
cycle in open order, not stacking order (order, wrap, composer focus,
|
||||
Command+Tab ignored). With the tiling focused Ctrl+Tab goes to the top-most
|
||||
shown window and leaves the panes alone; with one shown window it does
|
||||
nothing; with the window minimised the panes cycle and the window stays
|
||||
hidden. With one tiled pane and a minimised chat, Ctrl+Tab does nothing and
|
||||
shows nothing. A terminal that claims tab keys keeps Ctrl+Tab over a focused
|
||||
chat window.
|
||||
- Removed: the single-pane recent-chat swap (the chat shown before, opened
|
||||
back into the pane), with its tests in `chat_keyboard_focus_test.dart`. A
|
||||
single pane with no shown window now does nothing on Ctrl+Tab, so
|
||||
`chat_control_tab_test.dart` no longer expects the composer to take focus
|
||||
from the sidebar.
|
||||
- `tool/analyze.sh` on `lib/features/chat` and the three chat test files:
|
||||
clean.
|
||||
- Affected states: two or more floating chats; one floating chat shown;
|
||||
floating chat minimised with one tiled pane; tiling focused with windows
|
||||
shown and with none; a window focused; the terminal shown (claimed);
|
||||
Command+Tab.
|
||||
- Not covered: the terminal's own tab switching (the test app has no terminal
|
||||
surface), real browser or device keys, and captures (ui-review's).
|
||||
- Observed, not changed: in the widget harness, floating from a pane's More
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Chat terminal buttons (narrow duplicate, bar styling)
|
||||
|
||||
## Findings (from the code and the ui-review captures)
|
||||
|
||||
- The terminal toggle is the shell's bar action, passed as `barActions` from
|
||||
`application/pipelines_app.dart` on the Chat tab. The shell draws that bar
|
||||
only where it is not covered:
|
||||
- Wide (>= 600, `kListDetailMinWidth`): the shell bar sits over the list
|
||||
column while a chat is open, so the terminal shows there beside New chat
|
||||
and Refresh (capture: `Terminal (Option+T)` at x 287). The chat's own bar
|
||||
holds only Files and More.
|
||||
- Narrow (< 600): the open chat is a pushed page with its own bar
|
||||
(`ShellBar(barless: true)`), which covers the shell bar. A shell-bar
|
||||
terminal button therefore never shows on a phone chat, even though it was
|
||||
listed in `barActions`. This is why the first attempt (keeping it in
|
||||
`barActions` for an open chat) rendered nothing on phone.
|
||||
- Narrow chat list: the shell bar shows the toggle beside New chat and
|
||||
Refresh (the duplicate this change removes).
|
||||
- The styling difference: `TerminalToggleButton` passed `isSelected: shown`,
|
||||
which tints the icon while the terminal is shown. Files and More
|
||||
(`ChatBarAction`, `SegmentedMoreButton`) are plain IconButtons with no
|
||||
selected state.
|
||||
|
||||
## Changes
|
||||
|
||||
- `lib/application/app_terminals.dart`: `barToggle(context)` returns the shell
|
||||
toggle only on a wide layout; null on narrow (chat list and open chat).
|
||||
- `lib/application/pipelines_app.dart`: the Chat tab's `barActions` uses
|
||||
`?_terminals.barToggle(context)`.
|
||||
- `lib/features/terminal/terminal_open_action.dart`: new
|
||||
`terminalChatBarAction(context)`: on narrow, with a terminal surface, a
|
||||
`ChatBarAction` (the same widget as Files) that toggles the terminal
|
||||
(identifier `chat-terminal-toggle`). Null on wide or without a surface.
|
||||
- `lib/features/chat/conversation/chat_thread_view.dart`: the chat header's
|
||||
actions are Files followed by `?terminalChatBarAction(context)`, so a
|
||||
narrow open chat shows the terminal beside Files.
|
||||
- `lib/features/terminal/terminal_toggle_button.dart`: drops `isSelected`; the
|
||||
shown state is exposed as `Semantics(toggled:)` only.
|
||||
|
||||
## Tests
|
||||
|
||||
- `test/application/app_terminals_test.dart`: wide 1000 px offers the shell
|
||||
toggle; narrow 390 px offers none.
|
||||
- `test/features/terminal/terminal_chat_bar_action_test.dart`, light and dark:
|
||||
phone 390 px: the chat bar's terminal button is present, the same size as
|
||||
Files, the same icon colour, not selected, and tapping it toggles the
|
||||
terminal; wide 1000 px and no terminal surface: no chat-bar terminal button.
|
||||
- `test/features/terminal/terminal_toggle_button_test.dart`, light and dark:
|
||||
the shell's terminal button has no `isSelected`, its icon colour equals
|
||||
Files' in hidden and shown states, both are 48 px, and the shown state is
|
||||
announced as toggled.
|
||||
- Affected users re-run: `terminal_first_open_test.dart`,
|
||||
`terminal_surface_test.dart`, `chat_floating_chrome_test.dart`,
|
||||
`chat_floating_pane_test.dart`.
|
||||
|
||||
## Focused results
|
||||
|
||||
`tool/memwatch/full.sh` with the seven paths above as one argument:
|
||||
57 passed, 0 failed (peak 1877 MB, 53 s; verdict names only those paths).
|
||||
`tool/analyze.sh`: clean.
|
||||
|
||||
## Expected states (from the code; not captured here)
|
||||
|
||||
- Phone chat list: no terminal in the bar; the shortcut bubble remains.
|
||||
- Phone open chat: the chat bar reads Files, terminal, More; the terminal is
|
||||
the same 48 px plain IconButton style as Files.
|
||||
- Wide chat list and wide open chat: placement unchanged; the shell bar's
|
||||
terminal button is plain (no selected tint).
|
||||
|
||||
## Not verified here
|
||||
|
||||
- Rendered states at phone and desktop sizes, light and dark, and hover and
|
||||
pressed states: not captured (ui-review owns captures).
|
||||
- `pipelines_app.dart` wiring has no direct test.
|
||||
`test/application/pipelines_app_test.dart` fails on untouched main (pending
|
||||
launch-update timer), so it was not run.
|
||||
@@ -0,0 +1,117 @@
|
||||
# First-run walkthrough
|
||||
|
||||
A short, skippable four-page walkthrough for new users of the Flutter app.
|
||||
|
||||
## What it does
|
||||
|
||||
- Shows once per device on first launch, from the Pipelines page.
|
||||
- Is also offered once per server when the device has already seen it and the
|
||||
connected server has no pipelines, runs or chats yet (the server is checked
|
||||
with `list_pipelines`, `list_runs` and `chat_sessions`; an unreadable server
|
||||
never triggers it).
|
||||
- Pages: 1) what Pipelines is and how to connect to the server; 2) set up an
|
||||
agent harness, with an agent picker and one copy button for
|
||||
`pipelines harness setup <agent>` (`claude`, `codex`, `opencode`, `pi`);
|
||||
3) the Pipelines and Runs tabs and how to start a run; 4) the Chat tab, float
|
||||
and terminal.
|
||||
- Every page has Skip; Back and Next move between pages; Done ends on the last.
|
||||
- Closing by any route (Skip, Done, the close gesture, a tap outside) records the
|
||||
device as seen.
|
||||
- Settings reopens it from Tools → Help → "Show the walkthrough". Reopening
|
||||
does not change the seen record.
|
||||
|
||||
## Where it lives
|
||||
|
||||
- `lib/features/walkthrough/`
|
||||
- `walkthrough_store.dart`: the seen/offered records (`pipelines.next.*` keys;
|
||||
a store that cannot be read reports "seen", so it never nags).
|
||||
- `walkthrough_steps.dart`: the page copy and agent list (pure data).
|
||||
- `first_run_walkthrough.dart`: the stepper and `showFirstRunWalkthrough`
|
||||
(a Material bottom sheet on phones, a dialog on wide windows, via
|
||||
`showAppDetails`).
|
||||
- `walkthrough_harness_command.dart`: agent chips, the command and copy.
|
||||
- `walkthrough_gate.dart`: the first-launch and empty-server check.
|
||||
- `lib/application/pipelines_app.dart`: wraps the Pipelines destination body in
|
||||
the gate (the Pipelines tab is the first screen).
|
||||
- `lib/features/settings/settings_walkthrough_section.dart`: one row in the
|
||||
Tools → Help group, plus `SettingsKeys.walkthrough`.
|
||||
|
||||
## Focused tests
|
||||
|
||||
- `test/features/walkthrough/walkthrough_gate_test.dart`: first launch shows
|
||||
once; Done and Skip persist; a seen device on an empty server is offered once;
|
||||
a seen device that starts disconnected makes no server call and is offered
|
||||
after it connects; an unreadable check is retried on the next connection (and
|
||||
a repeated notification while connected does not re-query); a server with
|
||||
work, an unreadable server, a hidden Pipelines page, and an unavailable store
|
||||
all stay quiet; hiding the Pipelines page while the first-launch read is
|
||||
still pending keeps the walkthrough closed, and showing it again offers it
|
||||
once.
|
||||
- `test/features/walkthrough/first_run_walkthrough_test.dart`: phone bottom
|
||||
sheet and wide dialog; Back disabled on page 1; four pages with Done on the
|
||||
last and Skip throughout; the harness picker and copy; large text (2x) and
|
||||
dark mode without overflow.
|
||||
- `test/features/settings/settings_walkthrough_test.dart`: the Settings row
|
||||
reopens the walkthrough on page 1.
|
||||
|
||||
## Results
|
||||
|
||||
- Focused run: `tool/memwatch/full.sh 'test/features/walkthrough/first_run_walkthrough_test.dart test/features/walkthrough/walkthrough_gate_test.dart test/features/settings/settings_walkthrough_test.dart'`
|
||||
→ PASS, 20 passed, 0 failed, peak 1031 MB, 16 s. The verdict named only these
|
||||
three paths.
|
||||
- Visibility fix (review must-fix, visit 2): the gate offered without checking
|
||||
`enabled`, so a walkthrough could open over another destination if Pipelines
|
||||
was hidden before the post-frame callback or during a pending read. The gate
|
||||
now checks `mounted && enabled` in the callback, after each await, and before
|
||||
each show. A skipped callback clears the in-flight flag, so re-enabling
|
||||
Pipelines reschedules the offer. Covered by the new gate test
|
||||
"hiding Pipelines while an offer is pending keeps the walkthrough closed".
|
||||
That test was not run against the pre-fix code, so the failing-before claim
|
||||
is by reasoning only.
|
||||
- Lifecycle fix (review must-fix): the empty-server check used to run once
|
||||
right after the first frame, before the session connected. A seen device
|
||||
then got a `NotConnectedError`, and the check was never retried. The gate now
|
||||
takes the session as its connection source (`connection` + `connected`), waits
|
||||
while disconnected, re-runs on each new connection until the server answers,
|
||||
and stays quiet on a repeated notification while connected. A connection that
|
||||
arrives between frames requests a visual update, so the post-frame callback
|
||||
runs. The fix is covered by the two new gate tests above.
|
||||
- Two earlier runs failed and were fixed in the test code, not by weakening
|
||||
expectations: the large-text test tapped Next before scrolling it into view,
|
||||
and the "unavailable store" test awaited the real preferences plugin inside
|
||||
`testWidgets` and hung. The store now takes an injectable opener, so that case
|
||||
is a plain test with a null opener.
|
||||
- `tool/analyze.sh`: clean (0 errors, 0 warnings, 0 infos).
|
||||
- Not run here: `pipelines_app_test`, the Settings screen suites and the other
|
||||
Pipelines suites. They belong to the land gate.
|
||||
|
||||
## Affected states (checked by focused tests only; nothing captured)
|
||||
|
||||
- Phone (390×844): bottom sheet; page 1 with Back disabled; all four pages;
|
||||
Skip mid-walkthrough.
|
||||
- Wide (1280×900): dialog; Next reaches page 2.
|
||||
- Harness page: four agent chips; the command follows the selected agent; copy
|
||||
copies the selected command and the button shows a check.
|
||||
- Large text (2×) on a 360×740 phone and dark mode: every page builds with no
|
||||
exception.
|
||||
- Gate: first launch once; Done and Skip persist; a seen device on an empty
|
||||
server is offered once per server; a server with runs, an unreadable server,
|
||||
a hidden Pipelines page and an unavailable store stay quiet.
|
||||
- Settings: "Show the walkthrough" reopens page 1 and does not change the seen
|
||||
record.
|
||||
|
||||
Nothing was built, run on a device or captured. `ui-review` owns the rendered
|
||||
review.
|
||||
|
||||
## Limitations
|
||||
|
||||
- The gate is tested in isolation with fake stores and gateways. The Pipelines
|
||||
wiring in `pipelines_app.dart` is not covered by a focused test.
|
||||
- Narrow window: the empty-server offer marks the server as offered before it
|
||||
shows. If Pipelines is hidden during that one store write, the server is
|
||||
consumed without the walkthrough appearing. Fixing it needs the store write
|
||||
to move to the dialog's close, which changes when the offer is recorded.
|
||||
- On phones the walkthrough is a Material bottom sheet, not a full page.
|
||||
- The harness command is shown as a picker with one copy button for the
|
||||
selected agent, not four separate copy buttons.
|
||||
- The "Show the walkthrough" test covers the row, not the whole Settings tree.
|
||||
@@ -96,3 +96,77 @@ section with error and Retry.
|
||||
- Not on-device verified.
|
||||
- The "Check for updates" action walks the servers sequentially when pressed. That
|
||||
is a user action, not the page load, and was left unchanged.
|
||||
|
||||
## Re-entry after land: main moved (merge of main)
|
||||
|
||||
Main changed the Settings files this branch rewrote, so the merge conflicted in
|
||||
`settings_keys.dart`, `settings_screen.dart` and `settings_topic_pages.dart`.
|
||||
Resolution (merge staged, not committed):
|
||||
|
||||
- `settings_topic_pages.dart` stays deleted. Its main-side change added a
|
||||
walkthrough row to the old tab layout; this page already has the row.
|
||||
- `settings_keys.dart` keeps `SettingsKeys.showWalkthrough` only; main's
|
||||
`SettingsKeys.walkthrough` is dropped.
|
||||
- `settings_screen.dart` keeps this branch's imports; main's
|
||||
`settings_walkthrough_section.dart` import is dropped.
|
||||
- `settings_walkthrough_section.dart` and its test
|
||||
`test/features/settings/settings_walkthrough_test.dart` (main's, for the removed
|
||||
tab row) are deleted. The reopen behaviour stays covered by the Help and about
|
||||
row test in `settings_screen_test.dart`.
|
||||
- `pipelines_app.dart` now passes `onShowWalkthrough` to Settings, calling
|
||||
`showFirstRunWalkthrough(context)`. Before this, the row was disabled in the
|
||||
app because nothing supplied the handler. The settings route builder now names
|
||||
its parameter `context`.
|
||||
- Main's device-delivery changes (warning, connection log, `open()`) merged
|
||||
cleanly and are kept.
|
||||
|
||||
Focused results (memwatch, from app/):
|
||||
- Passing: settings_screen_test, settings_device_delivery_section_test,
|
||||
settings_search_page_test, settings_layout_test, settings_library_test,
|
||||
settings_server_load_test, first_run_walkthrough_test, walkthrough_gate_test.
|
||||
- Failing: `test/application/settings_page_test.dart` (2 tests: the bar gear
|
||||
case and the rail case) and `test/application/settings_registration_test.dart`
|
||||
(1 test). The same tests fail on untouched main, and the pre-merge branch
|
||||
commit passes them. Likely cause: main's Pipelines bar now includes the
|
||||
terminal toggle (`pipelines_app.dart` `_shellFor`), which pushes out the
|
||||
`pipelines-open-settings` gear. Not fixed here; these tests need a decision on
|
||||
the gear.
|
||||
- `settings_tabs_test.dart` and `settings_topic_restore_test.dart` do not exist
|
||||
on this branch; they are stale names in the change list.
|
||||
|
||||
`tool/analyze.sh`: clean.
|
||||
Not on-device verified; no UI captured in this stage.
|
||||
|
||||
## Re-entry after ui-review: phone bar over the page
|
||||
|
||||
ui-review (visit 2) captured the phone page panned under the shell's floating tab
|
||||
bar. The bar's glass let the Terminal help text and its controls show through the
|
||||
bar, so they could not be read.
|
||||
|
||||
Cause: the shell's `Scaffold` uses `extendBody`, so the page's body reads the bar's
|
||||
height as its bottom padding. The page padded only its scroll end, so rows scrolled
|
||||
under the bar.
|
||||
|
||||
Fix (`settings_screen.dart`, embedded branch): the page's viewport now ends at the
|
||||
bar's top edge. It reserves the body's bottom padding (the bar's height, or the
|
||||
system inset when no bar shows) and removes that padding from its subtree, so the
|
||||
page's own end padding is not counted twice. The non-embedded (own Scaffold) branch
|
||||
is unchanged. On a wide window the bar is in the rail, so the reserved space is zero.
|
||||
|
||||
New regression test: `settings_screen_test.dart`, "phone: the page scrolls to rest
|
||||
above the floating tab bar". It pumps the page in a `Scaffold(extendBody: true)` with
|
||||
an 80 px bottom bar at 390×844, scrolls to the end, and asserts the list viewport and
|
||||
the last row (the walkthrough row) end above the bar. It was confirmed to fail on the
|
||||
previous embedded layout and to pass with this fix.
|
||||
|
||||
Focused results (memwatch, from app/, same path list as above, plus the new test):
|
||||
- 49 passed, 3 failed. The 3 failures are the known application tests from the
|
||||
land stage: `settings_page_test.dart` (390 and 1200 cases) and
|
||||
`settings_registration_test.dart`. They fail at a tap on `segmented.more` and a
|
||||
route check before reaching this layout. Not changed here.
|
||||
- `tool/analyze.sh` on the settings lib/test paths and the two application tests: clean.
|
||||
|
||||
Affected states to re-capture (ui-review owns this): phone light and dark, panned to
|
||||
the end of the page (the walkthrough row and Terminal help text must sit above the
|
||||
bar); desktop, where the bar is in the rail and nothing changes.
|
||||
Not on-device verified; no UI was built or captured in this stage.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/application/app_terminals.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_toggle_button.dart';
|
||||
|
||||
import '../features/terminal/terminal_fixtures.dart';
|
||||
|
||||
void main() {
|
||||
late TerminalGateway gateway;
|
||||
late AppTerminals terminals;
|
||||
|
||||
setUp(() {
|
||||
gateway = TerminalGateway();
|
||||
terminals = AppTerminals(
|
||||
pool: null,
|
||||
connection: ValueNotifier<int>(0),
|
||||
connected: () => true,
|
||||
gateway: gateway,
|
||||
machineId: 'mac',
|
||||
machineName: 'Mac',
|
||||
layout: TerminalLayout(store: MemoryLayoutStore()),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
terminals.dispose();
|
||||
gateway.close();
|
||||
});
|
||||
|
||||
/// Pumps [AppTerminals.barToggle] at [width] and returns what it built.
|
||||
Future<Widget?> barToggleAt(WidgetTester tester, double width) async {
|
||||
Widget? built;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: MediaQuery(
|
||||
data: MediaQueryData(size: Size(width, 800)),
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
built = terminals.barToggle(context);
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
return built;
|
||||
}
|
||||
|
||||
testWidgets('the Chat shell bar offers the terminal toggle on a wide layout', (
|
||||
tester,
|
||||
) async {
|
||||
final built = await barToggleAt(tester, 1000);
|
||||
expect(built, isA<TerminalToggleButton>());
|
||||
});
|
||||
|
||||
testWidgets('a narrow layout has no terminal toggle in the shell bar', (
|
||||
tester,
|
||||
) async {
|
||||
// Covers both a narrow chat list and an open narrow chat: the open chat's
|
||||
// own bar carries the terminal (terminal_chat_bar_action_test.dart).
|
||||
final built = await barToggleAt(tester, 390);
|
||||
expect(built, isNull);
|
||||
});
|
||||
}
|
||||
@@ -133,9 +133,8 @@ void main() {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
testWidgets('single pane focuses input; empty workspace does not consume', (
|
||||
tester,
|
||||
) async {
|
||||
testWidgets('single pane with no shown window does nothing; empty workspace '
|
||||
'does not consume', (tester) async {
|
||||
await _setup(tester, open: false);
|
||||
await _chord(tester);
|
||||
expect(find.byType(ChatWorkspace), findsNothing);
|
||||
@@ -144,7 +143,9 @@ void main() {
|
||||
_focusSidebar(tester);
|
||||
await tester.pumpAndSettle();
|
||||
await _chord(tester);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
|
||||
expect(find.byType(ChatWorkspace), findsOneWidget);
|
||||
expect(_workspace(tester).paneCount, 1);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse);
|
||||
expect(_editable(tester, 'a').controller.text, isEmpty);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
@@ -531,25 +531,36 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
expect(app.floating, ['b', 'c', 'a']);
|
||||
|
||||
// The cycle follows the order the windows were opened in (b, c, a), not
|
||||
// the stacking order, which each raise changes. From a (opened last) the
|
||||
// next is b, the first opened.
|
||||
await _tab(tester);
|
||||
expect(app.floating, ['c', 'a', 'b']);
|
||||
expect(_composerFocused(tester, 'b'), isTrue);
|
||||
// Past the top, the bottom window comes up again.
|
||||
await _tab(tester);
|
||||
expect(app.floating, ['a', 'b', 'c']);
|
||||
expect(_composerFocused(tester, 'c'), isTrue);
|
||||
await _tab(tester);
|
||||
expect(app.floating, ['b', 'c', 'a']);
|
||||
expect(_composerFocused(tester, 'a'), isTrue);
|
||||
await _tab(tester, shift: true);
|
||||
expect(app.floating, ['b', 'a', 'c']);
|
||||
expect(_composerFocused(tester, 'c'), isTrue);
|
||||
await _tab(tester, shift: true);
|
||||
expect(app.floating, ['a', 'c', 'b']);
|
||||
expect(_composerFocused(tester, 'b'), isTrue);
|
||||
// Back past the first opened: the last opened (a) comes up.
|
||||
await _tab(tester, shift: true);
|
||||
expect(app.floating, ['a', 'b', 'c']);
|
||||
expect(_composerFocused(tester, 'c'), isTrue);
|
||||
expect(app.floating, ['c', 'b', 'a']);
|
||||
expect(_composerFocused(tester, 'a'), isTrue);
|
||||
expect(tester.takeException(), isNull);
|
||||
await app.stop(tester);
|
||||
});
|
||||
|
||||
testWidgets('with the tiling focused Ctrl+Tab cycles its panes and leaves '
|
||||
'the windows alone', (tester) async {
|
||||
testWidgets('with the tiling focused Ctrl+Tab goes to the top-most shown '
|
||||
'window, and cycles the panes only when no window is shown', (
|
||||
tester,
|
||||
) async {
|
||||
await _saved('a', 'b', 'c');
|
||||
final app = _App(_Store());
|
||||
await app.start(tester);
|
||||
@@ -557,26 +568,61 @@ void main() {
|
||||
expect(app.floating, ['c']);
|
||||
final controller = _workspace(tester);
|
||||
|
||||
// A window is shown: from the tiling, Ctrl+Tab takes the keyboard to it
|
||||
// and the panes stay where they are.
|
||||
await tester.tapAt(tester.getCenter(_input('a')));
|
||||
await tester.pump();
|
||||
expect(controller.activePane?.sessionId, 'a');
|
||||
await _tab(tester);
|
||||
expect(controller.activePane?.sessionId, 'b');
|
||||
expect(_composerFocused(tester, 'b'), isTrue);
|
||||
expect(controller.activePane?.sessionId, 'a');
|
||||
expect(_composerFocused(tester, 'c'), isTrue);
|
||||
expect(app.floating, ['c']);
|
||||
|
||||
// With a window focused, the panes stay where they are; a single window
|
||||
// has nothing to cycle to.
|
||||
await tester.tapAt(tester.getCenter(_input('c')));
|
||||
await tester.pump();
|
||||
// A single shown window has nothing to cycle to.
|
||||
await _tab(tester);
|
||||
expect(controller.activePane?.sessionId, 'a');
|
||||
expect(_composerFocused(tester, 'c'), isTrue);
|
||||
expect(app.floating, ['c']);
|
||||
|
||||
// No window shown: the panes cycle and the hidden window stays hidden.
|
||||
await _chord(tester);
|
||||
expect(_shown('Chat c'), findsNothing);
|
||||
await tester.tapAt(tester.getCenter(_input('a')));
|
||||
await tester.pump();
|
||||
await _tab(tester);
|
||||
expect(controller.activePane?.sessionId, 'b');
|
||||
expect(_composerFocused(tester, 'b'), isTrue);
|
||||
expect(_shown('Chat c'), findsNothing);
|
||||
expect(app.floating, ['c']);
|
||||
expect(tester.takeException(), isNull);
|
||||
await app.stop(tester);
|
||||
});
|
||||
|
||||
testWidgets('with one tiled pane and no shown window Ctrl+Tab does nothing; '
|
||||
'a minimised chat is not brought up', (tester) async {
|
||||
await _saved('a', 'b');
|
||||
final app = _App(_Store());
|
||||
await app.start(tester);
|
||||
await _menu(tester, 'b', 'Float (Alt+Y)');
|
||||
await tester.tap(find.byTooltip('Minimise'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_shown('Chat b'), findsNothing);
|
||||
final controller = _workspace(tester);
|
||||
expect(controller.panes.map((p) => p.sessionId), ['a']);
|
||||
|
||||
await tester.tapAt(tester.getCenter(_input('a')));
|
||||
await tester.pump();
|
||||
await _tab(tester);
|
||||
await _tab(tester, shift: true);
|
||||
expect(controller.panes.map((p) => p.sessionId), ['a']);
|
||||
expect(controller.activePane?.sessionId, 'a');
|
||||
expect(_shown('Chat b'), findsNothing);
|
||||
expect(app.floating, ['b']);
|
||||
expect(app.opened, isEmpty);
|
||||
expect(tester.takeException(), isNull);
|
||||
await app.stop(tester);
|
||||
});
|
||||
|
||||
testWidgets('a terminal that claims tab keys keeps Ctrl+Tab over a focused '
|
||||
'floating chat', (tester) async {
|
||||
await _saved('a', 'b', 'c');
|
||||
|
||||
@@ -150,38 +150,29 @@ void main() {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
});
|
||||
|
||||
testWidgets('Control Tab over one pane returns to the previous chat', (
|
||||
tester,
|
||||
) async {
|
||||
testWidgets('Control Tab over one pane does nothing: it never brings up '
|
||||
'another chat', (tester) async {
|
||||
await _setup(tester);
|
||||
await _openRow(tester, 'a');
|
||||
final workspace = _workspace(tester);
|
||||
// Nothing shown before: the chord only focuses the composer.
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'a');
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isTrue);
|
||||
expect(_editable(tester, 'a').focusNode.hasPrimaryFocus, isFalse);
|
||||
|
||||
// Opening b replaces the lone pane; a is no longer shown anywhere.
|
||||
await _openRow(tester, 'b');
|
||||
await tester.enterText(_input('b'), 'Draft B');
|
||||
await _focusSidebar(tester);
|
||||
for (final id in ['a', 'b', 'a']) {
|
||||
await _controlTab(tester);
|
||||
for (final shift in [false, true]) {
|
||||
await _controlTab(tester, shift: shift);
|
||||
expect(workspace.paneCount, 1);
|
||||
expect(workspace.activePane?.sessionId, id);
|
||||
expect(_editable(tester, id).focusNode.hasPrimaryFocus, isTrue);
|
||||
expect(workspace.activePane?.sessionId, 'b');
|
||||
expect(_editable(tester, 'b').focusNode.hasPrimaryFocus, isFalse);
|
||||
expect(_editable(tester, 'b').controller.text, 'Draft B');
|
||||
}
|
||||
await _controlTab(tester, shift: true);
|
||||
expect(workspace.activePane?.sessionId, 'b');
|
||||
expect(_editable(tester, 'b').controller.text, 'Draft B');
|
||||
|
||||
// A third chat makes the pair c and b; a is no longer one step away.
|
||||
// Two panes cycle the panes, not the history.
|
||||
await _openRow(tester, 'c');
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'b');
|
||||
await _controlTab(tester);
|
||||
expect(workspace.activePane?.sessionId, 'c');
|
||||
|
||||
// Two panes cycle the panes as before, not the history.
|
||||
await tester.tap(_actions('a'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Open to the right'));
|
||||
|
||||
@@ -16,6 +16,7 @@ class FakeNotificationService implements NotificationServiceBridge {
|
||||
);
|
||||
|
||||
NotificationServiceStatus current;
|
||||
List<NotificationConnectionEvent> events = const [];
|
||||
final calls = <(String, Map<String, Object?>)>[];
|
||||
final _changes = StreamController<NotificationServiceStatus>.broadcast();
|
||||
bool batteryGranted = true;
|
||||
@@ -85,4 +86,9 @@ class FakeNotificationService implements NotificationServiceBridge {
|
||||
if (batteryGranted) current = copy(batteryExempt: true);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Not recorded in [calls]: the log is re-read after every action, and the
|
||||
// tests assert on the action calls themselves.
|
||||
@override
|
||||
Future<List<NotificationConnectionEvent>> connectionEvents() async => events;
|
||||
}
|
||||
|
||||
@@ -92,5 +92,39 @@ void main() {
|
||||
final bridge = createNotificationServiceBridge();
|
||||
expect(bridge.supported, isFalse);
|
||||
expect((await bridge.status()).state, DeliveryState.off);
|
||||
expect(await bridge.connectionEvents(), isEmpty);
|
||||
});
|
||||
|
||||
test('a refused session reports sign_in_required', () {
|
||||
expect(
|
||||
NotificationServiceStatus.fromMap({'status': 'sign_in_required'}).state,
|
||||
DeliveryState.signInRequired,
|
||||
);
|
||||
});
|
||||
|
||||
test('connectionEvents reads the service log, newest first', () async {
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'connectionEvents') {
|
||||
return [
|
||||
{
|
||||
'time': 2000,
|
||||
'event': 'failed',
|
||||
'error': 'Expected HTTP 101',
|
||||
'code': 403,
|
||||
},
|
||||
{'time': 1000, 'event': 'connected'},
|
||||
];
|
||||
}
|
||||
return reply();
|
||||
});
|
||||
final bridge = MethodChannelNotificationServiceBridge(channel);
|
||||
final events = await bridge.connectionEvents();
|
||||
expect(events.map((event) => event.event), ['failed', 'connected']);
|
||||
expect(events.first.code, 403);
|
||||
expect(events.first.error, 'Expected HTTP 101');
|
||||
expect(events.first.detail, 'HTTP 403 · Expected HTTP 101');
|
||||
expect(events.last.code, isNull);
|
||||
expect(events.last.error, isNull);
|
||||
expect(events.last.time, DateTime.fromMillisecondsSinceEpoch(1000));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ Widget _host(
|
||||
return MaterialApp(home: Scaffold(body: body));
|
||||
}
|
||||
|
||||
int _requests(FakeNotificationService service) =>
|
||||
service.calls.where((call) => call.$1 == 'requestBatteryExemption').length;
|
||||
|
||||
bool _switchValue(WidgetTester tester) {
|
||||
final tile = find.byKey(DeviceDeliveryKeys.toggle);
|
||||
return tester.widget<SwitchListTile>(tile).value;
|
||||
@@ -62,9 +65,11 @@ void main() {
|
||||
testWidgets('allow background delivery asks for the exemption', (
|
||||
tester,
|
||||
) async {
|
||||
final service = FakeNotificationService();
|
||||
final service = FakeNotificationService()..batteryGranted = false;
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
// The open-time prompt was declined; the row is the user's second try.
|
||||
service.batteryGranted = true;
|
||||
await tester.tap(find.text(deviceDeliveryBatteryLabel));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
@@ -125,6 +130,157 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(DeviceDeliveryKeys.error), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a missing battery exemption keeps a warning row with the Samsung note',
|
||||
(tester) async {
|
||||
// The open-time prompt is declined, so the exemption stays missing.
|
||||
final service = FakeNotificationService()..batteryGranted = false;
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget);
|
||||
expect(find.text(deviceDeliveryWarningTitle), findsOneWidget);
|
||||
expect(find.textContaining(deviceDeliverySamsungNote), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('the warning goes away once the exemption is granted', (
|
||||
tester,
|
||||
) async {
|
||||
final service = FakeNotificationService()..batteryGranted = false;
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget);
|
||||
service.batteryGranted = true;
|
||||
await tester.tap(find.text(deviceDeliveryBatteryLabel));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('switching on asks for the battery exemption before starting', (
|
||||
tester,
|
||||
) async {
|
||||
final service = FakeNotificationService();
|
||||
service.current = service.copy(enabled: false, state: DeliveryState.off);
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(DeviceDeliveryKeys.toggle));
|
||||
await tester.pumpAndSettle();
|
||||
final names = service.calls.map((call) => call.$1).toList();
|
||||
expect(names, contains('requestBatteryExemption'));
|
||||
expect(
|
||||
names.indexOf('requestBatteryExemption'),
|
||||
lessThan(names.indexOf('setEnabled')),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'opening Settings with delivery on and no exemption asks right away',
|
||||
(tester) async {
|
||||
final service = FakeNotificationService();
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_requests(service), 1);
|
||||
expect(
|
||||
find.text('Allowed: battery optimisation will not pause delivery'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsNothing);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('a declined open-time prompt is not repeated on resume', (
|
||||
tester,
|
||||
) async {
|
||||
final service = FakeNotificationService()..batteryGranted = false;
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_requests(service), 1);
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget);
|
||||
// Returning from the system screen re-reads the status only.
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
|
||||
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
|
||||
await tester.pumpAndSettle();
|
||||
expect(_requests(service), 1);
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('no open-time prompt when the exemption is already granted', (
|
||||
tester,
|
||||
) async {
|
||||
final service = FakeNotificationService();
|
||||
service.current = service.copy(batteryExempt: true);
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_requests(service), 0);
|
||||
});
|
||||
|
||||
testWidgets('no open-time prompt while delivery is off', (tester) async {
|
||||
final service = FakeNotificationService();
|
||||
service.current = service.copy(enabled: false, state: DeliveryState.off);
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(_requests(service), 0);
|
||||
});
|
||||
|
||||
testWidgets('no warning while delivery is off', (tester) async {
|
||||
final service = FakeNotificationService();
|
||||
service.current = service.copy(enabled: false, state: DeliveryState.off);
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(DeviceDeliveryKeys.batteryWarning), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a refused session says the user must sign in again', (
|
||||
tester,
|
||||
) async {
|
||||
final service = FakeNotificationService();
|
||||
service.current = service.copy(state: DeliveryState.signInRequired);
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text('Sign in to Pipelines again to keep notifications'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'the connection log lists the service events, failures included',
|
||||
(tester) async {
|
||||
final service = FakeNotificationService();
|
||||
service.events = [
|
||||
NotificationConnectionEvent(
|
||||
time: DateTime(2026, 11, 12, 9, 30, 5),
|
||||
event: 'failed',
|
||||
error: 'Expected HTTP 101',
|
||||
code: 403,
|
||||
),
|
||||
NotificationConnectionEvent(
|
||||
time: DateTime(2026, 11, 12, 9, 29),
|
||||
event: 'connected',
|
||||
),
|
||||
];
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(deviceDeliveryLogTitle));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Socket failed'), findsOneWidget);
|
||||
expect(
|
||||
find.textContaining('HTTP 403 · Expected HTTP 101'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Socket opened'), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('an empty connection log says so', (tester) async {
|
||||
final service = FakeNotificationService();
|
||||
await tester.pumpWidget(_host(service));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(deviceDeliveryLogTitle));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(deviceDeliveryLogEmpty), findsOneWidget);
|
||||
});
|
||||
}
|
||||
|
||||
class _FailingService extends FakeNotificationService {
|
||||
|
||||
@@ -413,6 +413,61 @@ void main() {
|
||||
await tester.pump();
|
||||
await connecting;
|
||||
});
|
||||
|
||||
testWidgets('phone: the page scrolls to rest above the floating tab bar', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(390, 844));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
final client = transport.PipelinesClient(
|
||||
channelFactory: FakeChannelFactory().call,
|
||||
);
|
||||
addTearDown(client.dispose);
|
||||
|
||||
// The shell's shape: a body that extends behind a bottom bar, which the
|
||||
// body reads as its bottom padding.
|
||||
const barKey = ValueKey<String>('test.tabBar');
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: Scaffold(
|
||||
extendBody: true,
|
||||
body: SettingsScreen(
|
||||
client: client,
|
||||
store: MemorySettingsStore(),
|
||||
embedded: true,
|
||||
onShowWalkthrough: () {},
|
||||
),
|
||||
bottomNavigationBar: const SizedBox(
|
||||
key: barKey,
|
||||
width: double.infinity,
|
||||
height: 80,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
final scroll = find.byKey(const ValueKey<String>('settings.scroll'));
|
||||
// Each lazy section that the scroll reaches grows the list, so keep
|
||||
// scrolling until the page stops moving.
|
||||
for (var i = 0; i < 6; i++) {
|
||||
await tester.drag(scroll, const Offset(0, -10000));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
final barTop = tester.getTopLeft(find.byKey(barKey)).dy;
|
||||
// Nothing scrolls under the bar: the list's viewport ends at its top edge,
|
||||
// and the last row (the page's end) sits above it at rest.
|
||||
expect(tester.getRect(scroll).bottom, lessThanOrEqualTo(barTop + 0.5));
|
||||
expect(
|
||||
tester.getRect(find.byKey(SettingsKeys.showWalkthrough)).bottom,
|
||||
lessThanOrEqualTo(barTop + 0.5),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
/// The Server URL and Workspace fields, addressed by their keys: the search
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/sessions/chat_adaptive.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_open_action.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_scope.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_toggle_button.dart';
|
||||
|
||||
class _Actions implements TerminalActions {
|
||||
int toggles = 0;
|
||||
|
||||
@override
|
||||
void toggle() => toggles++;
|
||||
|
||||
@override
|
||||
bool get claimsTabKeys => false;
|
||||
|
||||
@override
|
||||
Future<String?> openAt(ApiGateway gateway, String cwd) async => null;
|
||||
}
|
||||
|
||||
const _filesKey = ValueKey('files');
|
||||
const _terminalIdentifier = 'chat-terminal-toggle';
|
||||
|
||||
/// Pumps an open chat's bar at [width]: Files, then whatever
|
||||
/// [terminalChatBarAction] builds (null on wide or with no terminal surface).
|
||||
/// Returns what it built.
|
||||
Future<Widget?> _pumpBar(
|
||||
WidgetTester tester, {
|
||||
required double width,
|
||||
required ThemeData theme,
|
||||
_Actions? actions,
|
||||
}) async {
|
||||
Widget? built;
|
||||
final bar = MediaQuery(
|
||||
data: MediaQueryData(size: Size(width, 800)),
|
||||
child: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) {
|
||||
built = terminalChatBarAction(context);
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
ChatBarAction(
|
||||
key: _filesKey,
|
||||
label: 'Files',
|
||||
onPressed: () {},
|
||||
materialIcon: Icons.folder_outlined,
|
||||
),
|
||||
?built,
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: theme,
|
||||
home: actions == null
|
||||
? bar
|
||||
: TerminalScope(actions: actions, child: bar),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
return built;
|
||||
}
|
||||
|
||||
/// The colour an icon inside [finder] resolves to in the current theme.
|
||||
Color? _iconColor(WidgetTester tester, Finder finder) {
|
||||
final icon = find.descendant(of: finder, matching: find.byType(Icon));
|
||||
final element = tester.element(icon);
|
||||
return tester.widget<Icon>(icon).color ?? IconTheme.of(element).color;
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final theme in [
|
||||
ThemeData(brightness: Brightness.light, useMaterial3: true),
|
||||
ThemeData(brightness: Brightness.dark, useMaterial3: true),
|
||||
]) {
|
||||
final mode = theme.brightness.name;
|
||||
|
||||
testWidgets('$mode, phone: an open chat has a terminal button beside '
|
||||
'Files, styled as Files', (tester) async {
|
||||
final actions = _Actions();
|
||||
final built = await _pumpBar(
|
||||
tester,
|
||||
width: 390,
|
||||
theme: theme,
|
||||
actions: actions,
|
||||
);
|
||||
expect(built, isA<ChatBarAction>());
|
||||
|
||||
final terminal = find.bySemanticsIdentifier(_terminalIdentifier);
|
||||
final files = find.byKey(_filesKey);
|
||||
expect(terminal, findsOneWidget);
|
||||
expect(
|
||||
tester.getSize(terminal),
|
||||
tester.getSize(files),
|
||||
reason: 'the terminal button must be the same size as Files',
|
||||
);
|
||||
expect(
|
||||
_iconColor(tester, terminal),
|
||||
_iconColor(tester, files),
|
||||
reason: 'the terminal icon must share the colour of Files',
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.widget<IconButton>(
|
||||
find.descendant(of: terminal, matching: find.byType(IconButton)),
|
||||
)
|
||||
.isSelected,
|
||||
isNull,
|
||||
reason: 'the terminal must not be a selected (tinted) button',
|
||||
);
|
||||
expect(find.byTooltip(TerminalToggleButton.label), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('$mode, phone: tapping the terminal button toggles the '
|
||||
'terminal', (tester) async {
|
||||
final actions = _Actions();
|
||||
await _pumpBar(tester, width: 390, theme: theme, actions: actions);
|
||||
|
||||
await tester.tap(find.byTooltip(TerminalToggleButton.label));
|
||||
await tester.pump();
|
||||
expect(actions.toggles, 1);
|
||||
});
|
||||
|
||||
testWidgets('$mode, wide: the open chat bar has no terminal button (the '
|
||||
'shell bar keeps it)', (tester) async {
|
||||
final built = await _pumpBar(
|
||||
tester,
|
||||
width: 1000,
|
||||
theme: theme,
|
||||
actions: _Actions(),
|
||||
);
|
||||
expect(built, isNull);
|
||||
expect(find.bySemanticsIdentifier(_terminalIdentifier), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('$mode, phone without a terminal surface: no terminal button', (
|
||||
tester,
|
||||
) async {
|
||||
final built = await _pumpBar(tester, width: 390, theme: theme);
|
||||
expect(built, isNull);
|
||||
expect(find.bySemanticsIdentifier(_terminalIdentifier), findsNothing);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'dart:ui' as ui;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/sessions/chat_adaptive.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_scope.dart';
|
||||
import 'package:pipelines_app/features/terminal/terminal_toggle_button.dart';
|
||||
|
||||
import 'terminal_fixtures.dart';
|
||||
|
||||
class _Actions implements TerminalActions {
|
||||
int toggles = 0;
|
||||
|
||||
@override
|
||||
void toggle() => toggles++;
|
||||
|
||||
@override
|
||||
bool get claimsTabKeys => false;
|
||||
|
||||
@override
|
||||
Future<String?> openAt(ApiGateway gateway, String cwd) async => null;
|
||||
}
|
||||
|
||||
const _filesKey = ValueKey('files');
|
||||
const _terminalKey = ValueKey('shell.terminal');
|
||||
|
||||
/// A chat's bar: Files beside the terminal toggle, as the shell shows them.
|
||||
Widget _bar(TerminalLayout layout, _Actions actions, ThemeData theme) =>
|
||||
MaterialApp(
|
||||
theme: theme,
|
||||
home: TerminalScope(
|
||||
actions: actions,
|
||||
child: Scaffold(
|
||||
body: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
ChatBarAction(
|
||||
key: _filesKey,
|
||||
label: 'Files',
|
||||
onPressed: () {},
|
||||
materialIcon: Icons.folder_outlined,
|
||||
),
|
||||
TerminalToggleButton(layout: layout),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
/// The colour an icon inside [finder] resolves to in the current theme.
|
||||
Color? _iconColor(WidgetTester tester, Finder finder) {
|
||||
final icon = find.descendant(of: finder, matching: find.byType(Icon));
|
||||
final element = tester.element(icon);
|
||||
return tester.widget<Icon>(icon).color ?? IconTheme.of(element).color;
|
||||
}
|
||||
|
||||
/// Whether the terminal button's semantics (or one of its merged parents)
|
||||
/// is announced as toggled on.
|
||||
bool _toggled(WidgetTester tester) {
|
||||
for (
|
||||
SemanticsNode? node = tester.getSemantics(
|
||||
find.byTooltip(TerminalToggleButton.label),
|
||||
);
|
||||
node != null;
|
||||
node = node.parent
|
||||
) {
|
||||
if (node.flagsCollection.isToggled == ui.Tristate.isTrue) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final theme in [
|
||||
ThemeData(brightness: Brightness.light, useMaterial3: true),
|
||||
ThemeData(brightness: Brightness.dark, useMaterial3: true),
|
||||
]) {
|
||||
final mode = theme.brightness.name;
|
||||
|
||||
testWidgets('$mode: the terminal button is a plain bar button, shown or '
|
||||
'hidden, like Files', (tester) async {
|
||||
final layout = TerminalLayout(store: MemoryLayoutStore());
|
||||
final actions = _Actions();
|
||||
await tester.pumpWidget(_bar(layout, actions, theme));
|
||||
await tester.pump();
|
||||
|
||||
final files = find.byKey(_filesKey);
|
||||
final terminal = find.byKey(_terminalKey);
|
||||
for (final shown in [false, true]) {
|
||||
if (shown) layout.show();
|
||||
await tester.pump();
|
||||
|
||||
final button = tester.widget<IconButton>(terminal);
|
||||
expect(button.isSelected, isNull, reason: 'shown: $shown');
|
||||
expect(
|
||||
_iconColor(tester, terminal),
|
||||
_iconColor(tester, files),
|
||||
reason: 'icon colour differs from Files (shown: $shown)',
|
||||
);
|
||||
expect(tester.getSize(terminal), tester.getSize(files));
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('$mode: the shown state is announced without a tint', (
|
||||
tester,
|
||||
) async {
|
||||
final handle = tester.ensureSemantics();
|
||||
final layout = TerminalLayout(store: MemoryLayoutStore());
|
||||
final actions = _Actions();
|
||||
await tester.pumpWidget(_bar(layout, actions, theme));
|
||||
await tester.pump();
|
||||
|
||||
expect(_toggled(tester), isFalse);
|
||||
layout.show();
|
||||
await tester.pump();
|
||||
expect(_toggled(tester), isTrue);
|
||||
await tester.tap(find.byKey(_terminalKey));
|
||||
expect(actions.toggles, 1);
|
||||
handle.dispose();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/walkthrough/first_run_walkthrough.dart';
|
||||
import 'package:pipelines_app/features/walkthrough/walkthrough_steps.dart';
|
||||
import 'package:pipelines_app/ui/theme/app_theme.dart';
|
||||
|
||||
const _nextKey = ValueKey<String>('walkthrough.next');
|
||||
const _backKey = ValueKey<String>('walkthrough.back');
|
||||
const _skipKey = ValueKey<String>('walkthrough.skip');
|
||||
const _copyKey = ValueKey<String>('walkthrough.copy');
|
||||
const _commandKey = ValueKey<String>('walkthrough.command');
|
||||
const _launchKey = ValueKey<String>('launch');
|
||||
|
||||
Widget _launcher({ThemeMode mode = ThemeMode.light, double textScale = 1}) =>
|
||||
MaterialApp(
|
||||
theme: appLightTheme(),
|
||||
darkTheme: appDarkTheme(),
|
||||
themeMode: mode,
|
||||
builder: (context, child) => MediaQuery(
|
||||
data: MediaQuery.of(
|
||||
context,
|
||||
).copyWith(textScaler: TextScaler.linear(textScale)),
|
||||
child: child!,
|
||||
),
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) => Center(
|
||||
child: FilledButton(
|
||||
key: _launchKey,
|
||||
onPressed: () => showFirstRunWalkthrough(context),
|
||||
child: const Text('Open'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> _open(WidgetTester tester) async {
|
||||
await tester.tap(find.byKey(_launchKey));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void _useViewport(WidgetTester tester, Size size) {
|
||||
tester.view.devicePixelRatio = 1;
|
||||
tester.view.physicalSize = size;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('phone layout', () {
|
||||
testWidgets('opens as a bottom sheet with the first page', (tester) async {
|
||||
_useViewport(tester, const Size(390, 844));
|
||||
await tester.pumpWidget(_launcher());
|
||||
await _open(tester);
|
||||
|
||||
expect(find.byType(BottomSheet), findsOneWidget);
|
||||
expect(find.byType(Dialog), findsNothing);
|
||||
expect(find.text('Step 1 of 4'), findsOneWidget);
|
||||
expect(find.text(walkthroughSteps.first.title), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Back is disabled on the first page; Next advances', (
|
||||
tester,
|
||||
) async {
|
||||
_useViewport(tester, const Size(390, 844));
|
||||
await tester.pumpWidget(_launcher());
|
||||
await _open(tester);
|
||||
|
||||
expect(tester.widget<TextButton>(find.byKey(_backKey)).onPressed, isNull);
|
||||
await tester.tap(find.byKey(_nextKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Step 2 of 4'), findsOneWidget);
|
||||
expect(
|
||||
tester.widget<TextButton>(find.byKey(_backKey)).onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(_backKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Step 1 of 4'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('walks four pages, Done on the last, Skip on every page', (
|
||||
tester,
|
||||
) async {
|
||||
_useViewport(tester, const Size(390, 844));
|
||||
await tester.pumpWidget(_launcher());
|
||||
await _open(tester);
|
||||
|
||||
for (var page = 0; page < 3; page++) {
|
||||
expect(find.byKey(_skipKey), findsOneWidget);
|
||||
expect(find.text('Next'), findsOneWidget);
|
||||
await tester.tap(find.byKey(_nextKey));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
expect(find.text('Step 4 of 4'), findsOneWidget);
|
||||
expect(find.text('Done'), findsOneWidget);
|
||||
expect(find.byKey(_skipKey), findsOneWidget);
|
||||
expect(find.text(walkthroughSteps.last.title), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Done'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(walkthroughSteps.last.title), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Skip closes from the middle of the walkthrough', (
|
||||
tester,
|
||||
) async {
|
||||
_useViewport(tester, const Size(390, 844));
|
||||
await tester.pumpWidget(_launcher());
|
||||
await _open(tester);
|
||||
await tester.tap(find.byKey(_nextKey));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byKey(_skipKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(BottomSheet), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('wide windows open the walkthrough as a dialog', (tester) async {
|
||||
_useViewport(tester, const Size(1280, 900));
|
||||
await tester.pumpWidget(_launcher());
|
||||
await _open(tester);
|
||||
|
||||
expect(find.byType(Dialog), findsOneWidget);
|
||||
expect(find.byType(BottomSheet), findsNothing);
|
||||
expect(find.text('Step 1 of 4'), findsOneWidget);
|
||||
await tester.tap(find.byKey(_nextKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(walkthroughSteps[1].title), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('the harness page offers each agent and copies its command', (
|
||||
tester,
|
||||
) async {
|
||||
_useViewport(tester, const Size(390, 844));
|
||||
final copied = <String>[];
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
copied.add((call.arguments as Map)['text'] as String);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(
|
||||
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(_launcher());
|
||||
await _open(tester);
|
||||
await tester.tap(find.byKey(_nextKey));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
tester.widget<SelectableText>(find.byKey(_commandKey)).data,
|
||||
'pipelines harness setup claude',
|
||||
);
|
||||
await tester.tap(
|
||||
find.byKey(const ValueKey<String>('walkthrough.agent.pi')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester.widget<SelectableText>(find.byKey(_commandKey)).data,
|
||||
'pipelines harness setup pi',
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(_copyKey));
|
||||
await tester.pumpAndSettle();
|
||||
expect(copied, ['pipelines harness setup pi']);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(_copyKey),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('large text and dark mode lay out without overflow', (
|
||||
tester,
|
||||
) async {
|
||||
_useViewport(tester, const Size(360, 740));
|
||||
await tester.pumpWidget(_launcher(mode: ThemeMode.dark, textScale: 2));
|
||||
await _open(tester);
|
||||
|
||||
for (var page = 0; page < walkthroughSteps.length; page++) {
|
||||
expect(tester.takeException(), isNull, reason: 'page $page');
|
||||
expect(find.text(walkthroughSteps[page].title), findsOneWidget);
|
||||
if (page < walkthroughSteps.length - 1) {
|
||||
// At 2x text the phone sheet scrolls, so Next can start off screen.
|
||||
await tester.ensureVisible(find.byKey(_nextKey));
|
||||
await tester.tap(find.byKey(_nextKey));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
}
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/walkthrough/walkthrough_gate.dart';
|
||||
import 'package:pipelines_app/features/walkthrough/walkthrough_store.dart';
|
||||
import 'package:pipelines_app/ui/theme/app_theme.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _welcome = 'Welcome to Pipelines';
|
||||
|
||||
Future<SharedPreferences?> _noPreferences() async => null;
|
||||
|
||||
/// A gateway that answers the three empty-server list calls from fixed lists.
|
||||
class _FakeGateway implements ApiGateway {
|
||||
_FakeGateway({this.runs = const <Object>[], this.failing = false});
|
||||
|
||||
/// Runs the server reports; pipelines and chats are always empty here.
|
||||
final List<Object> runs;
|
||||
bool failing;
|
||||
final calls = <String>[];
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
calls.add(type);
|
||||
if (failing) throw StateError('offline');
|
||||
return switch (type) {
|
||||
'list_pipelines' => <String, dynamic>{'pipelines': const <Object>[]},
|
||||
'list_runs' => <String, dynamic>{'runs': runs},
|
||||
'chat_sessions' => <String, dynamic>{'chat_sessions': const <Object>[]},
|
||||
_ => <String, dynamic>{'type': 'error'},
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
|
||||
}
|
||||
|
||||
/// Delegates to [inner], but holds [isSeen] until [release] so a test can
|
||||
/// change the page visibility while an offer is still in flight.
|
||||
class _HeldStore implements WalkthroughStore {
|
||||
_HeldStore(this.inner);
|
||||
|
||||
final MemoryWalkthroughStore inner;
|
||||
Completer<void>? _gate;
|
||||
|
||||
void hold() => _gate = Completer<void>();
|
||||
|
||||
void release() {
|
||||
_gate?.complete();
|
||||
_gate = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> isSeen() async {
|
||||
await _gate?.future;
|
||||
return inner.isSeen();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> markSeen() => inner.markSeen();
|
||||
|
||||
@override
|
||||
Future<bool> wasOffered(String serverScope) =>
|
||||
inner.wasOffered(serverScope);
|
||||
|
||||
@override
|
||||
Future<void> markOffered(String serverScope) =>
|
||||
inner.markOffered(serverScope);
|
||||
}
|
||||
|
||||
/// [link] stands in for the session: its value is whether the server connected,
|
||||
/// and notifying it is the connection transition. Defaults to connected.
|
||||
Widget _host({
|
||||
required WalkthroughStore store,
|
||||
ApiGateway? gateway,
|
||||
bool enabled = true,
|
||||
ValueNotifier<bool>? link,
|
||||
}) {
|
||||
final session = link ?? ValueNotifier<bool>(true);
|
||||
return MaterialApp(
|
||||
theme: appLightTheme(),
|
||||
darkTheme: appDarkTheme(),
|
||||
home: Scaffold(
|
||||
body: FirstRunWalkthroughGate(
|
||||
store: store,
|
||||
enabled: enabled,
|
||||
serverScope: 'server-a',
|
||||
connection: session,
|
||||
connected: () => session.value,
|
||||
gateway: gateway,
|
||||
child: const Text('Pipelines page'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _finishWalkthrough(WidgetTester tester) async {
|
||||
for (var page = 0; page < 3; page++) {
|
||||
await tester.tap(find.byKey(const ValueKey<String>('walkthrough.next')));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
await tester.tap(find.text('Done'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('first launch shows the walkthrough once per device', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore();
|
||||
await tester.pumpWidget(_host(store: store));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsOneWidget);
|
||||
|
||||
await _finishWalkthrough(tester);
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(store.seen, isTrue);
|
||||
|
||||
// A later launch on the same device does not show it again.
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpWidget(_host(store: store));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(find.text('Pipelines page'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Done persists the seen record and no server query runs', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore();
|
||||
final gateway = _FakeGateway();
|
||||
await tester.pumpWidget(_host(store: store, gateway: gateway));
|
||||
await tester.pumpAndSettle();
|
||||
await _finishWalkthrough(tester);
|
||||
|
||||
expect(store.seen, isTrue);
|
||||
expect(
|
||||
gateway.calls,
|
||||
isEmpty,
|
||||
reason: 'first launch needs no server check',
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('Skip on the first page persists the seen record', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore();
|
||||
await tester.pumpWidget(_host(store: store));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey<String>('walkthrough.skip')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(store.seen, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('a seen device on an empty server is offered it once', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore(seen: true);
|
||||
final gateway = _FakeGateway();
|
||||
await tester.pumpWidget(_host(store: store, gateway: gateway));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsOneWidget);
|
||||
expect(store.offered, {'server-a'});
|
||||
expect(
|
||||
gateway.calls,
|
||||
containsAll(['list_pipelines', 'list_runs', 'chat_sessions']),
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey<String>('walkthrough.skip')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The server was offered already, so a fresh mount stays quiet.
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpWidget(_host(store: store, gateway: gateway));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a seen device that starts disconnected is offered once it connects',
|
||||
(tester) async {
|
||||
// Startup order in the app: the Pipelines page mounts before the session
|
||||
// has connected. The server must not be asked yet, and the offer must
|
||||
// still happen after the connection arrives.
|
||||
final store = MemoryWalkthroughStore(seen: true);
|
||||
final gateway = _FakeGateway();
|
||||
final link = ValueNotifier<bool>(false);
|
||||
await tester.pumpWidget(
|
||||
_host(store: store, gateway: gateway, link: link),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(
|
||||
gateway.calls,
|
||||
isEmpty,
|
||||
reason: 'no server call while disconnected',
|
||||
);
|
||||
expect(store.offered, isEmpty);
|
||||
|
||||
link.value = true;
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsOneWidget);
|
||||
expect(store.offered, {'server-a'});
|
||||
expect(
|
||||
gateway.calls,
|
||||
containsAll(['list_pipelines', 'list_runs', 'chat_sessions']),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('an unreadable check is retried on the next connection', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore(seen: true);
|
||||
final gateway = _FakeGateway(failing: true);
|
||||
final link = ValueNotifier<bool>(true);
|
||||
await tester.pumpWidget(_host(store: store, gateway: gateway, link: link));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(store.offered, isEmpty);
|
||||
final callsAfterFailure = gateway.calls.length;
|
||||
|
||||
// A repeated notification while still connected does not re-query.
|
||||
link.notifyListeners();
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.calls.length, callsAfterFailure);
|
||||
|
||||
// The server recovers; a fresh connection runs the check and offers it.
|
||||
gateway.failing = false;
|
||||
link.value = false;
|
||||
await tester.pumpAndSettle();
|
||||
link.value = true;
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsOneWidget);
|
||||
expect(store.offered, {'server-a'});
|
||||
});
|
||||
|
||||
testWidgets('a seen device on a server with work is not offered', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore(seen: true);
|
||||
final gateway = _FakeGateway(
|
||||
runs: <Object>[
|
||||
<String, dynamic>{'id': 'run-1'},
|
||||
],
|
||||
);
|
||||
await tester.pumpWidget(_host(store: store, gateway: gateway));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(store.offered, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('an unreadable server never triggers the walkthrough', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore(seen: true);
|
||||
await tester.pumpWidget(
|
||||
_host(store: store, gateway: _FakeGateway(failing: true)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(store.offered, isEmpty);
|
||||
});
|
||||
|
||||
testWidgets('the Pipelines page being hidden defers the check', (
|
||||
tester,
|
||||
) async {
|
||||
final store = MemoryWalkthroughStore();
|
||||
await tester.pumpWidget(_host(store: store, enabled: false));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(store.seen, isFalse);
|
||||
|
||||
await tester.pumpWidget(_host(store: store, enabled: true));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(_welcome), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'hiding Pipelines while an offer is pending keeps the walkthrough closed',
|
||||
(tester) async {
|
||||
final inner = MemoryWalkthroughStore();
|
||||
final store = _HeldStore(inner)..hold();
|
||||
await tester.pumpWidget(_host(store: store));
|
||||
await tester.pump();
|
||||
|
||||
// The Pipelines page is hidden while the offer is still reading the store.
|
||||
await tester.pumpWidget(_host(store: store, enabled: false));
|
||||
store.release();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(_welcome), findsNothing);
|
||||
expect(inner.seen, isFalse);
|
||||
|
||||
// Showing Pipelines again offers it once, on the same mount.
|
||||
await tester.pumpWidget(_host(store: store, enabled: true));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(_welcome), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
test('an unavailable preference store reports seen and offered', () async {
|
||||
// The opener yields no preferences, as when the platform store is absent:
|
||||
// every read reports "seen" and every write is quietly dropped.
|
||||
const store = SharedPreferencesWalkthroughStore(open: _noPreferences);
|
||||
expect(await store.isSeen(), isTrue);
|
||||
expect(await store.wasOffered('server-a'), isTrue);
|
||||
await store.markSeen();
|
||||
await store.markOffered('server-a');
|
||||
expect(await store.isSeen(), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'SharedPreferences store records seen and offered under the keys',
|
||||
() async {
|
||||
SharedPreferences.setMockInitialValues(<String, Object>{});
|
||||
const store = SharedPreferencesWalkthroughStore();
|
||||
expect(await store.isSeen(), isFalse);
|
||||
await store.markSeen();
|
||||
expect(await store.isSeen(), isTrue);
|
||||
|
||||
expect(await store.wasOffered('server-a'), isFalse);
|
||||
await store.markOffered('server-a');
|
||||
expect(await store.wasOffered('server-a'), isTrue);
|
||||
expect(await store.wasOffered('server-b'), isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user