Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(apps): keep taps on open iPhone menus and list a dev server's addresses

leepokai6a9d7adf7c21
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt b/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt
index 980d1558..1eddb907 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt
@@ -90,6 +90,7 @@ private fun menuItems(botId: String, server: DevServer, store: AppStore, showLog
fun act(action: DevServerAction) = store.devServerAction(action, botId, server.id)
return server.menuRows.mapIndexed { index, row ->
when (row) {
+ is DevServerMenuRow.OpenAddress -> MenuItem(row.title, icon = "arrow.up.right", verbatim = true) { open(row.address) }
DevServerMenuRow.OnlyOnComputer -> MenuItem("Only reachable on the computer", enabled = false)
DevServerMenuRow.StartedByShell -> MenuItem("Started through the bot's shell: it stops with the bot", enabled = false)
DevServerMenuRow.Open -> MenuItem("Open", icon = "arrow.up.right") { server.remoteAddress?.let(open) }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt
index b0918a17..f4b6036a 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt
@@ -23,8 +23,12 @@ data class DevServer(
val exitCode: Int? = null,
val managed: Boolean = true,
) {
- /** Where a phone can reach it while it runs; null when it listens only on its computer. */
- val remoteAddress: String? get() = if (status == DevServerStatus.Running) ports.firstNotNullOfOrNull { it.remote.firstOrNull() } else null
+ /** Where a phone can reach it while it runs, best first: the first port that has any. */
+ val remoteAddresses: List<String> get() =
+ if (status == DevServerStatus.Running) ports.firstOrNull { it.remote.isNotEmpty() }?.remote.orEmpty() else emptyList()
+
+ /** The best of them; null when it listens only on its computer. */
+ val remoteAddress: String? get() = remoteAddresses.firstOrNull()
/** Its row's value: its ports, or a phrase to look up. */
val rowValue: String get() = when (status) {
@@ -38,11 +42,17 @@ data class DevServer(
val tap: DevServerTap? get() = remoteAddress?.let(DevServerTap::Open)
?: DevServerTap.Logs.takeIf { managed && !(status == DevServerStatus.Running && ports.isNotEmpty()) }
- /** Only what applies. A server the bot started through its shell can only be opened or stopped. */
+ /**
+ * Only what applies. A server the bot started through its shell can only be opened or stopped. A tap opens the first
+ * address, which this phone may not reach (a computer's Tailscale address, without Tailscale here), so when there are
+ * more each one is a row.
+ */
val menuRows: List<DevServerMenuRow> get() = buildList {
val live = status == DevServerStatus.Running || status == DevServerStatus.Starting
if (status == DevServerStatus.Running && ports.isNotEmpty() && remoteAddress == null) add(DevServerMenuRow.OnlyOnComputer)
- if (remoteAddress != null) { add(DevServerMenuRow.Open); add(DevServerMenuRow.CopyAddress) }
+ if (remoteAddresses.size > 1) remoteAddresses.forEach { add(DevServerMenuRow.OpenAddress(it)) }
+ else if (remoteAddress != null) add(DevServerMenuRow.Open)
+ if (remoteAddress != null) add(DevServerMenuRow.CopyAddress)
if (managed) {
add(DevServerMenuRow.Logs)
if (status != DevServerStatus.Starting) add(if (live) DevServerMenuRow.Restart else DevServerMenuRow.Start)
@@ -83,7 +93,21 @@ sealed interface DevServerTap {
}
/** A line of its menu. */
-enum class DevServerMenuRow { OnlyOnComputer, Open, CopyAddress, Logs, Restart, Start, StartedByShell, Stop, Remove }
+sealed interface DevServerMenuRow {
+ data object OnlyOnComputer : DevServerMenuRow
+ data object Open : DevServerMenuRow
+ data class OpenAddress(val address: String) : DevServerMenuRow {
+ /** As the row shows it. */
+ val title: String get() = address.removePrefix("http://")
+ }
+ data object CopyAddress : DevServerMenuRow
+ data object Logs : DevServerMenuRow
+ data object Restart : DevServerMenuRow
+ data object Start : DevServerMenuRow
+ data object StartedByShell : DevServerMenuRow
+ data object Stop : DevServerMenuRow
+ data object Remove : DevServerMenuRow
+}
/** What the chat's title shows of a bot's servers: nothing until one starts, or once they've all stopped. */
sealed interface DevServerSummary {
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt
index 09128500..e101c6ca 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt
@@ -9,7 +9,9 @@ class DevServerTest {
private fun server(status: DevServerStatus = DevServerStatus.Running, name: String = "web", ports: List<DevServerPort> = emptyList(), managed: Boolean = true) =
DevServer("a", name, "npm run dev", "/site", status, ports, startedAt = 1, managed = managed)
private fun port(number: Int, remote: List<String> = emptyList()) = DevServerPort(number, "http://localhost:$number", remote)
- private val reachable = port(5173, listOf("http://192.168.1.20:5173"))
+ private val tailscale = "http://100.64.0.1:5173"
+ private val lan = "http://192.168.1.20:5173"
+ private val reachable = port(5173, listOf(lan))
@Test fun `the title shows nothing without a live server`() {
assertEquals(DevServerSummary.None, devServerSummary(emptyList()))
@@ -64,6 +66,22 @@ class DevServerTest {
assertEquals(listOf(Logs, Start, Remove), server(DevServerStatus.Failed).menuRows)
}
+ @Test fun `a tap opens the first address and several are each a row of the menu`() {
+ val two = server(ports = listOf(port(5173, listOf(tailscale, lan))))
+ assertEquals(DevServerTap.Open(tailscale), two.tap)
+ assertEquals(listOf(tailscale, lan), two.remoteAddresses)
+ assertEquals(listOf(OpenAddress(tailscale), OpenAddress(lan), CopyAddress, Logs, Restart, Stop), two.menuRows)
+ // The first port listens only on the computer; the second doesn't.
+ assertEquals(listOf(OpenAddress(tailscale), OpenAddress(lan)), server(ports = listOf(port(1), port(5173, listOf(tailscale, lan)))).menuRows.take(2))
+ // Copy address copies the first.
+ assertEquals(tailscale, two.remoteAddress)
+ assertEquals(listOf(Logs, Start, Remove), server(DevServerStatus.Stopped, ports = listOf(port(5173, listOf(tailscale, lan)))).menuRows)
+ }
+
+ @Test fun `a row names an address without its scheme`() {
+ assertEquals("192.168.1.20:5173", OpenAddress(lan).title)
+ }
+
@Test fun `a server left in the bot's shell can only be opened or stopped`() {
assertEquals(listOf(Open, CopyAddress, StartedByShell, Stop), server(ports = listOf(reachable), managed = false).menuRows)
assertEquals(listOf(OnlyOnComputer, StartedByShell, Stop), server(ports = listOf(port(5173)), managed = false).menuRows)
diff --git a/apps/desktop/src/renderer/views/thread/DevServersSection.tsx b/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
index 4acbf51c..58b26117 100644
--- a/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
+++ b/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
-import { devServerAddress, devServerClick, devServerMenuRows, devServerValue, type DevServer, type DevServerMenuRow, type DevServerSummary } from '@shared/dev-servers'
+import { devServerAddress, devServerAddressTitle, devServerClick, devServerMenuRows, devServerValue, type DevServer, type DevServerMenuRow, type DevServerSummary } from '@shared/dev-servers'
import type { Bot } from '@shared/models'
import { Button, IconButton, Spinner } from '../../components/Controls'
import { AnchoredMenu, ModalHeader, Sheet, SheetPage, type MenuItem } from '../../components/Overlay'
@@ -55,15 +55,12 @@ function Row({ bot, server, showLogs }: { bot: Bot; server: DevServer; showLogs:
const clicked = () => {
const click = devServerClick(server, onThisComputer)
switch (click.kind) {
- case 'open':
- analytics.track({ event: 'dev_server_action', action: 'open' })
- window.codync.app.openExternal(click.address)
- return
+ case 'open': return openAddress(click.address)
case 'logs': return showLogs()
case 'menu': return setMenu(true)
}
}
- const items = () => menuItems(bot, server, devServerAddress(server, onThisComputer), store, showLogs)
+ const items = () => menuItems(bot, server, onThisComputer, store, showLogs)
return (
<HStack className="dev-server-row">
<button className="dev-server-open" title={tooltip(server, tr)} onClick={clicked}>
@@ -90,12 +87,19 @@ function tooltip(server: DevServer, tr: (text: string) => string): string {
return `${server.command}${code}`
}
-function menuItems(bot: Bot, server: DevServer, address: string | null, store: BotStore, showLogs: () => void): MenuItem[] {
+function openAddress(address: string) {
+ analytics.track({ event: 'dev_server_action', action: 'open' })
+ window.codync.app.openExternal(address)
+}
+
+function menuItems(bot: Bot, server: DevServer, onThisComputer: boolean, store: BotStore, showLogs: () => void): MenuItem[] {
+ const address = devServerAddress(server, onThisComputer)
const copyAddress = (local: string) => {
analytics.track({ event: 'dev_server_action', action: 'copy' })
window.codync.app.copy(address ?? local)
}
const item = (row: DevServerMenuRow, divider: boolean): MenuItem => {
+ if (typeof row === 'object') return { title: devServerAddressTitle(row.open), icon: 'arrow.up.right', verbatim: true, action: () => openAddress(row.open) }
switch (row) {
case 'copyAddress':
// Elsewhere, a server that listens on its computer only can't be opened from here.
@@ -119,7 +123,7 @@ function menuItems(bot: Bot, server: DevServer, address: string | null, store: B
return { title: 'Remove', icon: 'trash', destructive: true, divider, action: () => store.devServers.act('devServerRemove', bot.id, server.id) }
}
}
- return devServerMenuRows(server).map((row, index) => item(row, index > 0))
+ return devServerMenuRows(server, onThisComputer).map((row, index) => item(row, index > 0))
}
function Logs({ bot, server }: { bot: Bot; server: DevServer }) {
diff --git a/apps/desktop/src/shared/dev-servers.test.ts b/apps/desktop/src/shared/dev-servers.test.ts
index 1cd04cac..fe6c981f 100644
--- a/apps/desktop/src/shared/dev-servers.test.ts
+++ b/apps/desktop/src/shared/dev-servers.test.ts
@@ -1,12 +1,14 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { devServerAddress, devServerClick, devServerMenuRows, devServerSummary, devServerValue, type DevServer } from './dev-servers.ts'
+import { devServerAddress, devServerAddressTitle, devServerClick, devServerMenuRows, devServerRemote, devServerSummary, devServerValue, type DevServer } from './dev-servers.ts'
import { normalizeBot } from './models.ts'
const server = (over: Partial<DevServer>): DevServer => ({
id: 'a', name: 'web', command: 'npm run dev', folder: '/site', status: 'running', ports: [], startedAt: 1, exitCode: null, managed: true, ...over,
})
const port = (n: number, remote: string[] = []) => ({ port: n, local: `http://localhost:${n}`, remote })
+const tailscale = 'http://100.64.0.1:5173'
+const lan = 'http://192.168.1.20:5173'
test('the title shows nothing without a live server', () => {
assert.deepEqual(devServerSummary([]), { kind: 'none' })
@@ -35,7 +37,29 @@ test('a server opens at its local address on its own computer', () => {
test('elsewhere, an SSH store included, a server opens only at what other devices can reach', () => {
assert.equal(devServerAddress(server({ ports: [port(5173)] }), false), null)
- assert.equal(devServerAddress(server({ ports: [port(5173, ['http://192.168.1.20:5173'])] }), false), 'http://192.168.1.20:5173')
+ assert.equal(devServerAddress(server({ ports: [port(5173, [lan])] }), false), lan)
+ assert.equal(devServerAddress(server({ ports: [port(1), port(5173, [lan])] }), false), lan, 'the first port listens only on the computer')
+})
+
+test('elsewhere, a click opens the first address, and several are each a row of the menu', () => {
+ const two = server({ ports: [port(5173, [tailscale, lan])] })
+ assert.deepEqual(devServerClick(two, false), { kind: 'open', address: tailscale })
+ assert.deepEqual(devServerRemote(two), [tailscale, lan])
+ assert.deepEqual(devServerMenuRows(two, false), [{ open: tailscale }, { open: lan }, 'copyAddress', 'logs', 'restart', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({ ports: [port(1), port(5173, [tailscale, lan])] }), false).slice(0, 2), [{ open: tailscale }, { open: lan }])
+ assert.equal(devServerAddress(two, false), tailscale, 'Copy address copies the first')
+ assert.deepEqual(devServerMenuRows(server({ ports: [port(5173, [lan])] }), false), ['copyAddress', 'logs', 'restart', 'stop'], 'one has nothing to choose')
+ assert.deepEqual(devServerMenuRows(server({ status: 'stopped', ports: [port(5173, [tailscale, lan])] }), false), ['logs', 'start', 'remove'], 'a stopped server has no address')
+})
+
+test('on its own computer a server opens at local, with no rows for its addresses', () => {
+ const two = server({ ports: [port(5173, [tailscale, lan])] })
+ assert.equal(devServerAddress(two, true), 'http://localhost:5173')
+ assert.deepEqual(devServerMenuRows(two, true), ['copyAddress', 'logs', 'restart', 'stop'])
+})
+
+test('a row names an address without its scheme', () => {
+ assert.equal(devServerAddressTitle(lan), '192.168.1.20:5173')
})
test('only a running server with a port opens', () => {
@@ -61,12 +85,12 @@ test('a click opens what can be reached from here, and reads the log of what has
})
test('the menu offers only what applies', () => {
- assert.deepEqual(devServerMenuRows(server({ ports: [port(5173)] })), ['copyAddress', 'logs', 'restart', 'stop'])
- assert.deepEqual(devServerMenuRows(server({})), ['logs', 'restart', 'stop'])
- assert.deepEqual(devServerMenuRows(server({ status: 'starting' })), ['logs', 'stop'])
- assert.deepEqual(devServerMenuRows(server({ status: 'stopped' })), ['logs', 'start', 'remove'])
- assert.deepEqual(devServerMenuRows(server({ status: 'failed' })), ['logs', 'start', 'remove'])
- assert.deepEqual(devServerMenuRows(server({ ports: [port(5173)], managed: false })), ['copyAddress', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({ ports: [port(5173)] }), true), ['copyAddress', 'logs', 'restart', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({}), true), ['logs', 'restart', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({ status: 'starting' }), true), ['logs', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({ status: 'stopped' }), true), ['logs', 'start', 'remove'])
+ assert.deepEqual(devServerMenuRows(server({ status: 'failed' }), true), ['logs', 'start', 'remove'])
+ assert.deepEqual(devServerMenuRows(server({ ports: [port(5173)], managed: false }), true), ['copyAddress', 'stop'])
})
test('a status from a newer host reads as stopped', () => {
diff --git a/apps/desktop/src/shared/dev-servers.ts b/apps/desktop/src/shared/dev-servers.ts
index a577803a..116d7287 100644
--- a/apps/desktop/src/shared/dev-servers.ts
+++ b/apps/desktop/src/shared/dev-servers.ts
@@ -50,11 +50,19 @@ export function devServerSummary(servers: DevServer[]): DevServerSummary {
* computer. Anywhere else (a phone, or a desktop attached over SSH, whose loopback is a tunnel) can't use `local`.
*/
export function devServerAddress(server: DevServer, onThisComputer: boolean): string | null {
- const port = server.ports[0]
- if (server.status !== 'running' || !port) return null
- return onThisComputer ? port.local : port.remote[0] ?? null
+ if (server.status !== 'running') return null
+ return onThisComputer ? server.ports[0]?.local ?? null : devServerRemote(server)[0] ?? null
}
+/** Where other devices can reach it while it runs, best first: the first port that has any. */
+export function devServerRemote(server: DevServer): string[] {
+ if (server.status !== 'running') return []
+ return server.ports.find((port) => port.remote.length > 0)?.remote ?? []
+}
+
+/** An address as a menu row shows it. */
+export const devServerAddressTitle = (address: string) => address.replace(/^http:\/\//, '')
+
/** Its row's value: its ports, or a phrase to look up. */
export function devServerValue(server: DevServer): string {
switch (server.status) {
@@ -75,12 +83,18 @@ export function devServerClick(server: DevServer, onThisComputer: boolean): DevS
return server.managed && !listens ? { kind: 'logs' } : { kind: 'menu' }
}
-export type DevServerMenuRow = 'copyAddress' | 'logs' | 'restart' | 'start' | 'stop' | 'remove'
+export type DevServerMenuRow = { open: string } | 'copyAddress' | 'logs' | 'restart' | 'start' | 'stop' | 'remove'
-/** Only what applies. A server the bot started through its shell can only be opened or stopped. */
-export function devServerMenuRows(server: DevServer): DevServerMenuRow[] {
+/**
+ * Only what applies. A server the bot started through its shell can only be opened or stopped. Elsewhere, a click opens
+ * the first address, which this device may not reach (a computer's Tailscale address, without Tailscale here), so when
+ * there are more each one is a row. On its own computer `local` always works.
+ */
+export function devServerMenuRows(server: DevServer, onThisComputer: boolean): DevServerMenuRow[] {
const live = server.status === 'running' || server.status === 'starting'
const rows: DevServerMenuRow[] = []
+ const addresses = onThisComputer ? [] : devServerRemote(server)
+ if (addresses.length > 1) rows.push(...addresses.map((address) => ({ open: address })))
if (live && server.ports.length > 0) rows.push('copyAddress')
if (server.managed) {
rows.push('logs')
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift b/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift
index 5ccf35db..597808e4 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift
@@ -32,7 +32,7 @@ public struct DevServer: Codable, Identifiable, Hashable, Sendable {
/// A line of its menu.
public enum MenuRow: Equatable, Sendable {
- case onlyOnComputer, open, copyAddress, logs, restart, start, startedByShell, stop, remove
+ case onlyOnComputer, open, openAddress(String), copyAddress, logs, restart, start, startedByShell, stop, remove
}
public var id: String
@@ -47,9 +47,17 @@ public struct DevServer: Codable, Identifiable, Hashable, Sendable {
}
public extension DevServer {
- /// Where a phone can reach it while it runs; nil when it listens only on its computer.
- var remoteAddress: String? {
- status == .running ? ports.lazy.compactMap(\.remote.first).first : nil
+ /// Where a phone can reach it while it runs, best first: the first port that has any.
+ var remoteAddresses: [String] {
+ status == .running ? ports.first { !$0.remote.isEmpty }?.remote ?? [] : []
+ }
+
+ /// The best of them; nil when it listens only on its computer.
+ var remoteAddress: String? { remoteAddresses.first }
+
+ /// An address as a menu row shows it.
+ static func addressTitle(_ address: String) -> String {
+ String(address.trimmingPrefix("http://"))
}
/// Its row's value: its ports, or a phrase to look up.
@@ -69,12 +77,19 @@ public extension DevServer {
return managed && !listens ? .logs : nil
}
- /// Only what applies. A server the bot started through its shell can only be opened or stopped.
+ /// Only what applies. A server the bot started through its shell can only be opened or stopped. A tap opens the first
+ /// address, which this phone may not reach (a computer's Tailscale address, without Tailscale here), so when there are
+ /// more each one is a row.
var menuRows: [MenuRow] {
let live = status == .running || status == .starting
var rows: [MenuRow] = []
if status == .running, !ports.isEmpty, remoteAddress == nil { rows.append(.onlyOnComputer) }
- if remoteAddress != nil { rows += [.open, .copyAddress] }
+ if remoteAddresses.count > 1 {
+ rows += remoteAddresses.map(MenuRow.openAddress)
+ } else if remoteAddress != nil {
+ rows.append(.open)
+ }
+ if remoteAddress != nil { rows.append(.copyAddress) }
if managed {
rows.append(.logs)
if status != .starting { rows.append(live ? .restart : .start) }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift
index b083db1c..ef537936 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift
@@ -70,6 +70,7 @@ private struct DevServerRow: View {
case .onlyOnComputer: MenuItem("Only reachable on the computer", enabled: false) {}
case .startedByShell: MenuItem("Started through the bot's shell: it stops with the bot", enabled: false) {}
case .open: MenuItem("Open", icon: "arrow.up.right") { if let address = server.remoteAddress { open(address) } }
+ case let .openAddress(address): MenuItem(DevServer.addressTitle(address), icon: "arrow.up.right", verbatim: true) { open(address) }
case .copyAddress: MenuItem("Copy address", icon: "doc.on.doc") { copyAddress() }
case .logs: MenuItem("Logs", icon: "doc.text", action: showLogs)
case .restart: MenuItem("Restart", icon: "arrow.clockwise") { act(.restart) }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Chrome.swift b/apps/ios/Kit/Sources/CodyncUI/Chrome.swift
index d30b2fca..f85e6b48 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Chrome.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Chrome.swift
@@ -195,33 +195,72 @@ private struct CodyncItemSheet<Item: Identifiable, Sheet: View>: ViewModifier {
}
/// The system sheet: its own slide, grabber and swipe down, nothing hand-built.
-private struct CodyncSheet<Sheet: View>: ViewModifier {
+@MainActor private struct CodyncSheet<Sheet: View>: ViewModifier {
@Binding var isPresented: Bool
let sheet: () -> Sheet
+ @State private var held = Held<() -> Sheet>()
func body(content: Content) -> some View {
- content.sheet(isPresented: $isPresented) {
- sheet()
- .environment(\.dismissModal, DismissModalAction { isPresented = false })
- .presentationDragIndicator(.visible)
+ let _ = (held.value = sheet)
+ content.quietPresentation(shown: isPresented) {
+ $0.sheet(isPresented: $isPresented) {
+ HeldView { held.value?() }
+ .environment(\.dismissModal, DismissModalAction { isPresented = false })
+ .presentationDragIndicator(.visible)
+ }
}
}
}
-private struct CodyncOverlay<Layer: View>: ViewModifier {
+@MainActor private struct CodyncOverlay<Layer: View>: ViewModifier {
@Binding var isPresented: Bool
let layer: (_ close: @escaping () -> Void) -> Layer
+ @State private var held = Held<(_ close: @escaping () -> Void) -> Layer>()
func body(content: Content) -> some View {
- content
- .fullScreenCover(isPresented: $isPresented) {
- FadeLayer(close: { isPresented = false }, layer: layer)
+ let _ = (held.value = layer)
+ content.quietPresentation(shown: isPresented) {
+ $0.fullScreenCover(isPresented: $isPresented) {
+ FadeLayer(close: { isPresented = false }, layer: { close in HeldView { held.value?(close) } })
.presentationBackground(.clear)
}
.transaction(value: isPresented) { $0.disablesAnimations = true }
+ }
+ }
+}
+
+extension View {
+ /// Applies a presentation modifier (`.sheet`, `.fullScreenCover`, `.photosPicker`) that runs again only when what it
+ /// presents opens or closes. Any of them running again re-sends the content of whatever is presented, which resolves
+ /// the icons of a system menu open there anew and so rebuilds it, and a press during a rebuild is lost. So they can't
+ /// run with every render of the screen behind. Directly, only for what the system draws (`.photosPicker`): content of
+ /// our own would freeze here, so it goes through `.codyncSheet` or `.codyncOverlay`, which keep it live with `Held`.
+ func quietPresentation<Presenter: View>(shown: Bool, @ViewBuilder _ presenter: @escaping (Color) -> Presenter) -> some View {
+ background { QuietPresenter(shown: shown, presenter: presenter).equatable() }
}
}
+private struct QuietPresenter<Presenter: View>: View, Equatable {
+ let shown: Bool
+ let presenter: (Color) -> Presenter
+
+ nonisolated static func == (lhs: Self, rhs: Self) -> Bool { lhs.shown == rhs.shown }
+
+ var body: some View { presenter(.clear) }
+}
+
+/// What's presented, as of the latest render of the screen behind it.
+@MainActor @Observable private final class Held<Value> {
+ var value: Value?
+}
+
+/// Reads `Held` in a body of its own, which is what updates when it changes.
+private struct HeldView<Content: View>: View {
+ @ViewBuilder let content: () -> Content
+
+ var body: some View { content() }
+}
+
private struct FadeLayer<Layer: View>: View {
let close: () -> Void
let layer: (_ close: @escaping () -> Void) -> Layer
diff --git a/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift b/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
index d82c0367..f35ab546 100644
--- a/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
@@ -2,8 +2,7 @@ import CodyncKit
import SwiftUI
/// One row in a Codync menu: an action, a choice when `selected` is set, or a submenu.
-public struct MenuItem: Identifiable {
- public let id = UUID()
+public struct MenuItem {
public var title: String
public var icon: String?
/// A picture in the icon's place (an agent's logo).
@@ -43,6 +42,15 @@ public struct MenuItem: Identifiable {
func shownTitle(_ translate: (String) -> String = { L10n.tr($0) }) -> String { verbatim ? title : translate(title) }
}
+/// Rows are equal when they show the same thing; the action isn't part of it, since closures always differ.
+extension MenuItem: Equatable {
+ public static func == (lhs: MenuItem, rhs: MenuItem) -> Bool {
+ lhs.shownTitle() == rhs.shownTitle() && lhs.icon == rhs.icon && lhs.image == rhs.image && lhs.selected == rhs.selected
+ && lhs.destructive == rhs.destructive && lhs.divider == rhs.divider && lhs.enabled == rhs.enabled
+ && lhs.submenu == rhs.submenu
+ }
+}
+
/// A row of emoji above a message's menu (Slack's quick reactions).
public struct ReactionPick {
public var emoji: [String]
@@ -66,6 +74,7 @@ public extension View {
private struct ContextActions: ViewModifier {
let items: () -> [MenuItem]
let reactions: ReactionPick?
+ @State private var latest = LatestMenuRows()
func body(content: Content) -> some View {
content.contextMenu {
@@ -78,40 +87,75 @@ private struct ContextActions: ViewModifier {
}
.controlGroupStyle(.palette)
}
- ForEach(items()) { item in
- if item.divider { Divider() }
- systemMenuRow(item)
- }
+ MenuRows(rows: latest.holding(items()), latest: latest).equatable()
+ }
+ }
+}
+
+/// The rows of a menu as of its last update, so a row that didn't update still runs its newest action.
+@MainActor final class LatestMenuRows {
+ private var rows: [MenuItem] = []
+
+ func holding(_ rows: [MenuItem]) -> [MenuItem] {
+ self.rows = rows
+ return rows
+ }
+
+ /// A press can outrun an update that moved the rows: a place that now shows something else runs what was pressed,
+ /// never what took its place.
+ func run(_ pressed: MenuItem, row: Int, inSubmenu: Int? = nil) {
+ guard rows.indices.contains(row) else { return }
+ let siblings = inSubmenu == nil ? rows : rows[row].submenu
+ let index = inSubmenu ?? row
+ guard siblings.indices.contains(index) else { return }
+ (siblings[index] == pressed ? siblings[index] : pressed).action()
+ }
+}
+
+/// A menu's rows. SwiftUI rebuilds an open system menu when its content updates, and a press during that rebuild is lost,
+/// so they update only when what they show changed: not because the screen behind them did.
+private struct MenuRows: View {
+ let rows: [MenuItem]
+ let latest: LatestMenuRows
+
+ var body: some View {
+ ForEach(rows.indices, id: \.self) { index in
+ let item = rows[index]
+ if item.divider { Divider() }
+ systemMenuRow(item, row: index, latest: latest)
}
}
}
+extension MenuRows: @MainActor Equatable {
+ static func == (lhs: Self, rhs: Self) -> Bool { lhs.rows == rhs.rows }
+}
+
/// A `MenuItem` inside a system `Menu` or `contextMenu`; a submenu opens its rows in a system
/// `Menu`, one level deep (an opaque row type can't contain itself).
-@ViewBuilder private func systemMenuRow(_ item: MenuItem) -> some View {
+@MainActor @ViewBuilder private func systemMenuRow(_ item: MenuItem, row: Int, latest: LatestMenuRows) -> some View {
if item.submenu.isEmpty {
- systemMenuAction(item)
+ systemMenuAction(item) { latest.run(item, row: row) }
} else {
Menu {
- ForEach(item.submenu) { row in
- let _ = assert(row.submenu.isEmpty, "A submenu is one level deep: this row would be a dead button")
- if row.divider { Divider() }
- systemMenuAction(row)
+ ForEach(item.submenu.indices, id: \.self) { index in
+ let inner = item.submenu[index]
+ let _ = assert(inner.submenu.isEmpty, "A submenu is one level deep: this row would be a dead button")
+ if inner.divider { Divider() }
+ systemMenuAction(inner) { latest.run(inner, row: row, inSubmenu: index) }
}
} label: { menuLabel(item) }
}
}
-/// A `MenuItem` that runs its action: choices as checkmarked toggles.
-@ViewBuilder private func systemMenuAction(_ item: MenuItem) -> some View {
+/// A `MenuItem` that runs `action`: choices as checkmarked toggles.
+@ViewBuilder private func systemMenuAction(_ item: MenuItem, action: @escaping @MainActor () -> Void) -> some View {
let role: ButtonRole? = item.destructive ? .destructive : nil
if let selected = item.selected {
- // The binding's setter must be Sendable, but SwiftUI only calls it from the menu, on the
- // main thread where the action was made.
- nonisolated(unsafe) let action = item.action
- Toggle(isOn: Binding(get: { selected }, set: { _ in action() })) { menuLabel(item) }
+ // SwiftUI only calls the binding's setter from the menu, on the main thread.
+ Toggle(isOn: Binding(get: { selected }, set: { _ in MainActor.assumeIsolated { action() } })) { menuLabel(item) }
} else {
- Button(role: role, action: item.action) { menuLabel(item) }
+ Button(role: role, action: action) { menuLabel(item) }
.disabled(!item.enabled)
}
}
@@ -131,6 +175,7 @@ private struct ContextActions: ViewModifier {
public struct DropdownMenu<Label: View>: View {
let items: () -> [MenuItem]
let label: Label
+ @State private var latest = LatestMenuRows()
public init(items: @escaping () -> [MenuItem], @ViewBuilder label: () -> Label) {
self.items = items
@@ -140,10 +185,7 @@ public struct DropdownMenu<Label: View>: View {
public var body: some View {
// The system menu: it anchors correctly inside sheets and scroll views, where an overlay can't.
Menu {
- ForEach(items()) { item in
- if item.divider { Divider() }
- systemMenuRow(item)
- }
+ MenuRows(rows: latest.holding(items()), latest: latest).equatable()
} label: { label }
.buttonStyle(.plain)
.menuIndicator(.hidden)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
index a599cabc..b7985ced 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift
@@ -156,7 +156,9 @@ struct Composer: View {
.fileImporter(isPresented: $pickingFiles, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in
if case .success(let urls) = result { add(urls) }
}
- .photosPicker(isPresented: $pickingPhotos, selection: $photoItems, maxSelectionCount: 10, matching: .images)
+ .quietPresentation(shown: pickingPhotos) {
+ $0.photosPicker(isPresented: $pickingPhotos, selection: $photoItems, maxSelectionCount: 10, matching: .images)
+ }
.onChange(of: photoItems) { _, items in
guard !items.isEmpty else { return }
photoItems = []
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift
index 4613540d..4e1c82fe 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift
@@ -12,7 +12,9 @@ private func port(_ number: Int, remote: [String] = []) -> DevServer.Port {
DevServer.Port(port: number, local: "http://localhost:\(number)", remote: remote)
}
-private let reachable = port(5173, remote: ["http://192.168.1.20:5173"])
+private let tailscale = "http://100.64.0.1:5173"
+private let lan = "http://192.168.1.20:5173"
+private let reachable = port(5173, remote: [lan])
@Suite struct DevServerTests {
@Test func theTitleShowsNothingWithoutALiveServer() {
@@ -67,6 +69,23 @@ private let reachable = port(5173, remote: ["http://192.168.1.20:5173"])
#expect(server(.failed).menuRows == [.logs, .start, .remove])
}
+ @Test func aTapOpensTheFirstAddressAndSeveralAreEachARowOfTheMenu() {
+ let two = server(ports: [port(5173, remote: [tailscale, lan])])
+ #expect(two.tap == .open(tailscale))
+ #expect(two.remoteAddresses == [tailscale, lan])
+ #expect(two.menuRows == [.openAddress(tailscale), .openAddress(lan), .copyAddress, .logs, .restart, .stop])
+ // The first port listens only on the computer; the second doesn't.
+ let second = server(ports: [port(1), port(5173, remote: [tailscale, lan])])
+ #expect(Array(second.menuRows.prefix(2)) == [.openAddress(tailscale), .openAddress(lan)])
+ // Copy address copies the first.
+ #expect(two.remoteAddress == tailscale)
+ #expect(server(.stopped, ports: [port(5173, remote: [tailscale, lan])]).menuRows == [.logs, .start, .remove])
+ }
+
+ @Test func aRowNamesAnAddressWithoutItsScheme() {
+ #expect(DevServer.addressTitle(lan) == "192.168.1.20:5173")
+ }
+
@Test func aServerLeftInTheBotsShellCanOnlyBeOpenedOrStopped() {
#expect(server(ports: [reachable], managed: false).menuRows == [.open, .copyAddress, .startedByShell, .stop])
#expect(server(ports: [port(5173)], managed: false).menuRows == [.onlyOnComputer, .startedByShell, .stop])
diff --git a/apps/ios/Kit/Tests/CodyncUITests/MenuRowsTests.swift b/apps/ios/Kit/Tests/CodyncUITests/MenuRowsTests.swift
new file mode 100644
index 00000000..9e982290
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncUITests/MenuRowsTests.swift
@@ -0,0 +1,54 @@
+import SwiftUI
+import Testing
+@testable import CodyncUI
+
+@MainActor @Suite struct MenuRowsTests {
+ @Test func rowsAreEqualWhenTheyShowTheSameThingWhateverTheirActions() {
+ #expect(MenuItem("Logs", icon: "doc.text") { print("one") } == MenuItem("Logs", icon: "doc.text") { print("two") })
+ }
+
+ @Test func anyChangeARowShowsMakesItDifferent() {
+ let row = MenuItem("Logs", icon: "doc.text") {}
+ #expect(row != MenuItem("Files", icon: "doc.text") {})
+ #expect(row != MenuItem("Logs", icon: "trash") {})
+ #expect(row != MenuItem("Logs", icon: "doc.text", selected: true) {})
+ #expect(row != MenuItem("Logs", icon: "doc.text", destructive: true) {})
+ #expect(row != MenuItem("Logs", icon: "doc.text", divider: true) {})
+ #expect(row != MenuItem("Logs", icon: "doc.text", enabled: false) {})
+ #expect(MenuItem("Move", submenu: [MenuItem("A") {}]) != MenuItem("Move", submenu: [MenuItem("B") {}]))
+ }
+
+ @Test func aRowThatDidNotUpdateRunsItsNewestAction() {
+ var ran: [String] = []
+ let latest = LatestMenuRows()
+ _ = latest.holding([MenuItem("Logs") { ran.append("old") }, MenuItem("Move", submenu: [MenuItem("A") { ran.append("old A") }])])
+ _ = latest.holding([MenuItem("Logs") { ran.append("new") }, MenuItem("Move", submenu: [MenuItem("A") { ran.append("new A") }])])
+ latest.run(MenuItem("Logs") {}, row: 0)
+ latest.run(MenuItem("A") {}, row: 1, inSubmenu: 0)
+ #expect(ran == ["new", "new A"])
+ }
+
+ @Test func aRowGoneFromTheMenuRunsNothing() {
+ var ran = false
+ let latest = LatestMenuRows()
+ _ = latest.holding([MenuItem("Logs") { ran = true }])
+ latest.run(MenuItem("Logs") {}, row: 3)
+ latest.run(MenuItem("Logs") {}, row: 0, inSubmenu: 3)
+ #expect(!ran)
+ }
+
+ @Test func aPressThatOutranAnUpdateRunsWhatWasPressedNotWhatTookItsPlace() {
+ var ran: [String] = []
+ let stop = MenuItem("Stop") { ran.append("stop") }
+ let first = MenuItem("First") { ran.append("first") }
+ let latest = LatestMenuRows()
+ _ = latest.holding([MenuItem("Logs") {}, MenuItem("Restart") {}, stop, MenuItem("Move", submenu: [first])])
+ _ = latest.holding([
+ MenuItem("Logs") {}, MenuItem("Start") {}, MenuItem("Remove") { ran.append("remove") },
+ MenuItem("Move", submenu: [MenuItem("Second") { ran.append("second") }]),
+ ])
+ latest.run(stop, row: 2)
+ latest.run(first, row: 3, inSubmenu: 0)
+ #expect(ran == ["stop", "first"])
+ }
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 06c6cc73..59163b62 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -10,7 +10,9 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- bot 現在可以讓 dev server 持續在電腦上執行,不會因為 bot 閒置或重新啟動而中斷。port 會顯示在聊天標題下方;點 bot 的名稱,就能看記錄、重新啟動或停止;手機連得到電腦時,也能直接開啟。
- 用量頁面可以自己選要看哪些服務:預設只顯示 bot 正在用的,也可以打開或隱藏其他服務。另外支援顯示 Google Antigravity 和 GitHub Copilot 的額度。
+- 修正 bot 更新時,選單偶爾點了沒反應的問題。
### en-US
- Bots can now keep a dev server running on your computer, even when the bot goes idle or restarts. Its port shows under the chat title; tap the bot's name to read its logs, restart or stop it, and to open it when your phone can reach it.
-- Choose which agents show in Usage: by default it lists the ones your bots run, and you can turn others on or hide them. Usage now also reads Google Antigravity's and GitHub Copilot's limits.
\ No newline at end of file
+- Choose which agents show in Usage: by default it lists the ones your bots run, and you can turn others on or hide them. Usage now also reads Google Antigravity's and GitHub Copilot's limits.
+- Fixed menus sometimes ignoring a tap while a bot was updating.
diff --git a/apps/maestro/dev-servers.js b/apps/maestro/dev-servers.js
index e06c23e6..aad3768a 100644
--- a/apps/maestro/dev-servers.js
+++ b/apps/maestro/dev-servers.js
@@ -1,6 +1,6 @@
// Makes the bot `dev-servers.yaml` opens, on the host the phone is paired with (HOST_PORT and HOST_TOKEN, passed with
-// `-e`), with a server listening only on the computer and one whose command fails. The tool's call comes through the
-// host's API, so no agent or model runs. `CLEANUP`, when the flow completes, deletes the bot again.
+// `-e`), with a server listening only on the computer, one on all interfaces and one whose command fails. The tool's call
+// comes through the host's API, so no agent or model runs. `CLEANUP`, when the flow completes, deletes the bot again.
const api = (method, body) => {
const res = http.post(`http://127.0.0.1:${HOST_PORT}/api/${method}`, {
headers: { Authorization: `Bearer ${HOST_TOKEN}`, 'Content-Type': 'application/json' },
@@ -23,6 +23,9 @@ if (typeof CLEANUP !== 'undefined') {
const port = 20000 + Math.floor(Math.random() * 10000)
start('docs', 'echo no such script; exit 3')
start('web', `python3 -m http.server ${port} --bind 127.0.0.1`)
+ // From an empty folder: on all interfaces, it would otherwise share the bot's with the network.
+ start('shared', `python3 -m http.server ${port + 1} --directory "$(mktemp -d)"`)
output.bot = { name, id: bot.id }
output.port = String(port)
+ output.sharedPort = String(port + 1)
}
diff --git a/apps/maestro/dev-servers.yaml b/apps/maestro/dev-servers.yaml
index 3a5e21bc..f4e551df 100644
--- a/apps/maestro/dev-servers.yaml
+++ b/apps/maestro/dev-servers.yaml
@@ -37,6 +37,22 @@ onFlowComplete:
- assertVisible: "docs"
- assertVisible: "Failed to start"
- takeScreenshot: dev-servers-details
+# On all interfaces: the menu opens it, with Open or, when this computer has several addresses, a row for each. Those
+# leave the app, so they're only read.
+- assertVisible: ":${output.sharedPort}"
+- tapOn: "More actions for shared"
+- assertVisible: "Copy address"
+- runFlow:
+ when:
+ notVisible: "Open"
+ commands:
+ - assertVisible: ".+:${output.sharedPort}"
+- tapOn: "Stop"
+- assertVisible: "Stopped"
+- tapOn: "More actions for shared"
+- tapOn: "Remove"
+- assertNotVisible: "Remove"
+- assertNotVisible: "shared"
# It listens only on the computer: the menu says so, and offers no way to open it.
- tapOn: "More actions for web"
- assertVisible: "Only reachable on the computer"
@@ -58,6 +74,9 @@ onFlowComplete:
- assertVisible: "Stopped"
- tapOn: "More actions for web"
- tapOn: "Remove"
+# A menu left open hides the rows behind it from Maestro, so the gone row alone doesn't show the tap worked.
+- assertNotVisible: "Remove"
+- assertVisible: "docs"
- assertNotVisible: "web"
# One that failed: a tap on its row reads why.
- tapOn: "docs"
@@ -67,4 +86,5 @@ onFlowComplete:
- tapOn: "More actions for docs"
- assertVisible: "Start"
- tapOn: "Remove"
+- assertNotVisible: "Remove"
- assertNotVisible: "Dev servers"
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 83bf8e45..75711f30 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -4,6 +4,8 @@
The bot list and conversation use the system `NavigationStack` toolbar. `ToolbarItem` owns the account button, centered computer status/filter menu, and New button (New bot, New group chat). Computer management is inside the centered menu. The conversation copies Grok Bot: the title (the bot's avatar and name) is a plain button that opens its details sheet on Details, a group's editor for a group (VoiceOver: "<name>, view details"); the other bot actions live where the desktop has them (Pin, Make lead agent and Delete in the bot list's touch-and-hold menu, one list with no dividers, and no New session anywhere: sessions start over on their own, Full conversation through a message's Show what it did, Reconnect through pull to refresh and the computer menu), the only trailing button is the computer (remote screen; it pulses while this bot operates the screen), and the call button sits in the composer as a filled waveform capsule while the box is empty. Menus opened from toolbar buttons (New, the computer filter) are native `Menu`s, like every iOS menu; the conversation uses the system back button. iOS supplies Liquid Glass, control sizing, grouping and interaction feedback.
+iOS presents through `.codyncSheet` or `.codyncOverlay` (`Chrome.swift`), and what the system draws (`.photosPicker`) through `.quietPresentation`, which would freeze content of our own; never a raw `.sheet`, `.fullScreenCover` or `.photosPicker`. Any of those running again with a render re-sends what's presented, which rebuilds a system menu open there (its icons resolve anew), and a press during the rebuild is lost. `.fileImporter` hasn't been measured and stays raw. Two menus still rebuild with the list: the roster toolbar's computer and New menus, raw `Menu`s outside `MenuRows` (New's lost taps aren't measured).
+
The conversation keeps the native glass buttons over the chat with a soft top scroll-edge effect, so messages blur out under the header instead of running sharp behind it. Root error dialogs use an in-place, full-screen scrim so presenting them does not change the underlying glass controls' appearance.
iPhone conversation scrolling leaves dragging, deceleration, and bottom rubber-band return to UIKit. Passive bottom-following must not move the offset during those gestures, and returning from bottom overscroll does not count as reading history or show Jump to latest. Desktop keeps browser scrolling; the terminal uses line-based scrolling, so neither shares this UIKit-specific behavior.
diff --git a/docs/features/dev-servers.md b/docs/features/dev-servers.md
index ef5de10d..98d047bd 100644
--- a/docs/features/dev-servers.md
+++ b/docs/features/dev-servers.md
@@ -108,11 +108,12 @@ white, and color comes from the bots.
`⋯`, which on the desktop shows only when the row is hovered.
- **Other devices:** a server listening only on its computer can't be opened from a phone, or from a desktop over SSH
(`store === app.local`, not `isLoopback`: an SSH store is loopback through its tunnel). Its menu says so. A server on all
- interfaces opens at its first `remote` address.
+ interfaces opens at its first `remote` address, which this device may not reach (a Tailscale address, without Tailscale
+ here), so with several the menu lists each one to open, in place of `Open`.
- **Logs:** a sheet with the last 200 lines and a refresh button; for a failed server, its exit code.
- **Terminal:** `/servers` or a click on the port opens a sheet instead of a section; keys in `tui/manage/dev_servers.rs`,
the footer listing those that apply to the selected server. `codync-host tui --url` may be a tunnel, which looks local,
- so it shows the address instead of opening a browser.
+ so its sheet lists the selected server's addresses, one line each, instead of opening a browser.
Each client: desktop `views/thread/DevServersSection.tsx` and `src/shared/dev-servers.ts`; iPhone
`CodyncUI/Bots/DevServersSection.swift`; Android `DevServersSection.kt`; terminal `tui/manage/dev_servers.rs` and
diff --git a/host/src/tui/app/bot.rs b/host/src/tui/app/bot.rs
index f9a9fdc6..5c5182a1 100644
--- a/host/src/tui/app/bot.rs
+++ b/host/src/tui/app/bot.rs
@@ -165,7 +165,7 @@ impl Bot {
if self.managed_workspace { "personal workspace".to_owned() } else { tilde(&self.cwd, home) }
}
- pub(super) fn parse(v: &Value) -> Option<Self> {
+ pub(in crate::tui) fn parse(v: &Value) -> Option<Self> {
let s = |k: &str| v[k].as_str().unwrap_or_default().to_owned();
Some(Self {
id: v["id"].as_str()?.to_owned(),
diff --git a/host/src/tui/manage/dev_servers.rs b/host/src/tui/manage/dev_servers.rs
index f8ab311e..ce900936 100644
--- a/host/src/tui/manage/dev_servers.rs
+++ b/host/src/tui/manage/dev_servers.rs
@@ -50,6 +50,23 @@ impl DevServer {
self.status == Status::Running && !self.ports.is_empty()
}
+ /// The port to use: on its computer the first, what a browser there opens; elsewhere the first that other devices
+ /// can reach, or the first if none listens beyond its computer.
+ fn port_from(&self, here: bool) -> Option<&DevServerPort> {
+ let beyond = if here { None } else { self.ports.iter().find(|port| !port.remote.is_empty()) };
+ beyond.or_else(|| self.ports.first())
+ }
+
+ /// Where it can be reached from elsewhere, a line each: every address, since this device may reach only some of them.
+ pub fn reachable(&self) -> Vec<String> {
+ let Some(port) = self.port_from(false).filter(|_| self.opens()) else { return Vec::new() };
+ if port.remote.is_empty() {
+ vec![format!("{} · {}", port.local, tr(ONLY_ON_COMPUTER))]
+ } else {
+ port.remote.clone()
+ }
+ }
+
fn restarts(&self) -> bool {
self.managed && self.status != Status::Starting
}
@@ -209,21 +226,17 @@ impl App {
/// In this computer's browser. Anywhere else (a tunnel looks the same from here) shows where it can be reached.
fn open_dev_server(&mut self, server: &DevServer) {
- let Some(port) = server.ports.first() else { return };
- if self.on_this_computer && open_browser(&port.local, &self.url) {
+ if self.on_this_computer && server.port_from(true).is_some_and(|port| open_browser(&port.local, &self.url)) {
self.track_dev_server(DevServerAction::Open);
return;
}
- let address = match port.remote.first() {
- Some(address) => address.clone(),
- None => format!("{} · {}", port.local, tr(ONLY_ON_COMPUTER)),
- };
- self.hint = Some((address, std::time::Instant::now() + std::time::Duration::from_secs(5)));
+ self.hint =
+ Some((server.reachable().join(" · "), std::time::Instant::now() + std::time::Duration::from_secs(5)));
}
fn copy_dev_server(&mut self, server: &DevServer) {
- let Some(port) = server.ports.first() else { return };
let here = self.on_this_computer;
+ let Some(port) = server.port_from(here) else { return };
copy(if here { &port.local } else { port.remote.first().unwrap_or(&port.local) });
self.track_dev_server(DevServerAction::Copy);
self.flash(if here || !port.remote.is_empty() { "Copied" } else { ONLY_ON_COMPUTER });
@@ -236,7 +249,7 @@ impl App {
#[cfg(test)]
mod tests {
- use super::{DevServer, DevServerPort, DevServerSummary, Status, summary};
+ use super::{DevServer, DevServerPort, DevServerSummary, Status, summary, tr};
fn server(status: Status, port: Option<u16>) -> DevServer {
DevServer {
@@ -267,6 +280,43 @@ mod tests {
assert_eq!(summary(&[failed, server(Status::Running, Some(1))]), Some(DevServerSummary::Running(":1".into())));
}
+ #[test]
+ fn elsewhere_it_shows_every_address_or_says_it_stays_on_the_computer() {
+ let port = |remote: &[&str]| DevServerPort {
+ port: 5173,
+ local: "http://localhost:5173".into(),
+ remote: remote.iter().map(ToString::to_string).collect(),
+ };
+ let with = |ports| DevServer { ports, ..server(Status::Running, None) };
+ let (tailscale, lan) = ("http://100.64.0.1:5173", "http://192.168.1.20:5173");
+ assert_eq!(with(vec![port(&[lan])]).reachable(), [lan]);
+ assert_eq!(with(vec![port(&[tailscale, lan])]).reachable(), [tailscale, lan]);
+ let only_here = with(vec![port(&[])]).reachable();
+ assert!(only_here[0].starts_with("http://localhost:5173 · "), "{only_here:?}");
+ // The first port listens only on the computer; the second doesn't.
+ assert_eq!(with(vec![port(&[]), port(&[lan])]).reachable(), [lan]);
+ assert!(with(vec![]).reachable().is_empty());
+ let stopped = DevServer { ports: vec![port(&[lan])], ..server(Status::Stopped, None) };
+ assert!(stopped.reachable().is_empty());
+ }
+
+ #[test]
+ fn on_its_computer_it_uses_the_first_port_and_elsewhere_the_first_others_can_reach() {
+ let port = |port, remote: &[&str]| DevServerPort {
+ port,
+ remote: remote.iter().map(ToString::to_string).collect(),
+ ..Default::default()
+ };
+ let mixed = DevServer {
+ ports: vec![port(3000, &[]), port(5173, &["http://192.168.1.20:5173"])],
+ ..server(Status::Running, None)
+ };
+ assert_eq!(mixed.port_from(true).map(|p| p.port), Some(3000));
+ assert_eq!(mixed.port_from(false).map(|p| p.port), Some(5173));
+ let only_here = DevServer { ports: vec![port(3000, &[])], ..server(Status::Running, None) };
+ assert_eq!(only_here.port_from(false).map(|p| p.port), Some(3000));
+ }
+
#[test]
fn the_footer_offers_only_the_keys_that_apply() {
let keys = |server: &DevServer| server.key_hints().join(" · ");
@@ -297,9 +347,10 @@ mod tests {
#[test]
fn the_sheet_says_how_it_ended_or_that_it_ends_with_the_bot() {
let failed = DevServer { exit_code: Some(3), ..server(Status::Failed, None) };
- assert_eq!(failed.note(), "Exit code 3");
+ // Through `tr`: another test may have set the process's language.
+ assert_eq!(failed.note(), tr("Exit code {code}").replace("{code}", "3"));
assert_eq!(server(Status::Running, None).note(), "");
let shell = DevServer { managed: false, ..server(Status::Running, None) };
- assert_eq!(shell.note(), "Started through the bot's shell: it stops with the bot");
+ assert_eq!(shell.note(), tr("Started through the bot's shell: it stops with the bot"));
}
}
diff --git a/host/src/tui/view/dev_servers.rs b/host/src/tui/view/dev_servers.rs
index 8ca94067..850eb4d9 100644
--- a/host/src/tui/view/dev_servers.rs
+++ b/host/src/tui/view/dev_servers.rs
@@ -5,8 +5,8 @@ use ratatui::layout::Rect;
use super::super::app::{App, Bot, Click};
use super::super::l10n::tr;
-use super::super::manage::{DevServerSummary, DevServersSheet, LogsView, dev_server_summary};
-use super::buffer::{centered, frame_box, hline, put, rput};
+use super::super::manage::{DevServer, DevServerSummary, DevServersSheet, LogsView, dev_server_summary};
+use super::buffer::{centered, frame_box, hline, put, rput, u};
use super::style::theme;
use crate::dev_servers::Status;
@@ -37,14 +37,18 @@ pub(super) fn dev_servers(buf: &mut Buffer, area: Rect, app: &App, sheet: &DevSe
fn list(buf: &mut Buffer, area: Rect, app: &App, sheet: &DevServersSheet) {
let t = theme();
let servers = app.bots.get(&sheet.bot).map(|bot| bot.dev_servers.as_slice()).unwrap_or_default();
- let height = u16::try_from(servers.len()).unwrap_or(u16::MAX).saturating_add(7);
+ let selected = sheet.selected.min(servers.len().saturating_sub(1));
+ let server = servers.get(selected);
+ // Anywhere else its addresses stay on screen: a hint fades and cuts them off, and this device may reach only some.
+ let addresses = server.filter(|_| !app.on_this_computer).map(DevServer::reachable).unwrap_or_default();
+ let height = u(servers.len() + addresses.len()).saturating_add(7);
let r = centered(area, WIDTH, height.min(area.height.saturating_sub(2)));
let inner = frame_box(buf, r, t.text, t.panel, Some((&tr("Dev servers"), t.text)));
if inner.height < 4 {
return;
}
- let selected = sheet.selected.min(servers.len().saturating_sub(1));
- let rows = usize::from(inner.height.saturating_sub(3));
+ let address_lines = u(addresses.len()).min(inner.height - 4);
+ let rows = usize::from(inner.height - 3 - address_lines);
for (i, server) in servers.iter().take(rows).enumerate() {
let y = inner.y + u16::try_from(i).unwrap_or(0);
let chosen = i == selected;
@@ -58,7 +62,11 @@ fn list(buf: &mut Buffer, area: Rect, app: &App, sheet: &DevServersSheet) {
put(buf, inner.x + 21, y, 20, &tr(&server.value()), style.patch(row));
put(buf, inner.x + 42, y, inner.width.saturating_sub(42), &server.command, t.dim.patch(row));
}
- let Some(server) = servers.get(selected) else { return };
+ let Some(server) = server else { return };
+ let first_address = inner.bottom() - 3 - address_lines;
+ for (y, address) in (first_address..inner.bottom() - 3).zip(&addresses) {
+ put(buf, inner.x + 2, y, inner.width.saturating_sub(2), address, t.dim.patch(t.panel));
+ }
put(buf, inner.x + 2, inner.bottom() - 3, inner.width.saturating_sub(2), &server.note(), t.dim.patch(t.panel));
hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
let keys: Vec<String> = server.key_hints().into_iter().map(|key| tr(key).into_owned()).collect();
@@ -96,3 +104,40 @@ fn log_view(buf: &mut Buffer, area: Rect, logs: &LogsView) {
hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
put(buf, inner.x, inner.bottom() - 1, inner.width, &tr(" ↑↓ scroll · r refresh · esc back"), t.dim.patch(t.panel));
}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+ use crate::tui::app::test_app;
+
+ #[tokio::test]
+ async fn elsewhere_the_sheet_lists_every_address_of_the_selected_server_whole() {
+ let addresses = ["http://100.64.0.1:5173", "http://mac.tailnet-1234.ts.net:5173", "http://192.168.1.20:5173"];
+ let server = json!({"id": "a", "name": "web", "command": "npm run dev", "status": "running", "managed": true,
+ "ports": [{"port": 5173, "local": "http://localhost:5173", "remote": addresses}]});
+ let mut app = test_app();
+ let bot = json!({"id": "b", "name": "Bot", "devServers": [server]});
+ app.bots.insert("b".into(), Bot::parse(&bot).expect("a bot with servers parses"));
+ let sheet = DevServersSheet { bot: "b".into(), selected: 0, logs: None };
+ let area = Rect::new(0, 0, 100, 24);
+ let screen = |app: &App| {
+ let mut buf = Buffer::empty(area);
+ list(&mut buf, area, app, &sheet);
+ (0..area.height)
+ .map(|y| (0..area.width).map(|x| buf[(x, y)].symbol()).collect::<String>())
+ .collect::<Vec<_>>()
+ };
+
+ app.on_this_computer = false;
+ let lines = screen(&app);
+ let at = |address: &str| lines.iter().position(|line| line.contains(address));
+ let rows: Vec<_> = addresses.iter().map(|address| at(address).expect("the whole address shows")).collect();
+ assert_eq!(rows, [rows[0], rows[0] + 1, rows[0] + 2], "one line each");
+ assert!(at("npm run dev") < Some(rows[0]), "under the servers");
+
+ app.on_this_computer = true;
+ assert!(!screen(&app).concat().contains("100.64.0.1"), "a browser opens here");
+ }
+}
diff --git a/web/content/docs/dev-servers.mdx b/web/content/docs/dev-servers.mdx
index f4883454..1b48078f 100644
--- a/web/content/docs/dev-servers.mdx
+++ b/web/content/docs/dev-servers.mdx
@@ -40,6 +40,8 @@ A server's command and logs show in your apps, on all your devices. Keep secrets
Most dev servers listen only on the computer they run on, so a phone can't reach them, and the menu says **Only reachable on the computer**. To open one from your phone, ask the bot to run it on all interfaces (for Vite, `npm run dev -- --host`). Your phone must be able to reach your computer directly, on the same Wi-Fi or over Tailscale.
+A tap opens the first address your computer has. If that one doesn't load (it's a Tailscale address and this device isn't on Tailscale), the **⋯** menu lists every address to try. The desktop app does the same for a computer attached over SSH, and the terminal UI shows them all.
+
On all interfaces, anyone who can reach your computer on that network can open the server, and most dev servers have no sign-in. On shared Wi-Fi or a machine with a public address, that means strangers. Stay on Tailscale there, with a firewall that keeps the port closed elsewhere, or keep the default and open the server on the computer.
## When they stop