Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

fix(relay): diagnose desktop clock drift (#36139)

Kelvin Amoabaa874ff9d76b7
diff --git a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts
index 74fb230d7b6..b47769e8717 100644
--- a/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts
+++ b/src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts
@@ -13,7 +13,7 @@ import { relayIdentityKey } from './relay-auth-identity'
import { RelayAuthCoordinator } from './relay-auth-coordinator'
import { RelayUnavailableError } from './relay-readiness'
import { RelaySessionBroker } from './relay-session-broker'
-import type { RelayBrokerStatus } from './relay-session-broker-contract'
+import type { MobileRelayStatusPublisher } from '../../../shared/mobile-relay-status'
import type { PairingRelay } from '../../../shared/mobile-relay-pairing-offer'
import type {
RelayRevokeOutbox,
@@ -30,7 +30,7 @@ type DesktopRelayServiceOptions = {
userDataPath: string
appVersion: string
runtimeRpc: OrcaRuntimeRpcServer
- onStatus: (status: RelayBrokerStatus, cellUrl?: string) => void
+ onStatus: MobileRelayStatusPublisher
}
// Revive dead brokers lacking retry timers (sleep/token expiry) without requiring user Retry.
diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts
index 56f7e29a660..fb3a22fb6c1 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.test.ts
@@ -45,11 +45,19 @@ describe('RelayAuthCoordinator', () => {
coordinator.reconcile()
await coordinator.waitForLiveBroker()
- expect(onStatus).toHaveBeenLastCalledWith('registered', 'https://c27.relay.example.test')
+ expect(onStatus).toHaveBeenLastCalledWith(
+ 'registered',
+ 'https://c27.relay.example.test',
+ undefined
+ )
coordinator.reconcile()
await coordinator.waitForLiveBroker()
- expect(onStatus).toHaveBeenLastCalledWith('registered', 'https://c27.relay.example.test')
+ expect(onStatus).toHaveBeenLastCalledWith(
+ 'registered',
+ 'https://c27.relay.example.test',
+ undefined
+ )
})
it('drops the cell from every status the host is not served on', async () => {
@@ -69,10 +77,10 @@ describe('RelayAuthCoordinator', () => {
demanded = false
coordinator.reconcile()
await vi.advanceTimersByTimeAsync(0)
- expect(onStatus).toHaveBeenLastCalledWith('standby', undefined)
+ expect(onStatus).toHaveBeenLastCalledWith('standby', undefined, undefined)
coordinator.fenceAndCloseNow()
- expect(onStatus).toHaveBeenLastCalledWith('offline', undefined)
+ expect(onStatus).toHaveBeenLastCalledWith('offline', undefined, undefined)
for (const [status, cellUrl] of onStatus.mock.calls) {
expect(status === 'registered' || cellUrl === undefined).toBe(true)
}
diff --git a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts
index ebdf772f960..19953406bbc 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-auth-coordinator.ts
@@ -2,13 +2,16 @@ import {
RELAY_HOST_CLOSE_REASON,
type RelayHostCloseReason
} from '../../../shared/relay-host-close-reason'
-import { relayStatusCellUrl } from '../../../shared/mobile-relay-status'
+import {
+ relayStatusCellUrl,
+ type MobileRelayStatusPublisher
+} from '../../../shared/mobile-relay-status'
import type { RelayBrokerStatus, RelayAccessTokenRefresh } from './relay-session-broker-contract'
import { shouldRetryRelayConnectionError } from './relay-http-client'
import {
RelayReadinessWaiters,
relayRetryFloorMs,
- relayUnavailableReasonFor,
+ relayUnavailableFor,
type RelayUnavailable
} from './relay-readiness'
import { RelayRetrySchedule } from './relay-retry-schedule'
@@ -29,7 +32,7 @@ type RelayAuthCoordinatorOptions = {
isCurrent: () => boolean
refreshAccessToken: () => Promise<RelayAccessTokenRefresh>
}) => Promise<CoordinatedRelayBroker>
- onStatus: (status: RelayBrokerStatus, cellUrl?: string) => void
+ onStatus: MobileRelayStatusPublisher
lingerMs?: number
random?: () => number
}
@@ -50,19 +53,17 @@ function authLossCloseReason(context: RelayAuthContext | null): RelayHostCloseRe
}
export class RelayAuthCoordinator {
- private readonly options: RelayAuthCoordinatorOptions
private authEpoch = 0
private ownership: BrokerOwnership | null = null
private readonly pendingOwnerships = new Set<BrokerOwnership>()
private latestReconcile: Promise<void> = Promise.resolve()
private readonly linger = new RelayLingerTimer()
private readonly retry: RelayRetrySchedule
- private unavailableReason: RelayUnavailable['reason'] | null = null
+ private unavailable: Omit<RelayUnavailable, 'retryAt'> = { reason: 'control_not_active' }
private readonly readinessWaiters = new RelayReadinessWaiters()
private stopped = false
- constructor(options: RelayAuthCoordinatorOptions) {
- this.options = options
+ constructor(private readonly options: RelayAuthCoordinatorOptions) {
this.retry = new RelayRetrySchedule(options.random)
}
@@ -80,9 +81,7 @@ export class RelayAuthCoordinator {
}
const epoch = ++this.authEpoch
this.invalidatePendingOwnerships()
- const reconcile = this.reconcileEpoch(epoch, expectedIdentityKey)
- this.latestReconcile = reconcile
- void reconcile
+ this.latestReconcile = this.reconcileEpoch(epoch, expectedIdentityKey)
}
// Name only auth loss to phones; quit/relaunch fences retain abrupt, cause-free closure.
@@ -93,8 +92,10 @@ export class RelayAuthCoordinator {
this.retry.reset()
this.invalidatePendingOwnerships()
this.invalidateOwnership(hostCloseReason)
- this.unavailableReason =
- hostCloseReason === RELAY_HOST_CLOSE_REASON.SIGNED_OUT ? 'signed_out' : null
+ this.unavailable = {
+ reason:
+ hostCloseReason === RELAY_HOST_CLOSE_REASON.SIGNED_OUT ? 'signed_out' : 'control_not_active'
+ }
this.readinessWaiters.releaseAll()
this.publish('offline')
}
@@ -103,7 +104,8 @@ export class RelayAuthCoordinator {
private publish(status: RelayBrokerStatus): void {
this.options.onStatus(
status,
- relayStatusCellUrl(status, this.ownership?.broker?.endpoint?.cellUrl)
+ relayStatusCellUrl(status, this.ownership?.broker?.endpoint?.cellUrl),
+ status === 'offline' || status === 'connecting' ? this.unavailable.clockOffsetMs : undefined
)
}
@@ -131,8 +133,9 @@ export class RelayAuthCoordinator {
readiness(): RelayReadiness {
const broker = this.getLiveBroker()
- const reason = this.unavailableReason ?? 'control_not_active'
- return broker ? { ready: true, broker } : { ready: false, reason, retryAt: this.retry.retryAt }
+ return broker
+ ? { ready: true, broker }
+ : { ready: false, ...this.unavailable, retryAt: this.retry.retryAt }
}
async waitForLiveBroker(): Promise<CoordinatedRelayBroker | null> {
@@ -183,14 +186,14 @@ export class RelayAuthCoordinator {
this.linger.cancel()
this.retry.reset()
this.invalidateOwnership(authLossCloseReason(context))
- this.unavailableReason = context ? 'not_entitled' : 'signed_out'
+ this.unavailable = { reason: context ? 'not_entitled' : 'signed_out' }
this.publish('offline')
return
}
const nextIdentityKey = relayIdentityKey(context.identity)
if (expectedIdentityKey && nextIdentityKey !== expectedIdentityKey) {
this.retry.reset()
- this.unavailableReason = 'identity_changed'
+ this.unavailable = { reason: 'identity_changed' }
this.publish('offline')
return
}
@@ -212,7 +215,7 @@ export class RelayAuthCoordinator {
(this.ownership.broker?.isLive?.() ?? true)
) {
this.retry.reset()
- this.unavailableReason = null
+ this.unavailable = { reason: 'control_not_active' }
this.publish('registered')
return
}
@@ -246,7 +249,7 @@ export class RelayAuthCoordinator {
}
this.ownership = ownership
this.retry.reset()
- this.unavailableReason = null
+ this.unavailable = { reason: 'control_not_active' }
this.publish('registered')
} catch (error) {
if (this.isEpochCurrent(epoch)) {
@@ -254,7 +257,7 @@ export class RelayAuthCoordinator {
'[relay] broker reconcile failed:',
error instanceof Error ? error.message : String(error)
)
- this.unavailableReason = relayUnavailableReasonFor(error)
+ this.unavailable = relayUnavailableFor(error)
this.publish('offline')
if (shouldRetryRelayConnectionError(error)) {
const retryAfterMs = relayRetryFloorMs(error, this.retry.attempts)
diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts b/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts
index aa6f1df4209..588b89ff319 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-control-client.test.ts
@@ -7,6 +7,9 @@ import { WebSocketServer, type WebSocket } from 'ws'
import type { E2EEKeypair } from '../e2ee-keypair'
import { MOBILE_RELAY_CLOSE_CODE } from '../../../shared/mobile-relay-close-codes'
import { RelayControlClient } from './relay-control-client'
+import { RelayAuthCoordinator } from './relay-auth-coordinator'
+import { RelayUnavailableError } from './relay-readiness'
+import { mobileRelayMintFailureFromUnknown } from '../../../shared/mobile-relay-mint-failure'
const encoder = new TextEncoder()
@@ -588,12 +591,59 @@ describe('RelayControlClient scripted-socket lifecycle', () => {
expect(client.isLive()).toBe(true)
})
- it('rejects a challenge issued beyond the clock tolerance', async () => {
- const { client } = scriptedControl({ issuedAtOffsetMs: 45_000 })
-
- await expect(client.connect()).rejects.toThrow('invalid host challenge')
- expect(client.isLive()).toBe(false)
- })
+ it.each([38_000, -45_000])(
+ 'preserves clock drift of %i ms through readiness, status and serialized pairing failure',
+ async (issuedAtOffsetMs) => {
+ vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
+ let currentOffsetMs = issuedAtOffsetMs
+ const onStatus = vi.fn()
+ const coordinator = new RelayAuthCoordinator({
+ readContext: async () => ({
+ identity: { userId: 'user-1', profileId: 'profile-1', organizationId: 'org-1' },
+ accessToken: 'access-1',
+ relayEntitled: true
+ }),
+ openBroker: async () => {
+ const { client } = scriptedControl({ issuedAtOffsetMs: currentOffsetMs })
+ await client.connect()
+ return client
+ },
+ onStatus,
+ random: () => 1
+ })
+ try {
+ coordinator.reconcile()
+ const readiness = await coordinator.waitForReadiness(0)
+ expect(readiness.ready).toBe(false)
+ if (readiness.ready) {
+ throw new Error('expected clock failure')
+ }
+ const failure = mobileRelayMintFailureFromUnknown({
+ error: new RelayUnavailableError(readiness),
+ stage: 'create_pairing_relay',
+ fallbackCode: 'relay_mint_failed',
+ fallbackMessage: 'Relay pairing invite request failed'
+ })
+ expect(readiness).toMatchObject({
+ reason: 'clock_skew',
+ clockOffsetMs: -issuedAtOffsetMs
+ })
+ expect(failure).toMatchObject({
+ code: 'relay_clock_skew',
+ clockOffsetMs: -issuedAtOffsetMs
+ })
+ expect(onStatus).toHaveBeenLastCalledWith('offline', undefined, -issuedAtOffsetMs)
+ currentOffsetMs = 0
+ coordinator.reconcile()
+ await coordinator.waitForLiveBroker()
+ expect(coordinator.readiness()).toMatchObject({ ready: true })
+ expect(onStatus).toHaveBeenLastCalledWith('registered', undefined, undefined)
+ } finally {
+ coordinator.stop()
+ vi.restoreAllMocks()
+ }
+ }
+ )
it('terminates a silent control after the silence limit and reports closure', async () => {
vi.useFakeTimers()
diff --git a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts b/src/main/runtime/mobile-cloud-relay/relay-control-client.ts
index 07bdfda47ee..bf90efa30e8 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-control-client.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-control-client.ts
@@ -28,7 +28,6 @@ type RelayControlState = 'idle' | 'opening' | 'proving' | 'active' | 'draining'
const RELAY_CONTROL_CONNECT_DEADLINE_MS = 15_000
export class RelayControlClient {
- private readonly options: RelayControlClientOptions
private readonly relayOrigin: string
private readonly controlUrl: string
private readonly createSocket: NonNullable<RelayControlClientOptions['createSocket']>
@@ -41,8 +40,7 @@ export class RelayControlClient {
private connectTimer: ReturnType<typeof setTimeout> | null = null
private controlErrorCode: string | null = null
- constructor(options: RelayControlClientOptions) {
- this.options = options
+ constructor(private readonly options: RelayControlClientOptions) {
const endpoint = controlWebSocketUrl(options.cellUrl)
this.relayOrigin = endpoint.origin
this.controlUrl = endpoint.url
@@ -236,7 +234,7 @@ export class RelayControlClient {
private handleProofMessage(message: Record<string, unknown>): void {
const challenge = RelayHostChallengeMessageSchema.safeParse(message)
if (challenge.success) {
- let invalidReason = 'unknown'
+ const invalid: { reason: string | Error } = { reason: 'unknown' }
const proofB64 = answerRelayHostChallenge(challenge.data, {
relayOrigin: this.relayOrigin,
...this.options.identity,
@@ -246,13 +244,17 @@ export class RelayControlClient {
assignmentEpoch: this.options.assignmentEpoch,
previousGeneration: this.options.previousGeneration,
resumeRequested: Boolean(this.options.controlResumeSecret),
- onInvalid: (reason) => {
- invalidReason = reason
+ onInvalid: (reason, error) => {
+ invalid.reason = error ?? reason
}
})
if (!proofB64) {
// Report failing check names, never challenge field values.
- this.failProtocol(`invalid host challenge: ${invalidReason} origin=${this.relayOrigin}`)
+ this.failProtocol(
+ invalid.reason instanceof Error
+ ? invalid.reason
+ : `invalid host challenge: ${invalid.reason} origin=${this.relayOrigin}`
+ )
return
}
this.socket?.send(
@@ -282,10 +284,10 @@ export class RelayControlClient {
this.socket.send(JSON.stringify(payload))
}
- private failProtocol(reason: string): void {
- this.connectReject?.(new Error(reason))
+ private failProtocol(reason: string | Error): void {
+ this.connectReject?.(reason instanceof Error ? reason : new Error(reason))
this.clearConnectPromise()
- this.socket?.close(MOBILE_RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, reason)
+ this.socket?.close(MOBILE_RELAY_CLOSE_CODE.BAD_OUTER_CREDENTIAL, String(reason))
}
private handleClose(code: number): void {
diff --git a/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts b/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts
index 39e47e322b2..7097ceb40a3 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-host-proof.test.ts
@@ -201,16 +201,28 @@ describe('answerRelayHostChallenge clock skew (#10401)', () => {
expect(answerRelayHostChallenge(ahead.challenge, ahead.context)).toBeNull()
})
- it('still rejects an oversized server challenge window', () => {
- const issuedAt = 1_700_000_000_000
- const expiresAt = issuedAt + 10_001
- const { challenge, context } = buildChallengeFixture({
- issuedAt,
- expiresAt,
- localNow: issuedAt
- })
- expect(answerRelayHostChallenge(challenge, context)).toBeNull()
- })
+ it.each([0, -38_000])(
+ 'rejects an oversized window without diagnosing drift of %i ms',
+ (offsetMs) => {
+ const issuedAt = 1_700_000_000_000
+ const expiresAt = issuedAt + 10_001
+ const { challenge, context } = buildChallengeFixture({
+ issuedAt,
+ expiresAt,
+ localNow: issuedAt + offsetMs
+ })
+ let clockFailure: Error | undefined
+ expect(
+ answerRelayHostChallenge(challenge, {
+ ...context,
+ onInvalid: (_reason, error) => {
+ clockFailure = error
+ }
+ })
+ ).toBeNull()
+ expect(clockFailure).toBeUndefined()
+ }
+ )
it('rejects a challenge that expires before it is issued', () => {
const issuedAt = 1_700_000_000_000
diff --git a/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts b/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts
index 5aa9005ee74..1bd8ef080d9 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-host-proof.ts
@@ -14,6 +14,12 @@ const HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-relay-host-challenge/v1'
const RELAY_HOST_PROOF_CLOCK_SKEW_MS = 30_000
const MAX_HOST_PROOF_CHALLENGE_WINDOW_MS = 10_000
+export class RelayHostProofClockSkewError extends Error {
+ constructor(readonly clockOffsetMs: number) {
+ super(`invalid host challenge: clock_skew(offset=${clockOffsetMs}ms)`)
+ }
+}
+
export type RelayHostChallenge = {
challengeId: string
relayEphemeralPublicKeyB64: string
@@ -34,7 +40,7 @@ export type RelayHostProofContext = {
previousGeneration?: number
resumeRequested: boolean
now?: () => number
- onInvalid?: (reason: string) => void
+ onInvalid?: (reason: string, error?: RelayHostProofClockSkewError) => void
}
function validateTranscript(
@@ -57,17 +63,8 @@ function validateTranscript(
context.previousGeneration === undefined
? new Uint8Array()
: encodeUint64(context.previousGeneration)
- // Report check names and relative deltas only; retain the 30s skew bound.
const checks: [string, boolean][] = [
['issuedAt-readable', issuedAt !== null],
- [
- `issuedAt-not-future(d=${issuedAt === null ? 'n/a' : issuedAt - now}ms)`,
- issuedAt === null || issuedAt - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= now
- ],
- [
- `not-expired(d=${challenge.expiresAt - now}ms)`,
- now - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= challenge.expiresAt
- ],
['issuedAt-before-expiry', issuedAt === null || issuedAt <= challenge.expiresAt],
[
`window(w=${issuedAt === null ? 'n/a' : challenge.expiresAt - issuedAt}ms)`,
@@ -103,6 +100,18 @@ function validateTranscript(
context.onInvalid?.(`transcript:${failed.join('+')}`)
return false
}
+ if (
+ issuedAt !== null &&
+ !(
+ issuedAt - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= now &&
+ now - RELAY_HOST_PROOF_CLOCK_SKEW_MS <= challenge.expiresAt
+ )
+ ) {
+ // Diagnose time only after the transcript's identity and signed window pass.
+ const error = new RelayHostProofClockSkewError(now - issuedAt)
+ context.onInvalid?.(error.message, error)
+ return false
+ }
return true
}
diff --git a/src/main/runtime/mobile-cloud-relay/relay-readiness.ts b/src/main/runtime/mobile-cloud-relay/relay-readiness.ts
index e9bec46634f..f8949fc7eb7 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-readiness.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-readiness.ts
@@ -1,4 +1,5 @@
import { RelayHttpError } from './relay-http-client'
+import { RelayHostProofClockSkewError } from './relay-host-proof'
import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason'
// Lowercase reason tokens must form valid relay_<reason> mint-failure codes.
@@ -10,11 +11,16 @@ export type RelayUnavailableReason =
| 'tls_untrusted'
| 'connect_timeout'
| 'network'
+ | 'clock_skew'
| 'control_not_active'
| `director_${'token_exchange' | 'assignment'}_${number}`
| `control_${string}`
-export type RelayUnavailable = { reason: RelayUnavailableReason; retryAt: number | null }
+export type RelayUnavailable = {
+ reason: RelayUnavailableReason
+ retryAt: number | null
+ clockOffsetMs?: number
+}
const TLS_TRUST_ERROR_CODES = new Set([
'UNABLE_TO_GET_ISSUER_CERT',
@@ -49,6 +55,9 @@ function errorChain(error: unknown): unknown[] {
}
export function relayUnavailableReasonFor(error: unknown): RelayUnavailableReason {
+ if (error instanceof RelayHostProofClockSkewError) {
+ return 'clock_skew'
+ }
if (error instanceof RelayHttpError) {
return error.statusCode === 429
? 'rate_limited'
@@ -70,6 +79,13 @@ export function relayUnavailableReasonFor(error: unknown): RelayUnavailableReaso
return message ? `control_${message[1].slice('control_'.length)}` : 'network'
}
+export function relayUnavailableFor(error: unknown): Omit<RelayUnavailable, 'retryAt'> {
+ return {
+ reason: relayUnavailableReasonFor(error),
+ ...(error instanceof RelayHostProofClockSkewError ? { clockOffsetMs: error.clockOffsetMs } : {})
+ }
+}
+
const RATE_LIMIT_FLOOR_BASE_MS = 5_000
const RATE_LIMIT_FLOOR_MAX_MS = 30_000
@@ -121,9 +137,11 @@ export class RelayReadinessWaiters {
export class RelayUnavailableError extends Error {
readonly code: string
+ readonly clockOffsetMs?: number
constructor(readonly unavailable: RelayUnavailable) {
super(`relay_${unavailable.reason}`)
this.code = this.message
+ this.clockOffsetMs = unavailable.clockOffsetMs
}
}
diff --git a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts b/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts
index a82dd44eda7..6767f0f7de7 100644
--- a/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts
+++ b/src/main/runtime/mobile-cloud-relay/relay-session-broker-contract.ts
@@ -1,6 +1,9 @@
import type WebSocket from 'ws'
import type { OrcaCloudAuthConfig } from '../../orca-profiles/profile-cloud-auth-config'
-import type { MobileRelayStatus } from '../../../shared/mobile-relay-status'
+import type {
+ MobileRelayStatus,
+ MobileRelayStatusPublisher
+} from '../../../shared/mobile-relay-status'
import type { E2EEKeypair } from '../e2ee-keypair'
import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring'
import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason'
@@ -33,7 +36,7 @@ export type RelaySessionBrokerOptions = {
measureRegionDecision?: (window: RelayRegionWindow) => Promise<RelayRegionDecision>
onAssignedCellActive?: (cellUrl: string) => void
/** `cellUrl` is absent whenever the host holds no active assignment. */
- onStatus: (status: RelayBrokerStatus, cellUrl?: string) => void
+ onStatus: MobileRelayStatusPublisher
fetch?: typeof globalThis.fetch
createControlSocket?: (url: string, relayJwt: string) => WebSocket
createDataSocket?: (url: string) => WebSocket
diff --git a/src/main/startup/main-process-relay-status.ts b/src/main/startup/main-process-relay-status.ts
index 1dd254df8b3..c7576802f5e 100644
--- a/src/main/startup/main-process-relay-status.ts
+++ b/src/main/startup/main-process-relay-status.ts
@@ -2,17 +2,18 @@ import type { MobileRelayStatusDetail } from '../../shared/mobile-relay-status'
import { mainProcessState as state } from './main-process-state'
export function getDesktopRelayStatus(): MobileRelayStatusDetail {
- return {
- status: state.desktopRelayStatus,
- ...(state.desktopRelayCellUrl === undefined ? {} : { cellUrl: state.desktopRelayCellUrl })
- }
+ return { ...state.desktopRelayStatus }
}
export function publishDesktopRelayStatus(
status: MobileRelayStatusDetail['status'],
- cellUrl?: string
+ cellUrl?: string,
+ clockOffsetMs?: number
): void {
- state.desktopRelayStatus = status
- state.desktopRelayCellUrl = cellUrl
+ state.desktopRelayStatus = {
+ status,
+ ...(cellUrl === undefined ? {} : { cellUrl }),
+ ...(clockOffsetMs === undefined ? {} : { clockOffsetMs })
+ }
state.mainWindow?.webContents.send('mobile:relayStatusChanged', getDesktopRelayStatus())
}
diff --git a/src/main/startup/main-process-state.ts b/src/main/startup/main-process-state.ts
index c2c29582b59..eee43cda4a8 100644
--- a/src/main/startup/main-process-state.ts
+++ b/src/main/startup/main-process-state.ts
@@ -26,7 +26,7 @@ import type { PluginAutoUpdater } from '../plugins/catalog/plugin-auto-updater'
import type { PluginMarketplaceService } from '../plugins/catalog/plugin-marketplace-service'
import type { PluginMarketplaceInstaller } from '../plugins/catalog/plugin-marketplace-installer'
import type { KeybindingService } from '../keybindings/keybinding-service'
-import type { RelayBrokerStatus } from '../runtime/mobile-cloud-relay/relay-session-broker-contract'
+import type { MobileRelayStatusDetail } from '../../shared/mobile-relay-status'
import type { AgentBrowserBridge } from '../browser/agent-browser-bridge'
import type { EmulatorBridge } from '../emulator/emulator-bridge'
import type { GpuFallbackMarker, GpuFallbackEnvironment } from './gpu-fallback-marker'
@@ -66,6 +66,8 @@ function createInitialProfileStateAdmission(): ProfileStateRuntimeAdmission | un
}
/** Mutable composition-root state shared by startup, window, serve, and quit phases. */
+const desktopRelayStatus: MobileRelayStatusDetail = { status: 'offline' }
+
export const mainProcessState = {
mainWindow: null as BrowserWindow | null,
// Never cleared: closing the last main window still quits on Windows/Linux.
@@ -94,8 +96,7 @@ export const mainProcessState = {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: widens the null slot to the installer assigned by main-process-relay-startup.
desktopRelayInstaller: null as DesktopRelayServiceInstaller | null,
desktopPushService: null as DesktopPushService | null,
- desktopRelayStatus: 'offline' as RelayBrokerStatus,
- desktopRelayCellUrl: undefined as string | undefined,
+ desktopRelayStatus,
pendingUnpairedDeviceAuthFailure: false,
// Advertise headless browser panes only when offscreen display initialization succeeds.
headlessBrowserDisplayAvailable: false,
diff --git a/src/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsx b/src/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsx
index 2aba5750093..055f75b64f1 100644
--- a/src/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsx
+++ b/src/renderer/src/components/mobile/mobile-relay-mint-failure-notice.tsx
@@ -5,6 +5,7 @@ import { translate } from '@/i18n/i18n'
import type { MobileRelayMintFailure } from '../../../../shared/mobile-relay-mint-failure'
import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
+import { relayClockSkewMessage } from './relay-clock-skew-message'
export function MobileRelayMintFailureNotice({
failure,
@@ -88,10 +89,12 @@ export function MobileRelayMintFailureNotice({
'auto.components.mobile.MobileRelayMintFailureNotice.rateLimitedBody',
'Orca Relay is busy. Wait a minute and retry, or use LAN to pair over Tailscale or the same Wi‑Fi.'
)
- : translate(
- 'auto.components.mobile.MobileRelayMintFailureNotice.body',
- 'Retry, or use LAN to pair over Tailscale or the same Wi‑Fi.'
- )
+ : failure.code === 'relay_clock_skew' && failure.clockOffsetMs !== undefined
+ ? relayClockSkewMessage(failure.clockOffsetMs)
+ : translate(
+ 'auto.components.mobile.MobileRelayMintFailureNotice.body',
+ 'Retry, or use LAN to pair over Tailscale or the same Wi‑Fi.'
+ )
return (
<div
diff --git a/src/renderer/src/components/mobile/relay-clock-skew-message.ts b/src/renderer/src/components/mobile/relay-clock-skew-message.ts
new file mode 100644
index 00000000000..6f984484d9f
--- /dev/null
+++ b/src/renderer/src/components/mobile/relay-clock-skew-message.ts
@@ -0,0 +1,9 @@
+import { translate } from '@/i18n/i18n'
+
+export function relayClockSkewMessage(clockOffsetMs: number): string {
+ return translate(
+ 'auto.components.mobile.relayClockSkewMessage.message',
+ "Your computer's clock is off by about {{seconds}} seconds. Turn on automatic time, then retry.",
+ { seconds: Math.round(Math.abs(clockOffsetMs) / 1000) }
+ )
+}
diff --git a/src/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsx b/src/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsx
index 51373e3d2a7..1a03e5228fe 100644
--- a/src/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsx
+++ b/src/renderer/src/components/settings/MobilePairingConnectionOptions.test.tsx
@@ -42,10 +42,6 @@ function publishStoreState(next: MobileRelayStoreState): void {
mocks.listeners.forEach((listener) => listener())
}
-vi.mock('../../i18n/i18n', () => ({
- translate: (_key: string, fallback: string) => fallback
-}))
-
describe('MobilePairingConnectionOptions', () => {
let statusListener: ((detail: MobileRelayStatusDetail) => void) | null
const connect = vi.fn().mockResolvedValue(null)
@@ -282,6 +278,28 @@ describe('MobilePairingConnectionOptions', () => {
await waitFor(() => expect(screen.queryByTestId('relay-cell-line')).toBeNull())
})
+ it('shows clock guidance from status and clears it when Relay recovers', async () => {
+ mocks.state = {
+ ...mocks.state,
+ orcaProfileAuthStatus: {
+ activeProfileId: 'profile-1',
+ configured: true,
+ state: 'connected',
+ persistence: 'encrypted'
+ }
+ }
+ render(<MobilePairingConnectionOptions value="automatic" onChange={vi.fn()} />)
+ await waitFor(() => expect(screen.getByText('Ready')).toBeVisible())
+
+ statusListener?.({ status: 'offline', clockOffsetMs: -38_000 })
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ "Your computer's clock is off by about 38 seconds. Turn on automatic time, then retry."
+ )
+
+ statusListener?.({ status: 'registered' })
+ await waitFor(() => expect(screen.queryByRole('alert')).toBeNull())
+ })
+
it('keeps LAN available while Relay is retrying', async () => {
mocks.state = {
...mocks.state,
diff --git a/src/renderer/src/components/settings/MobilePairingConnectionOptions.tsx b/src/renderer/src/components/settings/MobilePairingConnectionOptions.tsx
index f92e80cb068..b68c437ec5c 100644
--- a/src/renderer/src/components/settings/MobilePairingConnectionOptions.tsx
+++ b/src/renderer/src/components/settings/MobilePairingConnectionOptions.tsx
@@ -11,6 +11,7 @@ import type {
import type { MobilePairingConnectionMode } from '../../../../shared/mobile-pairing-connection-mode'
import { MobilePairingPathOption } from './MobilePairingPathOption'
import { MobileRelaySignInPanel } from './MobileRelaySignInPanel'
+import { relayClockSkewMessage } from '../mobile/relay-clock-skew-message'
function relayStatusLabel(status: MobileRelayStatus): string {
if (status === 'registered') {
@@ -64,8 +65,7 @@ export function MobilePairingConnectionOptions({
relayMintRetrying?: boolean
}): React.JSX.Element {
const authStatus = useAppStore((state) => state.orcaProfileAuthStatus)
- const [relayStatus, setRelayStatus] = useState<MobileRelayStatus>('offline')
- const [relayCellUrl, setRelayCellUrl] = useState<string | undefined>(undefined)
+ const [relayStatus, setRelayStatus] = useState<MobileRelayStatusDetail>({ status: 'offline' })
const signedIn = authStatus?.state === 'connected'
const reconnectRequired = authStatus?.state === 'reconnect-required'
// Unconfigured builds have no Relay sign-in endpoint; mark unavailable instead of offering a dead CTA.
@@ -98,7 +98,7 @@ export function MobilePairingConnectionOptions({
optionRefs.current[next]?.focus()
}
- const relayCell = relayCellUrl ? relayCellLabel(relayCellUrl) : null
+ const relayCell = relayStatus.cellUrl ? relayCellLabel(relayStatus.cellUrl) : null
useOrcaProfileAuthStatusRefresh()
@@ -106,8 +106,7 @@ export function MobilePairingConnectionOptions({
let receivedEvent = false
let active = true
const apply = (detail: MobileRelayStatusDetail): void => {
- setRelayStatus(detail.status)
- setRelayCellUrl(detail.cellUrl)
+ setRelayStatus(detail)
}
const unsubscribe = window.api.mobile.onRelayStatusChanged((detail) => {
receivedEvent = true
@@ -185,12 +184,20 @@ export function MobilePairingConnectionOptions({
'auto.components.settings.MobilePairingConnectionOptions.unavailable',
'Unavailable'
)
- : relayStatusLabel(relayStatus)}
+ : relayStatusLabel(relayStatus.status)}
</Badge>
) : null
}
/>
{needsSignIn ? <MobileRelaySignInPanel reconnectRequired={reconnectRequired} /> : null}
+ {signedIn &&
+ value === 'automatic' &&
+ !relayMintFailed &&
+ relayStatus.clockOffsetMs !== undefined ? (
+ <p className="border-t border-border/60 px-3 py-2 text-xs text-destructive" role="alert">
+ {relayClockSkewMessage(relayStatus.clockOffsetMs)}
+ </p>
+ ) : null}
{value === 'automatic' && relayCell ? (
<p
className="border-t border-border/60 py-2 pl-10 pr-3 text-xs text-muted-foreground"
diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json
index 020f233429c..b4c6074d225 100644
--- a/src/renderer/src/i18n/locales/de.json
+++ b/src/renderer/src/i18n/locales/de.json
@@ -15013,6 +15013,9 @@
"reconnectBody": "Erneut anmelden, um Orca Relay zu nutzen, oder LAN verwenden, um über Tailscale oder dasselbe Wi‑Fi-Netzwerk zu koppeln.",
"notEntitledTitle": "Orca Relay ist in diesem Orca-Konto nicht enthalten.",
"rateLimitedBody": "Orca Relay ist ausgelastet. Eine Minute warten und erneut versuchen oder LAN verwenden, um über Tailscale oder dasselbe Wi‑Fi-Netzwerk zu koppeln."
+ },
+ "relayClockSkewMessage": {
+ "message": "Die Uhr deines Computers geht um etwa {{seconds}} Sekunden falsch. Aktiviere die automatische Zeiteinstellung und versuche es erneut."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json
index 5bd991aa00c..574f78d6b66 100644
--- a/src/renderer/src/i18n/locales/en.json
+++ b/src/renderer/src/i18n/locales/en.json
@@ -15418,6 +15418,9 @@
"reconnectBody": "Sign in again to use Orca Relay, or use LAN to pair over Tailscale or the same Wi‑Fi.",
"notEntitledTitle": "Orca Relay isn’t included with this Orca account.",
"rateLimitedBody": "Orca Relay is busy. Wait a minute and retry, or use LAN to pair over Tailscale or the same Wi‑Fi."
+ },
+ "relayClockSkewMessage": {
+ "message": "Your computer's clock is off by about {{seconds}} seconds. Turn on automatic time, then retry."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json
index 63f0474b71f..91541897a59 100644
--- a/src/renderer/src/i18n/locales/es.json
+++ b/src/renderer/src/i18n/locales/es.json
@@ -15013,6 +15013,9 @@
"reconnectBody": "Inicia sesión de nuevo para usar Orca Relay, o usa LAN para emparejar mediante Tailscale o la misma red Wi‑Fi.",
"notEntitledTitle": "Orca Relay no está incluido en esta cuenta de Orca.",
"rateLimitedBody": "Orca Relay está ocupado. Espera un minuto y vuelve a intentarlo, o usa LAN para emparejar por Tailscale o la misma Wi‑Fi."
+ },
+ "relayClockSkewMessage": {
+ "message": "El reloj de tu computadora está desfasado unos {{seconds}} segundos. Activa la hora automática y vuelve a intentarlo."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json
index ddd62db773e..0e6d9223226 100644
--- a/src/renderer/src/i18n/locales/fr.json
+++ b/src/renderer/src/i18n/locales/fr.json
@@ -15237,6 +15237,9 @@
"reconnectBody": "Connectez-vous à nouveau pour utiliser Orca Relay, ou utilisez le réseau local pour effectuer le couplage via Tailscale ou le même Wi‑Fi.",
"notEntitledTitle": "Orca Relay n'est pas inclus avec ce compte Orca.",
"rateLimitedBody": "Orca Relay est occupé. Attendez une minute et réessayez, ou utilisez le LAN pour appairer via Tailscale ou le même Wi‑Fi."
+ },
+ "relayClockSkewMessage": {
+ "message": "L’horloge de votre ordinateur est décalée d’environ {{seconds}} secondes. Activez le réglage automatique de l’heure, puis réessayez."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json
index f185b72b763..c138e0dc776 100644
--- a/src/renderer/src/i18n/locales/ja.json
+++ b/src/renderer/src/i18n/locales/ja.json
@@ -14640,6 +14640,9 @@
"reconnectBody": "もう一度サインインして Orca Relay を使用するか、LAN を使用して Tailscale または同じ Wi-Fi 経由でペアリングします。",
"notEntitledTitle": "Orca Relay はこの Orca アカウントには含まれていません。",
"rateLimitedBody": "Orca Relay が混雑しています。1 分待って再試行するか、LAN を使用して Tailscale または同じ Wi‑Fi 経由でペアリングしてください。"
+ },
+ "relayClockSkewMessage": {
+ "message": "コンピューターの時計が約 {{seconds}} 秒ずれています。時刻の自動設定をオンにしてから、もう一度お試しください。"
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json
index dc8fccf3a55..6581c93e14d 100644
--- a/src/renderer/src/i18n/locales/ko.json
+++ b/src/renderer/src/i18n/locales/ko.json
@@ -14640,6 +14640,9 @@
"reconnectBody": "Orca Relay를 사용하려면 다시 로그인하거나 LAN을 사용하여 Tailscale 또는 동일한 Wi-Fi를 통해 페어링하세요.",
"notEntitledTitle": "이 Orca 계정에는 Orca Relay가 포함되어 있지 않습니다.",
"rateLimitedBody": "Orca Relay가 사용 중입니다. 1분 정도 기다렸다가 다시 시도하거나, LAN을 사용해 Tailscale 또는 동일한 Wi‑Fi로 페어링하세요."
+ },
+ "relayClockSkewMessage": {
+ "message": "컴퓨터 시계가 약 {{seconds}}초 어긋나 있습니다. 자동 시간 설정을 켠 다음 다시 시도하세요."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json
index f485de595e5..4ee7e06499e 100644
--- a/src/renderer/src/i18n/locales/pt.json
+++ b/src/renderer/src/i18n/locales/pt.json
@@ -16440,6 +16440,9 @@
"96d651cb87": "Sessão de terminal",
"93217b41c1": "Lista de worktrees",
"89c7713645": "Tela inicial do Orca Mobile"
+ },
+ "relayClockSkewMessage": {
+ "message": "O relógio do seu computador está com uma diferença de cerca de {{seconds}} segundos. Ative a hora automática e tente novamente."
}
},
"PullRequestConfirmation": {
diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json
index 4e744eebd20..efe4d9f607b 100644
--- a/src/renderer/src/i18n/locales/ru.json
+++ b/src/renderer/src/i18n/locales/ru.json
@@ -15479,6 +15479,9 @@
"reconnectBody": "Войдите снова для использования Orca Relay или выберите LAN для сопряжения через Tailscale либо общую сеть Wi‑Fi.",
"notEntitledTitle": "Для этой учётной записи Orca доступ к Orca Relay не предусмотрен.",
"rateLimitedBody": "Orca Relay занят. Подождите минуту и повторите попытку или используйте LAN для сопряжения через Tailscale либо общую сеть Wi‑Fi."
+ },
+ "relayClockSkewMessage": {
+ "message": "Часы компьютера отклоняются примерно на {{seconds}} сек. Включите автоматическую настройку времени и повторите попытку."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json
index b92a6785e7a..7f8d3b00a51 100644
--- a/src/renderer/src/i18n/locales/tr.json
+++ b/src/renderer/src/i18n/locales/tr.json
@@ -14999,6 +14999,9 @@
"reconnectBody": "Orca Relay'i kullanmak için tekrar oturum açın veya Tailscale ya da aynı Wi-Fi üzerinden eşleştirmek için Yerel Ağı kullanın.",
"notEntitledTitle": "Orca Relay bu Orca hesabına dahil değil.",
"rateLimitedBody": "Orca Relay meşgul. Bir dakika bekleyip yeniden deneyin veya Tailscale ya da aynı Wi‑Fi üzerinden eşleştirmek için LAN kullanın."
+ },
+ "relayClockSkewMessage": {
+ "message": "Bilgisayarınızın saati yaklaşık {{seconds}} saniye farklı. Otomatik saat ayarını açıp yeniden deneyin."
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json
index 71533b5dd56..21de7db391f 100644
--- a/src/renderer/src/i18n/locales/zh-Hant.json
+++ b/src/renderer/src/i18n/locales/zh-Hant.json
@@ -14801,6 +14801,9 @@
"reconnectBody": "再次登入使用 Orca Relay,或使用 LAN 透過 Tailscale 或相同 Wi-Fi 進行配對。",
"notEntitledTitle": "此 Orca 帳戶不包含 Orca Relay。",
"rateLimitedBody": "Orca Relay 正忙。請等待一分鐘再重試,或使用 LAN 透過 Tailscale 或同一 Wi‑Fi 配對。"
+ },
+ "relayClockSkewMessage": {
+ "message": "你的電腦時鐘偏差約 {{seconds}} 秒。請開啟自動設定時間,然後重試。"
}
},
"gitlab": {
diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json
index 84a277db214..14a2e32e80f 100644
--- a/src/renderer/src/i18n/locales/zh.json
+++ b/src/renderer/src/i18n/locales/zh.json
@@ -14640,6 +14640,9 @@
"reconnectBody": "再次登录以使用 Orca Relay,或使用 LAN 通过 Tailscale 或同一 Wi-Fi 进行配对。",
"notEntitledTitle": "此 Orca 账户不包含 Orca Relay。",
"rateLimitedBody": "Orca Relay 正忙。请等待一分钟再重试,或使用 LAN 通过 Tailscale 或同一 Wi‑Fi 配对。"
+ },
+ "relayClockSkewMessage": {
+ "message": "你的电脑时钟偏差约 {{seconds}} 秒。请开启自动设置时间,然后重试。"
}
},
"gitlab": {
diff --git a/src/shared/mobile-relay-mint-failure.ts b/src/shared/mobile-relay-mint-failure.ts
index fc96f6fbe4f..24f04d92938 100644
--- a/src/shared/mobile-relay-mint-failure.ts
+++ b/src/shared/mobile-relay-mint-failure.ts
@@ -9,6 +9,7 @@ export type MobileRelayMintFailure = {
code: string
stage: MobileRelayMintFailureStage
message: string
+ clockOffsetMs?: number
}
export function mobileRelayMintFailureFromUnknown(args: {
@@ -30,9 +31,19 @@ export function mobileRelayMintFailureFromUnknown(args: {
candidateCode != null && /^relay_[a-z0-9_]{1,74}$/.test(candidateCode)
? candidateCode
: args.fallbackCode
+ const clockOffsetMs =
+ code === 'relay_clock_skew' &&
+ typeof args.error === 'object' &&
+ args.error !== null &&
+ 'clockOffsetMs' in args.error &&
+ typeof args.error.clockOffsetMs === 'number' &&
+ Number.isFinite(args.error.clockOffsetMs)
+ ? args.error.clockOffsetMs
+ : undefined
return {
code,
stage: args.stage,
- message: args.fallbackMessage
+ message: args.fallbackMessage,
+ ...(clockOffsetMs === undefined ? {} : { clockOffsetMs })
}
}
diff --git a/src/shared/mobile-relay-status.ts b/src/shared/mobile-relay-status.ts
index f375e0e78a5..7f51ec18454 100644
--- a/src/shared/mobile-relay-status.ts
+++ b/src/shared/mobile-relay-status.ts
@@ -12,8 +12,16 @@ export type MobileRelayStatus = (typeof MOBILE_RELAY_STATUSES)[number]
export type MobileRelayStatusDetail = {
status: MobileRelayStatus
cellUrl?: string
+ /** Local clock minus Relay issuedAt; positive means the computer is ahead. */
+ clockOffsetMs?: number
}
+export type MobileRelayStatusPublisher = (
+ status: MobileRelayStatus,
+ cellUrl?: string,
+ clockOffsetMs?: number
+) => void
+
// Offline/connecting hosts may retain an assignment for reuse; publish a cell only while actually serving there.
const STATUSES_SERVED_FROM_A_CELL: readonly MobileRelayStatus[] = ['registered', 'draining']