perf(mobile): stop polling live worktree names (#8051)

* perf(mobile): replace worktree name polling with events

* fix(worktrees): push rename invalidation to remote clients

worktrees:updateMeta deliberately skips the renderer notifier (PR #209),
but paired mobile clients no longer poll for titles, so a manual rename
would never reach them. Emit the remote-only worktreesChanged client
event (with resolved-cache invalidation), gated on displayName so
per-click isUnread writes stay event-free.

Co-authored-by: Orca <help@stably.ai>

* test(worktrees): add missing runtimeStub type member for typecheck

Co-authored-by: Orca <help@stably.ai>

* fix(worktrees): derive rename event repoId with the shared non-throwing parser

getRepoIdFromWorktreeId matches the mobile client's event filter exactly
and cannot throw after the meta write already persisted.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-10 22:44:59 -07:00
committed by GitHub
co-authored by Orca
parent c869891b37
commit 4f7fe78921
7 changed files with 464 additions and 11 deletions
@@ -0,0 +1,169 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { RpcClient } from '../transport/rpc-client'
import { useLiveWorktreeName } from './use-live-worktree-name'
vi.mock('expo-router', async () => {
const React = await import('react')
return {
useFocusEffect(effect: () => void | (() => void)): void {
React.useEffect(effect, [effect])
}
}
})
function suppressReactTestRendererDeprecationWarning(): () => void {
const originalConsoleError = console.error
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation((...args) => {
const firstArg = args[0]
if (typeof firstArg === 'string' && firstArg.includes('react-test-renderer is deprecated')) {
return
}
originalConsoleError(...args)
})
return () => consoleErrorSpy.mockRestore()
}
describe('useLiveWorktreeName request volume', () => {
let renderer: ReactTestRenderer | null = null
let eventListener: ((payload: unknown) => void) | null = null
const unsubscribeStream = vi.fn()
const sendRequest = vi.fn().mockResolvedValue({
id: 'worktree-show',
ok: true,
result: { worktree: { id: 'repo-1::/worktree', displayName: 'Live name' } },
_meta: { runtimeId: 'runtime-1' }
})
const subscribe = vi.fn(
(_method: string, _params: unknown, listener: (payload: unknown) => void) => {
eventListener = listener
return unsubscribeStream
}
)
const client = { sendRequest, subscribe } as unknown as RpcClient
async function mountHarness(): Promise<void> {
function Harness(): null {
useLiveWorktreeName({
client,
connState: 'connected',
routeName: 'Route name',
worktreeId: 'repo-1::/worktree'
})
return null
}
const restoreConsoleError = suppressReactTestRendererDeprecationWarning()
try {
await act(async () => {
renderer = create(createElement(Harness))
await Promise.resolve()
})
} finally {
restoreConsoleError()
}
}
async function emitEvent(payload: unknown): Promise<void> {
await act(async () => {
eventListener?.(payload)
await Promise.resolve()
await Promise.resolve()
})
}
beforeEach(() => {
vi.useFakeTimers()
globalThis.IS_REACT_ACT_ENVIRONMENT = true
eventListener = null
sendRequest.mockClear().mockResolvedValue({
id: 'worktree-show',
ok: true,
result: { worktree: { id: 'repo-1::/worktree', displayName: 'Live name' } },
_meta: { runtimeId: 'runtime-1' }
})
subscribe.mockClear()
unsubscribeStream.mockClear()
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.useRealTimers()
})
it('cuts thirty-second idle request volume from eleven calls to one', async () => {
await mountHarness()
expect(subscribe).toHaveBeenCalledWith(
'runtime.clientEvents.subscribe',
null,
expect.any(Function)
)
expect(sendRequest).toHaveBeenCalledTimes(1)
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-1' })
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
// The retired 3s interval made one initial request plus ten idle ticks here.
expect(sendRequest).toHaveBeenCalledTimes(1)
await emitEvent({ type: 'worktreesChanged', repoId: 'repo-2' })
expect(sendRequest).toHaveBeenCalledTimes(1)
await emitEvent({ type: 'worktreesChanged', repoId: 'repo-1' })
expect(sendRequest).toHaveBeenCalledTimes(2)
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
expect(sendRequest).toHaveBeenCalledTimes(2)
})
it('keeps polling when an older runtime rejects the event stream', async () => {
await mountHarness()
await emitEvent({ type: 'error', message: 'Unknown method' })
await act(async () => {
await vi.advanceTimersByTimeAsync(9_000)
})
expect(sendRequest).toHaveBeenCalledTimes(4)
})
it('retries a failed initial read even after the event stream is ready', async () => {
sendRequest.mockRejectedValueOnce(new Error('transient')).mockResolvedValue({
id: 'worktree-show',
ok: true,
result: { worktree: { id: 'repo-1::/worktree', displayName: 'Live name' } },
_meta: { runtimeId: 'runtime-1' }
})
await mountHarness()
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-1' })
await act(async () => {
await vi.advanceTimersByTimeAsync(3_000)
await vi.advanceTimersByTimeAsync(30_000)
})
expect(sendRequest).toHaveBeenCalledTimes(2)
})
it('refreshes once when a reconnected stream becomes ready again', async () => {
await mountHarness()
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-1' })
await emitEvent({ type: 'ready', subscriptionId: 'runtime-events-2' })
expect(sendRequest).toHaveBeenCalledTimes(2)
})
it('unsubscribes when the screen loses focus', async () => {
await mountHarness()
act(() => renderer?.unmount())
renderer = null
expect(unsubscribeStream).toHaveBeenCalledTimes(1)
})
})
+80 -5
View File
@@ -1,9 +1,13 @@
import { useCallback, useEffect, useState } from 'react'
import { useFocusEffect } from 'expo-router'
import type { RuntimeClientEventStreamMessage } from '../../../src/shared/runtime-client-events'
import { getRepoIdFromWorktreeId } from '../../../src/shared/worktree-id'
import type { RpcClient } from '../transport/rpc-client'
import type { ConnectionState, RpcSuccess } from '../transport/types'
import { getLiveWorktreeDisplayName, type WorktreeDisplayNameSource } from './worktree-display-name'
const WORKTREE_NAME_FALLBACK_POLL_MS = 3000
type Params = {
client: RpcClient | null
connState: ConnectionState
@@ -24,12 +28,27 @@ export function useLiveWorktreeName({ client, connState, routeName, worktreeId }
return
}
let stale = false
const refreshWorktreeName = async () => {
let eventStreamReady = false
let hasSuccessfulRefresh = false
let fallbackInterval: ReturnType<typeof setInterval> | null = null
let refreshGeneration = 0
const repoId = getRepoIdFromWorktreeId(worktreeId)
const stopFallbackPoll = (): void => {
if (fallbackInterval !== null) {
clearInterval(fallbackInterval)
fallbackInterval = null
}
}
const refreshWorktreeName = async (): Promise<void> => {
// Why: an event-driven refresh can overtake a slow fallback request;
// only the newest read may publish or stop the retry poll.
const generation = ++refreshGeneration
try {
const response = await client.sendRequest('worktree.show', {
worktree: `id:${worktreeId}`
})
if (stale || !response.ok) {
if (stale || generation !== refreshGeneration || !response.ok) {
return
}
const result = (response as RpcSuccess).result as {
@@ -41,17 +60,73 @@ export function useLiveWorktreeName({ client, connState, routeName, worktreeId }
if (liveName) {
setWorktreeName((current) => (current === liveName ? current : liveName))
}
hasSuccessfulRefresh = true
if (eventStreamReady) {
stopFallbackPoll()
}
} catch {
// Non-fatal: the route param remains a usable label until the next refresh.
}
}
const startFallbackPoll = (): void => {
if (stale || fallbackInterval !== null) {
return
}
fallbackInterval = setInterval(
() => void refreshWorktreeName(),
WORKTREE_NAME_FALLBACK_POLL_MS
)
}
const invalidateAndRefresh = (): void => {
hasSuccessfulRefresh = false
startFallbackPoll()
void refreshWorktreeName()
}
startFallbackPoll()
const unsubscribe = client.subscribe(
'runtime.clientEvents.subscribe',
null,
(payload: unknown) => {
if (stale || !payload || typeof payload !== 'object') {
return
}
const event = payload as RuntimeClientEventStreamMessage | { type: 'error' }
if (event.type === 'ready') {
const replayedAfterReconnect = eventStreamReady
eventStreamReady = true
if (hasSuccessfulRefresh) {
stopFallbackPoll()
}
if (replayedAfterReconnect) {
// Why: client events are not queued while disconnected, so replay
// readiness must re-read the title once to close that event gap.
invalidateAndRefresh()
}
return
}
if (event.type === 'end' || event.type === 'error') {
eventStreamReady = false
startFallbackPoll()
return
}
if (
event.type === 'reposChanged' ||
(event.type === 'worktreesChanged' && event.repoId === repoId)
) {
invalidateAndRefresh()
}
}
)
// Why: route params are only an entry hint. The desktop/runtime owns
// displayName, including task-generated names that may settle after open.
// displayName. Modern runtimes push invalidations; the poll remains only
// until that stream proves available, preserving older-runtime behavior.
void refreshWorktreeName()
const interval = setInterval(() => void refreshWorktreeName(), 3000)
return () => {
stale = true
clearInterval(interval)
stopFallbackPoll()
unsubscribe()
}
}, [client, connState, worktreeId])
)
@@ -0,0 +1,135 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { connect, type RpcClient } from './rpc-client'
vi.mock('./e2ee', () => ({
generateKeyPair: () => ({
publicKey: new Uint8Array(32),
secretKey: new Uint8Array(32)
}),
deriveSharedKey: () => new Uint8Array(32),
publicKeyFromBase64: () => new Uint8Array(32),
publicKeyToBase64: () => 'client-public-key',
encrypt: (plaintext: string) => `encrypted:${plaintext}`,
decrypt: (raw: string) => raw.replace(/^encrypted:/, ''),
decryptBytes: (bytes: Uint8Array) => bytes
}))
class RuntimeEventTestSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
readonly CONNECTING = RuntimeEventTestSocket.CONNECTING
readonly OPEN = RuntimeEventTestSocket.OPEN
readonly CLOSING = RuntimeEventTestSocket.CLOSING
readonly CLOSED = RuntimeEventTestSocket.CLOSED
readyState = RuntimeEventTestSocket.CONNECTING
onopen: (() => void) | null = null
onclose: (() => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onerror: (() => void) | null = null
sent: string[] = []
constructor(readonly endpoint: string) {
sockets.push(this)
}
send(payload: string): void {
this.sent.push(payload)
}
close(): void {
this.readyState = RuntimeEventTestSocket.CLOSED
this.onclose?.()
}
open(): void {
this.readyState = RuntimeEventTestSocket.OPEN
this.onopen?.()
}
receive(payload: unknown): void {
this.onmessage?.({ data: payload })
}
}
type SentRequest = { id: string; method: string; params?: unknown }
const sockets: RuntimeEventTestSocket[] = []
const originalWebSocket = globalThis.WebSocket
function sentRequests(socket: RuntimeEventTestSocket, method: string): SentRequest[] {
return socket.sent
.map((payload) => JSON.parse(payload.replace(/^encrypted:/, '')) as SentRequest)
.filter((request) => request.method === method)
}
function connectReadyClient(): { client: RpcClient; socket: RuntimeEventTestSocket } {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
const socket = sockets[0]!
socket.open()
socket.receive(JSON.stringify({ type: 'e2ee_ready' }))
socket.receive('encrypted:{"type":"e2ee_authenticated"}')
return { client, socket }
}
function emitReady(
socket: RuntimeEventTestSocket,
requestId: string,
subscriptionId: string
): void {
socket.receive(
`encrypted:${JSON.stringify({
id: requestId,
ok: true,
streaming: true,
result: { type: 'ready', subscriptionId },
_meta: { runtimeId: 'r1' }
})}`
)
}
describe('runtime client-event stream disposal', () => {
beforeEach(() => {
vi.useFakeTimers()
sockets.length = 0
globalThis.WebSocket = RuntimeEventTestSocket as unknown as typeof WebSocket
})
afterEach(() => {
globalThis.WebSocket = originalWebSocket
vi.useRealTimers()
})
it('unsubscribes a stream disposed after ready', () => {
const { client, socket } = connectReadyClient()
const unsubscribe = client.subscribe('runtime.clientEvents.subscribe', null, () => {})
const request = sentRequests(socket, 'runtime.clientEvents.subscribe')[0]!
emitReady(socket, request.id, 'runtime-events:test')
unsubscribe()
expect(sentRequests(socket, 'runtime.clientEvents.unsubscribe')).toEqual([
expect.objectContaining({ params: { subscriptionId: 'runtime-events:test' } })
])
client.close()
})
it('keeps a tombstone and unsubscribes a stream disposed before ready', () => {
const { client, socket } = connectReadyClient()
const listener = vi.fn()
const unsubscribe = client.subscribe('runtime.clientEvents.subscribe', null, listener)
const request = sentRequests(socket, 'runtime.clientEvents.subscribe')[0]!
unsubscribe()
emitReady(socket, request.id, 'runtime-events:late')
expect(listener).not.toHaveBeenCalled()
expect(sentRequests(socket, 'runtime.clientEvents.unsubscribe')).toEqual([
expect.objectContaining({ params: { subscriptionId: 'runtime-events:late' } })
])
client.close()
})
})
+39 -4
View File
@@ -567,10 +567,10 @@ export function connect(
const stream = streamListeners.get(response.id)
if (stream && response.ok) {
const result = (response as RpcSuccess).result
if (isBrowserScreencastReadyResult(result)) {
if (isStreamingSubscriptionReadyResult(result)) {
stream.subscriptionId = result.subscriptionId
if (stream.cancelled) {
sendBrowserScreencastUnsubscribe(result.subscriptionId)
sendServerSubscriptionUnsubscribe(stream)
removeStreamListener(response.id)
return
}
@@ -947,8 +947,21 @@ export function connect(
if (pendingBrowserScreencastRequestId === id) {
pendingBrowserScreencastRequestId = null
}
disposeServerSubscriptionStream(id, stream)
}
function disposeRuntimeClientEventsStream(id: string): void {
const stream = streamListeners.get(id)
if (!stream || stream.method !== 'runtime.clientEvents.subscribe') {
return
}
disposeServerSubscriptionStream(id, stream)
}
function disposeServerSubscriptionStream(id: string, stream: StreamRequest): void {
stream.cancelled = true
if (stream.subscriptionId) {
sendBrowserScreencastUnsubscribe(stream.subscriptionId)
sendServerSubscriptionUnsubscribe(stream)
removeStreamListener(id)
return
}
@@ -1022,6 +1035,24 @@ export function connect(
})
}
function sendServerSubscriptionUnsubscribe(stream: StreamRequest): void {
if (!stream.subscriptionId) {
return
}
if (stream.method === 'browser.screencast') {
sendBrowserScreencastUnsubscribe(stream.subscriptionId)
return
}
if (stream.method === 'runtime.clientEvents.subscribe') {
sendEncrypted({
id: nextId(),
deviceToken,
method: 'runtime.clientEvents.unsubscribe',
params: { subscriptionId: stream.subscriptionId }
})
}
}
openConnection()
return {
@@ -1120,6 +1151,10 @@ export function connect(
disposeBrowserScreencastStream(id)
return
}
if (stream?.method === 'runtime.clientEvents.subscribe') {
disposeRuntimeClientEventsStream(id)
return
}
if (stream?.method === 'terminal.subscribe') {
// Why: the runtime registers cleanup under the composite key
// `${terminal}:${clientId}` so two phones subscribing to the same
@@ -1243,7 +1278,7 @@ function isTerminalSubscribedResult(
)
}
function isBrowserScreencastReadyResult(
function isStreamingSubscriptionReadyResult(
value: unknown
): value is { type: 'ready'; subscriptionId: string } {
return (
+21 -1
View File
@@ -282,6 +282,7 @@ describe('registerWorktreeHandlers', () => {
resolveManagedMrBase: ReturnType<typeof vi.fn>
createTerminal: ReturnType<typeof vi.fn>
splitTerminal: ReturnType<typeof vi.fn>
notifyWorktreesChangedForRemoteClients: ReturnType<typeof vi.fn>
}
beforeEach(() => {
@@ -490,7 +491,8 @@ describe('registerWorktreeHandlers', () => {
handle: 'term-setup',
tabId: 'tab-startup',
paneRuntimeId: -1
})
}),
notifyWorktreesChangedForRemoteClients: vi.fn()
}
registerWorktreeHandlers(mainWindow as never, store as never, runtimeStub as never)
})
@@ -742,6 +744,24 @@ describe('registerWorktreeHandlers', () => {
expect(result).toMatchObject({ comment: 'keep me', isPinned: true })
})
it('pushes a remote-client invalidation for renames but not read-state updates', () => {
store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta)
handlers['worktrees:updateMeta'](null, {
worktreeId: 'repo-1::/workspace/feature-wt',
updates: { isUnread: false }
})
// Why: per-click isUnread writes must stay event-free (PR #209), while a
// rename must reach paired remote clients that no longer poll for titles.
expect(runtimeStub.notifyWorktreesChangedForRemoteClients).not.toHaveBeenCalled()
handlers['worktrees:updateMeta'](null, {
worktreeId: 'repo-1::/workspace/feature-wt',
updates: { displayName: 'Renamed workspace' }
})
expect(runtimeStub.notifyWorktreesChangedForRemoteClients).toHaveBeenCalledWith('repo-1')
})
it('does not trust renderer-authored automation provenance during local create', async () => {
store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta)
listWorktreesMock.mockResolvedValue([
+12 -1
View File
@@ -150,7 +150,10 @@ import {
} from '../worktree-removal-safety'
import { isWindowsAbsolutePathLike } from '../../shared/cross-platform-path'
import { DEFAULT_WORKSPACE_STATUS_ID } from '../../shared/workspace-statuses'
import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR } from '../../shared/worktree-id'
import {
FOLDER_WORKSPACE_INSTANCE_SEPARATOR,
getRepoIdFromWorktreeId
} from '../../shared/worktree-id'
import { prefetchWorktreeCreateBase } from '../worktree-create-base-prefetch'
import {
getLocalProjectGitExecOptions,
@@ -2017,6 +2020,14 @@ export function registerWorktreeHandlers(
// sortEpoch and reorders the sidebar — the exact bug PR #209 tried
// to fix (clicking a card would clear isUnread → updateMeta →
// worktrees:changed → fetchWorktrees → sortEpoch++ → re-sort).
if (args.updates.displayName !== undefined) {
// Why: paired remote clients have no optimistic copy of the rename and
// no longer poll for titles, so push the remote-only invalidation.
// Gated on displayName to keep isUnread-per-click updates event-free.
// getRepoIdFromWorktreeId matches the mobile client's event filter and
// never throws after the meta write already succeeded.
runtime.notifyWorktreesChangedForRemoteClients(getRepoIdFromWorktreeId(args.worktreeId))
}
return meta
}
)
+8
View File
@@ -2979,6 +2979,14 @@ export class OrcaRuntimeService {
this.emitClientEvent({ type: 'sshStateChanged', targetId, state })
}
// Why: renderer-initiated meta updates intentionally skip the renderer
// notifier (the renderer already applied them optimistically), but remote
// clients hold no optimistic copy and need the invalidation event.
notifyWorktreesChangedForRemoteClients(repoId: string): void {
this.invalidateResolvedWorktreeCache()
this.emitClientEvent({ type: 'worktreesChanged', repoId })
}
private notifyActivateWorktree(
repoId: string,
worktreeId: string,