fix(remote): read paired rows only when consumed; fence the delta base by contact

This commit is contained in:
Jinwoo-H
2026-11-13 03:44:36 -05:00
parent 58963eafa7
commit f33698b4cf
6 changed files with 113 additions and 29 deletions
@@ -80,11 +80,15 @@ export type MobileDesktopRelayHosts = {
/** The saved server list was edited (added, renamed, removed), here or by the CLI. */
onCatalogChanged?: (listener: () => void) => () => void
/** Windowless server events: onChange fires on ready, catalog and agent row changes, and reconnect replay.
* catalog is false for worktreesChanged and worktreeRowsChanged; repo/project-group writes never emit those alone. */
* catalog is false for worktreesChanged and worktreeRowsChanged; repo/project-group writes never emit those alone.
* agentRowsOnly marks worktreeRowsChanged: only agent status in the rows moved. */
watchChanges: (
host: Pick<MobileDesktopRelayHost, 'environmentId'>,
expected: NonNullable<MobileDesktopRelayCallOptions['expected']>,
callbacks: { onChange: (change: { catalog: boolean }) => void; onClose: () => void }
callbacks: {
onChange: (change: { catalog: boolean; agentRowsOnly?: true }) => void
onClose: () => void
}
) => MobileDesktopRelayHostWatch
}
@@ -6,10 +6,15 @@ const WORKSPACE_CHANGES = [
] as const
/** The workspace change a server's client event announces; catalog is false when only rows moved. */
export function workspaceChangeOfClientEvent(message: unknown): { catalog: boolean } | null {
export function workspaceChangeOfClientEvent(
message: unknown
): { catalog: boolean; agentRowsOnly?: true } | null {
if (typeof message !== 'object' || message === null || !('type' in message)) {
return null
}
const change = WORKSPACE_CHANGES.find((type) => type === message.type)
if (change === 'worktreeRowsChanged') {
return { catalog: false, agentRowsOnly: true }
}
return change ? { catalog: change === 'ready' || change === 'reposChanged' } : null
}
@@ -1,5 +1,9 @@
import { z } from 'zod'
import { toRuntimeExecutionHostId } from '../../../shared/execution-host'
import {
isWorktreeCatalogRow,
worktreeCatalogRowDelta
} from '../../../shared/worktree/catalog-row-delta'
// Default pages stop at 200; the phone has no pagination.
export const SERVER_WORKTREE_LIMIT = 10_000
@@ -8,6 +12,13 @@ export const SERVER_FETCH_TIMEOUT_MS = 5_000
export const WorktreePsReplySchema = z.object({ worktrees: z.array(z.looseObject({})) })
export type ServerWorktreeRow = { [key: string]: unknown; worktreeId: string }
/** A server's worktree.ps read as row deltas on top of the rows held from its last answer. */
export const serverRowDeltas = worktreeCatalogRowDelta((row): row is ServerWorktreeRow =>
isWorktreeCatalogRow(row)
)
/** Collapse server-relative local/SSH hosts to the server id, matching the desktop sidebar. */
export function stampServerWorktreeRows<Row extends object>(
environmentId: string,
@@ -107,7 +107,7 @@ describe('runtime workspace activity facts', () => {
server.ingestTerminalStatus({
paneKey: `tab-1:${LEAF}`,
tabId: 'tab-1',
payload: { state: 'working', agentType: 'claude' }
payload: { state: 'working', prompt: '', agentType: 'claude' }
})
await vi.advanceTimersByTimeAsync(2000)
expect(events).toContain('worktreeRowsChanged')
@@ -60,7 +60,7 @@ function fakeHosts(servers: { id: string; live: boolean; wsl?: true }[]) {
string,
{
/** A catalog change unless told otherwise, as ready and reposChanged are. */
onChange: (change?: { catalog: boolean }) => void
onChange: (change?: { catalog: boolean; agentRowsOnly?: true }) => void
onClose: () => void
closed: boolean
ended: boolean
@@ -279,10 +279,10 @@ describe('PairedServerRowsProducer', () => {
})
describe('agent row changes', () => {
function attached(servers = [{ id: 'box', live: true }]) {
const fake = fakeHosts(servers)
function attached(demand = { on: true }) {
const fake = fakeHosts([{ id: 'box', live: true }])
const producer = new PairedServerRowsProducer({
hasDemand: () => true,
hasDemand: () => demand.on,
hostLabelOverrides: () => new Map()
})
producer.attach(fake.hosts)
@@ -376,6 +376,50 @@ describe('PairedServerRowsProducer', () => {
expect(snapshotParams()).toEqual([null, 's1', null, null])
})
it('reads nothing for agent notices nobody consumes, then catches up once on the next read', async () => {
const demand = { on: false }
const { call, watches, producer, ids } = attached(demand)
call.mockResolvedValueOnce(psReply([row('a')]))
watches.get('box')?.onChange()
await vi.advanceTimersByTimeAsync(0)
call.mockClear()
for (let step = 0; step < 5; step += 1) {
watches.get('box')?.onChange({ catalog: false, agentRowsOnly: true })
}
await vi.advanceTimersByTimeAsync(0)
expect(call).not.toHaveBeenCalled()
demand.on = true
call.mockResolvedValueOnce(psReply([row('a'), row('b')]))
producer.snapshot()
producer.snapshot()
await vi.advanceTimersByTimeAsync(0)
expect(call).toHaveBeenCalledTimes(1)
expect(ids()).toEqual(['a', 'b'])
})
it('keeps the reconnect full read when a reply from before the gap lands after it', async () => {
const { call, watches, producer, snapshotParams, state, publishStatus } = attached()
call.mockResolvedValueOnce(reply({ worktrees: [row('a')], snapshotId: 's1' }))
watches.get('box')?.onChange()
await vi.advanceTimersByTimeAsync(0)
let answer: (response: RuntimeRpcResponse<unknown>) => void = () => {}
call.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)))
const beforeGap = producer.refresh('box')
state.servers = [{ id: 'box', live: false }]
publishStatus()
state.servers = [{ id: 'box', live: true }]
publishStatus()
answer(reply({ worktrees: [row('a')], snapshotId: 's2' }))
await beforeGap
call.mockResolvedValueOnce(reply({ worktrees: [row('a')], snapshotId: 's2' }))
await producer.refresh('box')
expect(snapshotParams()).toEqual([null, 's1', null])
})
it('reads an older server in full on every refresh and every 30 s', async () => {
const { call, watches, producer, ids, snapshotParams } = attached()
call.mockResolvedValueOnce(psReply([row('a')]))
@@ -18,25 +18,17 @@ import {
import type { ServerWorktreeRows } from '../../mobile-desktop-relay/mobile-relay-host-catalog'
import {
SERVER_WORKTREE_LIMIT,
stampServerWorktreeRows
serverRowDeltas,
stampServerWorktreeRows,
type ServerWorktreeRow
} from '../../mobile-desktop-relay/server-worktree-fetch'
import {
isWorktreeCatalogRow,
worktreeCatalogRowDelta,
type WorktreeCatalogSnapshot
} from '../../../../shared/worktree/catalog-row-delta'
import type { WorktreeCatalogSnapshot } from '../../../../shared/worktree/catalog-row-delta'
import type { PairedServerCatalog } from '../../../../shared/sidebar-list/sidebar-project-catalog'
import { fetchPairedServerCatalog } from '../../../../shared/sidebar-list/paired-server-catalog'
// Backstop for changes a server announces no event for (terminal counts, unread, PR badge) and for older servers.
export const FALLBACK_REFRESH_MS = 30_000
type ServerRow = { [key: string]: unknown; worktreeId: string }
const serverRowDeltas = worktreeCatalogRowDelta((row): row is ServerRow =>
isWorktreeCatalogRow(row)
)
type ServerEntry = {
environmentId: string
fence: string
@@ -47,7 +39,9 @@ type ServerEntry = {
/** Null until a fetch under this pairing answered. */
rows: MobileRelayServerWorktreeRow[] | null
/** The server's rows under its snapshot id, the base of the next delta read; null asks in full. */
delta: WorktreeCatalogSnapshot<ServerRow> | null
delta: WorktreeCatalogSnapshot<ServerWorktreeRow> | null
/** An agent status notice arrived while nothing consumed rows; the next consumer read catches up. */
agentRowsStale: boolean
/** The rows are the server's answer since it last came into contact; else unverifiable. */
confirmed: boolean
/** Its repos and project groups as last fetched under this pairing; null until one answered. */
@@ -128,6 +122,7 @@ export class PairedServerRowsProducer implements ServerWorktreeRows {
contactGeneration: 0,
rows: null,
delta: null,
agentRowsStale: false,
confirmed: false,
catalog: null,
catalogStale: true,
@@ -178,10 +173,17 @@ export class PairedServerRowsProducer implements ServerWorktreeRows {
/** The server's raw rows as last fetched under this pairing; null when none were. */
rows(environmentId: string, fence: string): readonly MobileRelayServerWorktreeRow[] | null {
const entry = this.servers.get(environmentId)
return entry && entry.fence === fence ? entry.rows : null
if (!entry || entry.fence !== fence) {
return null
}
this.catchUp(entry)
return entry.rows
}
snapshot(): PairedServerRowsSnapshot {
for (const entry of this.servers.values()) {
this.catchUp(entry)
}
const shown = new Map(
(this.hosts
? describePairedServerHosts({
@@ -223,13 +225,19 @@ export class PairedServerRowsProducer implements ServerWorktreeRows {
const current = (): boolean => this.servers.get(entry.environmentId) === entry
// Ready fires on every (re)connect, so contact and a missed-event replay both count as changes.
const watch = hosts.watchChanges({ environmentId: entry.environmentId }, entry.identity, {
onChange: ({ catalog }) => {
if (current()) {
// A fetch already in flight may predate this change, so one more runs after it.
entry.refreshAgain ||= entry.refreshing !== null
entry.catalogStale ||= catalog
void this.refresh(entry.environmentId)
onChange: ({ catalog, agentRowsOnly }) => {
if (!current()) {
return
}
// A busy agent announces every step; nobody needs those rows until something reads them.
if (agentRowsOnly && !this.options.hasDemand()) {
entry.agentRowsStale = true
return
}
// A fetch already in flight may predate this change, so one more runs after it.
entry.refreshAgain ||= entry.refreshing !== null
entry.catalogStale ||= catalog
void this.refresh(entry.environmentId)
},
onClose: () => {
if (current() && entry.watch === watch) {
@@ -240,6 +248,14 @@ export class PairedServerRowsProducer implements ServerWorktreeRows {
entry.watch = watch
}
private catchUp(entry: ServerEntry): void {
if (entry.agentRowsStale && entry.inContact) {
entry.agentRowsStale = false
entry.refreshAgain ||= entry.refreshing !== null
void this.refresh(entry.environmentId)
}
}
private unconfirm(entry: ServerEntry): void {
if (entry.confirmed) {
entry.confirmed = false
@@ -264,6 +280,7 @@ export class PairedServerRowsProducer implements ServerWorktreeRows {
// Only on contact, ready, a replay or reposChanged, which every catalog write announces.
const readCatalog = entry.catalogStale
entry.catalogStale = false
entry.agentRowsStale = false
const held = entry.delta
const [read, catalog] = await Promise.all([
serverRowDeltas
@@ -304,7 +321,10 @@ export class PairedServerRowsProducer implements ServerWorktreeRows {
const confirmed = entry.inContact && entry.contactGeneration === contactGeneration
// An unchanged reply hands back the held snapshot itself.
const rowsChanged = read.snapshot !== held
entry.delta = read.snapshot
// A reply from before a contact gap must not restore the base the reconnect dropped.
if (entry.contactGeneration === contactGeneration) {
entry.delta = read.snapshot
}
if (rowsChanged) {
entry.rows = stampServerWorktreeRows(entry.environmentId, read.snapshot.worktrees)
} else if (confirmed === entry.confirmed) {