Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion mobile/src/host-screen/host-screen-header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
} from 'lucide-react-native'
import { StatusDot } from '../components/StatusDot'
import { classifyConnection, type ConnectionVerdict } from '../transport/connection-health'
import { useCalmConnectionState } from '../transport/calm-connection-state'
import { colors } from '../theme/mobile-theme'
import { hostScreenStyles as styles } from './host-screen-styles'
import type { HostScreenController } from './use-host-screen-controller'
Expand All @@ -39,6 +40,8 @@ export function HostScreenHeader({ controller }: { controller: HostScreenControl
relayRecovery,
state
} = controller
// Why: a drop healed in a few seconds must not flash the host dot amber.
const presentedConnState = useCalmConnectionState(connState, lastConnectedAt)

return (
<View style={styles.topChrome}>
Expand All @@ -64,7 +67,11 @@ export function HostScreenHeader({ controller }: { controller: HostScreenControl
<>
<View style={styles.hostIdentity}>
<View style={styles.hostIdentityLine}>
<StatusDot state={connState} verdict={headerVerdict} />
{presentedConnState !== connState && !isErrorVerdict(headerVerdict) ? (
<StatusDot state={presentedConnState} />
) : (
<StatusDot state={connState} verdict={headerVerdict} />
)}
<Text style={styles.hostNameText} numberOfLines={1}>
{hostDisplay.title}
</Text>
Expand Down
4 changes: 2 additions & 2 deletions mobile/src/session/MobileSessionHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC
hostId,
isFolderWorkspaceRoute,
isFloatingWorkspaceRoute,
connState,
presentedConnState,
forceReconnectHost,
worktreeName,
activePanel,
Expand Down Expand Up @@ -66,7 +66,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC
accessibilityRole={showConnectionRetry ? 'button' : undefined}
accessibilityLabel={showConnectionRetry ? 'Reconnect to desktop' : undefined}
>
<StatusDot state={connState} />
<StatusDot state={presentedConnState} />
<Text style={styles.sessionMetaText} numberOfLines={1}>
{terminalSummary}
</Text>
Expand Down
8 changes: 6 additions & 2 deletions mobile/src/session/use-mobile-session-presentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useInitialSessionTerminalAutoCreate } from './use-initial-session-termi
import { MOBILE_SESSION_STATUS_LABELS } from './mobile-session-route-helpers'
import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close'
import { hostOs } from '../platform/host-os'
import { useCalmConnectionState } from '../transport/calm-connection-state'

export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) {
const {
Expand Down Expand Up @@ -61,8 +62,10 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel)
// Not on the page: the shell owns the connection and the tap could only do nothing.
const showConnectionRetry = connectionEscalated && forceReconnectHost !== null

// Why: a drop the client heals in a few seconds must not flip the header to Reconnecting and back.
const presentedConnState = useCalmConnectionState(connState, lastConnectedAt)
const terminalSummary =
connState === 'connected'
presentedConnState === 'connected'
? showLoadingState
? 'Loading tabs'
: visibleTabs.length === 1
Expand All @@ -72,7 +75,7 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel)
? `${verdictDisplayLabel(connectionVerdict)} — tap to retry`
: connectionEscalated
? verdictDisplayLabel(connectionVerdict)
: MOBILE_SESSION_STATUS_LABELS[connState]
: MOBILE_SESSION_STATUS_LABELS[presentedConnState]

// Why: iOS keyboard height includes the home-indicator inset; Android IME height does not.
const keyboardLift =
Expand All @@ -91,6 +94,7 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel)
transform: [{ translateY: -keyboardLift }]
}
return {
presentedConnState,
showLoadingState,
showEmptyState,
connectionVerdict,
Expand Down
71 changes: 71 additions & 0 deletions mobile/src/transport/calm-connection-state.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest'
import {
CALM_STATUS_IDLE,
CALM_STATUS_REVEAL_DELAY_MS
} from '../../../src/shared/calm-status-reveal'
import { stepCalmConnectionState } from './calm-connection-state'
import type { ConnectionState } from './types'

function present(
lastConnectedAt: number | null,
events: { at: number; state: ConnectionState }[]
): ConnectionState[] {
let reveal = CALM_STATUS_IDLE
return events.map(({ at, state }) => {
const step = stepCalmConnectionState(reveal, { state, lastConnectedAt, now: at })
reveal = step.next
return step.presented
})
}

describe('stepCalmConnectionState', () => {
it('keeps the header connected through a reconnect that heals within the delay', () => {
expect(
present(0, [
{ at: 1_000, state: 'reconnecting' },
{ at: 2_000, state: 'handshaking' },
{ at: 3_500, state: 'connected' }
])
).toEqual(['connected', 'connected', 'connected'])
})

it('says Reconnecting once the drop outlasts the delay', () => {
expect(
present(0, [
{ at: 1_000, state: 'reconnecting' },
{ at: 1_000 + CALM_STATUS_REVEAL_DELAY_MS, state: 'reconnecting' }
])
).toEqual(['connected', 'reconnecting'])
})

it('shows the first connect and a refused pairing at once', () => {
expect(present(null, [{ at: 0, state: 'connecting' }])).toEqual(['connecting'])
expect(present(0, [{ at: 1_000, state: 'auth-failed' }])).toEqual(['auth-failed'])
})

it('shows a drop already under way when the screen opens long after the last connect', () => {
const step = stepCalmConnectionState(CALM_STATUS_IDLE, {
state: 'reconnecting',
lastConnectedAt: 0,
now: 10 * 60_000,
since: 0
})
expect(step.presented).toBe('reconnecting')
})

it('keeps a drop that just appeared on screen through its minimum time', () => {
let reveal = CALM_STATUS_IDLE
let shown: ConnectionState = 'connected'
const presented = [
{ at: 1_000, state: 'reconnecting' as const },
{ at: 1_000 + CALM_STATUS_REVEAL_DELAY_MS, state: 'reconnecting' as const },
{ at: 1_010 + CALM_STATUS_REVEAL_DELAY_MS, state: 'connected' as const }
].map(({ at, state }) => {
const step = stepCalmConnectionState(reveal, { state, lastConnectedAt: 0, now: at, shown })
reveal = step.next
shown = step.presented
return step.presented
})
expect(presented).toEqual(['connected', 'reconnecting', 'reconnecting'])
})
})
82 changes: 82 additions & 0 deletions mobile/src/transport/calm-connection-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { useEffect, useRef, useState } from 'react'
import {
CALM_STATUS_IDLE,
stepCalmStatusReveal,
type CalmStatusReveal
} from '../../../src/shared/calm-status-reveal'
import type { ConnectionState } from './types'

/**
* What the header shows for a connection: a drop after this session was connected reads as
* connected until it outlasts a clean reconnect, the same schedule the desktop banner uses.
* The first connect and a refused pairing show at once.
*/
export function stepCalmConnectionState(
previous: CalmStatusReveal,
input: {
state: ConnectionState
lastConnectedAt: number | null
now: number
/** On mount the drop already happened unseen; it began no earlier than the last connect. */
since?: number | null
/** What the header shows now; a drop on screen stays through its minimum time and hold. */
shown?: ConnectionState
}
): { next: CalmStatusReveal; presented: ConnectionState; recheckInMs: number | null } {
// Why 'disconnected' waits too: an app suspend publishes it and the resume redials at once.
const healing = input.state !== 'auth-failed' && input.lastConnectedAt !== null
const step = stepCalmStatusReveal(previous, {
down: input.state !== 'connected',
immediate: !healing,
now: input.now,
since: input.since
})
return {
next: step.next,
presented: !step.visible
? 'connected'
: input.state !== 'connected'
? input.state
: (input.shown ?? 'connected'),
recheckInMs: step.recheckInMs
}
}

export function useCalmConnectionState(
state: ConnectionState,
lastConnectedAt: number | null
): ConnectionState {
const revealRef = useRef<CalmStatusReveal>(CALM_STATUS_IDLE)
const [presented, setPresented] = useState<ConnectionState>(
() =>
stepCalmConnectionState(CALM_STATUS_IDLE, {
state,
lastConnectedAt,
now: Date.now(),
since: lastConnectedAt
}).presented
)
const [wake, setWake] = useState(0)
const observedRef = useRef(false)
const shownRef = useRef(presented)
useEffect(() => {
const step = stepCalmConnectionState(revealRef.current, {
state,
lastConnectedAt,
now: Date.now(),
// Why the last connect: the drop time is unseen on mount; erring early shows a real outage at once.
since: observedRef.current ? null : lastConnectedAt,
shown: shownRef.current
})
observedRef.current = true
revealRef.current = step.next
shownRef.current = step.presented
setPresented(step.presented)
if (step.recheckInMs === null) {
return
}
const timer = setTimeout(() => setWake((count) => count + 1), Math.max(0, step.recheckInMs))
return () => clearTimeout(timer)
}, [state, lastConnectedAt, wake])
return presented
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { useEffect, useState } from 'react'
import { Clock, KeyRound, ServerOff } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { tailscalePingCommand } from '../../../../shared/remote-runtime/remote-runtime-tailscale-hint'
import {
remoteRuntimeDownForLabel,
remoteRuntimeTailscaleHintLabel
} from './remote-runtime-recovery-copy'

function useNow(active: boolean): number {
const [now, setNow] = useState(() => Date.now())
useEffect(() => {
if (!active) {
return
}
setNow(Date.now())
const timer = setInterval(() => setNow(Date.now()), 1_000)
return () => clearInterval(timer)
}, [active])
return now
}

/** The one look for "this remote work is recovering", shared by the pane and server notices. */
export function RemoteRuntimeRecoveryCard({
icon,
title,
body,
downSince = null,
tailscaleHost = null,
action = null,
data
}: {
icon: 'retrying' | 'waiting' | 'sign-in' | 'stopped'
title: string
body: string
downSince?: number | null
tailscaleHost?: string | null
action?: { label: string; onClick: () => void } | null
data: Record<`data-${string}`, string>
}): React.JSX.Element {
const now = useNow(downSince !== null)
return (
<div
className="pointer-events-none absolute inset-x-3 bottom-3 z-30 flex justify-center"
{...data}
>
<div
className="pointer-events-auto flex w-full max-w-xl items-center gap-3 rounded-md border border-border bg-card/95 px-3 py-3 text-card-foreground shadow-xs backdrop-blur-[1px]"
role="status"
aria-live="polite"
>
<div className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border bg-muted text-muted-foreground">
{icon === 'retrying' ? (
<LoadingSpinner className="size-4" />
) : icon === 'sign-in' ? (
<KeyRound className="size-4" />
) : icon === 'waiting' ? (
<Clock className="size-4" />
) : (
<ServerOff className="size-4" />
)}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-baseline gap-2">
<div className="min-w-0 truncate text-sm font-semibold">{title}</div>
{downSince !== null ? (
// Why hidden: a per-second tick inside the live region would re-announce the whole card.
<div
aria-hidden="true"
className="ml-auto shrink-0 text-xs tabular-nums text-muted-foreground"
>
{remoteRuntimeDownForLabel(now - downSince)}
</div>
) : null}
</div>
<div className="mt-0.5 text-xs leading-5 text-muted-foreground">{body}</div>
{tailscaleHost ? (
<div className="mt-1 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground">
<span className="shrink-0">{remoteRuntimeTailscaleHintLabel()}</span>
<code className="min-w-0 truncate rounded-sm bg-muted px-1.5 py-0.5 font-mono select-text">
{tailscalePingCommand(tailscaleHost)}
</code>
</div>
) : null}
</div>
{action ? (
<Button size="sm" onClick={action.onClick}>
{action.label}
</Button>
) : null}
</div>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useAppStore } from '@/store'
import type { CalmStatusView } from '@/hooks/use-calm-status-reveal'
import { RemoteRuntimeRecoveryCard } from './RemoteRuntimeRecoveryCard'
import { remoteRuntimeRecoveryCopy } from './remote-runtime-recovery-copy'
import {
selectRemoteServerOutageCause,
selectRuntimeServerName,
selectRuntimeServerTailscaleHost
} from './remote-server-outage'

/**
* The one notice for a server whose shared connection dropped and is retrying, in place of a
* banner in every pane. The surface owns `reveal`, so its panes stay quiet for as long as this shows.
*/
export function RemoteServerOutageNotice({
environmentId,
reveal
}: {
environmentId: string
reveal: CalmStatusView
}): React.JSX.Element | null {
const serverName = useAppStore((state) => selectRuntimeServerName(state, environmentId))
const cause = useAppStore((state) => selectRemoteServerOutageCause(state, environmentId))
const tailscaleHost = useAppStore((state) =>
selectRuntimeServerTailscaleHost(state, environmentId)
)
if (!reveal.visible) {
return null
}
const copy = remoteRuntimeRecoveryCopy(cause, serverName)
return (
<RemoteRuntimeRecoveryCard
icon="retrying"
data={{
'data-remote-server-outage-notice': environmentId,
'data-terminal-remote-runtime-recovery-cause': cause
}}
title={copy.title}
body={copy.body}
downSince={reveal.downSince}
tailscaleHost={cause === 'connection-lost' ? tailscaleHost : null}
/>
)
}
Loading
Loading