Fix restored mobile terminals and workspace visibility parity (#8789)

* Fix mobile cutover activation and usage refresh loops

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

* Fix restored mobile terminal state parity

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

* Fix migrated PTY workspace attribution

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

* Fix overlapping mobile terminal surface swaps

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

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-07-14 19:36:47 -07:00
committed by GitHub
co-authored by Orca
parent d9f7fd08f7
commit 42ee45f392
19 changed files with 1240 additions and 96 deletions
+182
View File
@@ -7404,6 +7404,70 @@ describe('OrcaRuntimeService', () => {
})
})
it('falls back to provider history when a mounted renderer has not hydrated yet', async () => {
const { runtime } = createSideEffectRuntime()
const serializeBuffer = vi.fn().mockResolvedValue({
data: '',
cols: 80,
rows: 24
})
const serializeProviderBuffer = vi.fn().mockResolvedValue({
data: '',
scrollbackAnsi: 'restored history\r\n',
cols: 120,
rows: 40,
seq: 900,
source: 'headless'
})
runtime.setPtyController({
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
serializeBuffer,
serializeProviderBuffer,
hasRendererSerializer: () => true
})
const snapshot = await runtime.serializeTerminalBuffer('pty-restored', {
scrollbackRows: 5000
})
expect(serializeBuffer).toHaveBeenCalledOnce()
expect(serializeProviderBuffer).toHaveBeenCalledWith('pty-restored', {
scrollbackRows: 5000
})
expect(snapshot).toMatchObject({
data: '',
scrollbackAnsi: 'restored history\r\n',
source: 'headless'
})
})
it('keeps an empty renderer snapshot when the provider has no retained content', async () => {
const { runtime } = createSideEffectRuntime()
const serializeProviderBuffer = vi.fn().mockResolvedValue({
data: '',
scrollbackAnsi: '',
cols: 120,
rows: 40,
seq: 0,
source: 'headless'
})
runtime.setPtyController({
write: () => true,
kill: () => true,
getForegroundProcess: async () => null,
serializeBuffer: vi.fn().mockResolvedValue({ data: '', cols: 51, rows: 40 }),
serializeProviderBuffer,
hasRendererSerializer: () => true
})
const snapshot = await runtime.serializeTerminalBuffer('pty-new')
expect(serializeProviderBuffer).toHaveBeenCalledOnce()
expect(snapshot).toMatchObject({ data: '', cols: 51, rows: 40, source: 'renderer' })
})
it('does not let pre-response bytes hide restored provider history', async () => {
const { runtime } = createSideEffectRuntime()
const serializeProviderBuffer = vi.fn().mockResolvedValue({
@@ -22459,6 +22523,124 @@ describe('OrcaRuntimeService', () => {
})
})
it('attributes live legacy PTYs from saved layout bindings when their panes are hidden', async () => {
const session = makeWorkspaceSessionWithHeadlessTerminal()
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession({
...session,
tabsByWorktree: {
[TEST_WORKTREE_ID]: session.tabsByWorktree[TEST_WORKTREE_ID]!.map((tab) => ({
...tab,
ptyId: null
}))
}
})
const runtime = new OrcaRuntimeService(runtimeStore as never)
runtime.setPtyController({
write: vi.fn(() => true),
kill: vi.fn(() => true),
getForegroundProcess: vi.fn(async () => null),
// Legacy local PTYs have opaque ids and the local provider cannot recover cwd.
listProcesses: vi.fn(async () => [{ id: 'persisted-pty', cwd: '', title: 'shell' }])
})
const { worktrees } = await runtime.getWorktreePs()
expect(worktrees[0]).toMatchObject({
worktreeId: TEST_WORKTREE_ID,
hasHostSidebarActivity: true,
hasAttachedPty: true,
liveTerminalCount: 1
})
})
it('prefers migrated layout ownership over a worktree id frozen in the PTY id', async () => {
const priorWorktreeId = `${TEST_REPO_ID}::/tmp/worktree-before-rename`
const migratedPtyId = `${priorWorktreeId}@@daemon-controller-pty`
const session = makeWorkspaceSessionWithHeadlessTerminal()
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession({
...session,
tabsByWorktree: {
[TEST_WORKTREE_ID]: session.tabsByWorktree[TEST_WORKTREE_ID]!.map((tab) => ({
...tab,
ptyId: null
}))
},
terminalLayoutsByTabId: {
'host-tab': makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: migratedPtyId })
}
})
const runtime = new OrcaRuntimeService(runtimeStore as never)
runtime.setPtyController({
write: vi.fn(() => true),
kill: vi.fn(() => true),
getForegroundProcess: vi.fn(async () => null),
listProcesses: vi.fn(async () => [{ id: migratedPtyId, cwd: '', title: 'shell' }])
})
const { worktrees } = await runtime.getWorktreePs()
expect(worktrees[0]).toMatchObject({
worktreeId: TEST_WORKTREE_ID,
hasHostSidebarActivity: true,
hasAttachedPty: true,
liveTerminalCount: 1
})
})
it('preserves deferred startup activity before restored terminal panes mount', async () => {
const session = makeWorkspaceSessionWithHeadlessTerminal({
activeWorktreeIdsOnShutdown: [TEST_WORKTREE_ID]
})
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(session)
const runtime = new OrcaRuntimeService(runtimeStore as never)
runtime.setPtyController({
write: vi.fn(() => true),
kill: vi.fn(() => true),
getForegroundProcess: vi.fn(async () => null),
listProcesses: vi.fn(async () => [])
})
const { worktrees } = await runtime.getWorktreePs()
expect(worktrees[0]).toMatchObject({
worktreeId: TEST_WORKTREE_ID,
hasHostSidebarActivity: true
})
})
it('marks saved browser tabs as host sidebar activity like desktop', async () => {
const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession(
makeWorkspaceSessionWithHeadlessTerminal({
tabsByWorktree: {},
terminalLayoutsByTabId: {},
browserTabsByWorktree: {
[TEST_WORKTREE_ID]: [
{
id: 'browser-1',
worktreeId: TEST_WORKTREE_ID,
url: 'https://example.com',
title: 'Example',
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 1
}
]
}
})
)
const runtime = new OrcaRuntimeService(runtimeStore as never)
const { worktrees } = await runtime.getWorktreePs()
expect(worktrees[0]).toMatchObject({
worktreeId: TEST_WORKTREE_ID,
hasHostSidebarActivity: true
})
})
it('falls back to the path-keyed GitHub cache entry', async () => {
const runtimeStore = {
...store,
+95 -1
View File
@@ -7269,7 +7269,20 @@ export class OrcaRuntimeService {
}
const rendererSnapshot = await this.serializeRendererTerminalBuffer(ptyId, opts)
return rendererSnapshot ?? this.serializeProviderTerminalBuffer(ptyId, opts)
if (!rendererSnapshot) {
return this.serializeProviderTerminalBuffer(ptyId, opts)
}
if (rendererSnapshot.data.length > 0) {
return rendererSnapshot
}
// Why: parked desktop panes register serializers before their xterm has
// hydrated. Treat that empty shell as provisional so retained provider
// history can restore mobile without forcing the desktop pane to mount.
const providerSnapshot = await this.serializeProviderTerminalBuffer(ptyId, opts)
return providerSnapshot &&
(providerSnapshot.data.length > 0 || Boolean(providerSnapshot.scrollbackAnsi))
? providerSnapshot
: rendererSnapshot
}
private async serializeRendererTerminalBuffer(
@@ -8061,6 +8074,17 @@ export class OrcaRuntimeService {
])
}
// Why: connection migration replays subscriptions; use the stale-aware lane
// so a reconnect cannot turn one mobile viewer into continuous forced fetches.
async refreshAccountsForMobileSubscriber(): Promise<void> {
const { rateLimits } = this.requireAccountServices()
await Promise.allSettled([
rateLimits.refreshIfStale(),
rateLimits.fetchInactiveClaudeAccountsOnOpen(),
rateLimits.fetchInactiveCodexAccountsOnOpen()
])
}
selectClaudeAccount(accountId: string | null): Promise<ClaudeRateLimitAccountsState> {
return this.requireAccountServices().claudeAccounts.selectAccount(accountId)
}
@@ -11494,6 +11518,7 @@ export class OrcaRuntimeService {
const previousLastOutputAt = summary.lastOutputAt
summary.liveTerminalCount += 1
summary.hasAttachedPty = true
summary.hasHostSidebarActivity = true
summary.lastOutputAt = maxTimestamp(summary.lastOutputAt, pty.lastOutputAt)
summary.status = mergeWorktreeStatus(summary.status, 'active')
if (
@@ -11505,6 +11530,19 @@ export class OrcaRuntimeService {
}
const session = this.store?.getWorkspaceSession?.()
for (const worktreeId of session?.activeWorktreeIdsOnShutdown ?? []) {
const summary = this.getSummaryForRuntimeWorktreeId(
summaries,
runtimeWorktreeSummaryPathIndex,
missingRuntimeWorktreeIds,
worktreeId
)
if (summary) {
// Why: desktop advertises deferred reattach ids as live before their
// panes mount; mobile must preserve the same startup activity view.
summary.hasHostSidebarActivity = true
}
}
for (const [worktreeId, tabs] of Object.entries(session?.tabsByWorktree ?? {})) {
if (tabs.length === 0) {
continue
@@ -11534,6 +11572,23 @@ export class OrcaRuntimeService {
}
}
for (const [worktreeId, tabs] of Object.entries(session?.browserTabsByWorktree ?? {})) {
if (tabs.length === 0) {
continue
}
const summary = this.getSummaryForRuntimeWorktreeId(
summaries,
runtimeWorktreeSummaryPathIndex,
missingRuntimeWorktreeIds,
worktreeId
)
if (summary) {
// Why: desktop's sleeping predicate treats any open browser workspace
// as active, so the mobile host projection must preserve that parity.
summary.hasHostSidebarActivity = true
}
}
// Why: surface the desktop's focused worktree so mobile can scroll it into
// view and highlight it. Resolve through getSummaryForRuntimeWorktreeId so
// SSH/remote path-projected ids match the same way tabsByWorktree does.
@@ -20606,10 +20661,16 @@ export class OrcaRuntimeService {
return null
}
const sessions = sessionsResult.value
const persistedWorktreeIdByPtyId = indexPersistedPtyWorktreeBindings(
this.store?.getWorkspaceSession?.()
)
const livePtyIds = new Set(sessions.map((session) => session.id))
for (const session of sessions) {
this.adoptControllerTerminalHandle(session.id, session.terminalHandle)
// Why: workspace identity migration rekeys persisted ownership while a
// running daemon PTY keeps the worktree id minted into its session id.
const worktreeId =
persistedWorktreeIdByPtyId.get(session.id) ??
inferWorktreeIdFromPtyId(session.id) ??
findResolvedWorktreeIdForPath(resolvedWorktrees, session.cwd)
if (targetWorktreeId && worktreeId !== targetWorktreeId) {
@@ -26910,6 +26971,39 @@ function inferWorktreeIdFromPtyId(ptyId: string): string | null {
return parsePtySessionId(ptyId).worktreeId
}
function indexPersistedPtyWorktreeBindings(
session: WorkspaceSessionState | null | undefined
): ReadonlyMap<string, string> {
const worktreeIdByPtyId = new Map<string, string>()
const ambiguousPtyIds = new Set<string>()
const bind = (ptyId: string | null | undefined, worktreeId: string): void => {
if (!ptyId || ambiguousPtyIds.has(ptyId)) {
return
}
const existingWorktreeId = worktreeIdByPtyId.get(ptyId)
if (existingWorktreeId && existingWorktreeId !== worktreeId) {
// Why: corrupt/stale duplicate bindings must not attribute a live PTY to
// whichever workspace happened to be visited first.
worktreeIdByPtyId.delete(ptyId)
ambiguousPtyIds.add(ptyId)
return
}
worktreeIdByPtyId.set(ptyId, worktreeId)
}
for (const [worktreeId, tabs] of Object.entries(session?.tabsByWorktree ?? {})) {
for (const tab of tabs) {
bind(tab.ptyId, worktreeId)
bind(session?.remoteSessionIdsByTabId?.[tab.id], worktreeId)
const layout = session?.terminalLayoutsByTabId[tab.id]
for (const ptyId of Object.values(layout?.ptyIdsByLeafId ?? {})) {
bind(ptyId, worktreeId)
}
}
}
return worktreeIdByPtyId
}
function setsEqual<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean {
if (a.size !== b.size) {
return false
@@ -337,6 +337,11 @@ describe('remote runtime request connection integration', () => {
listener({ claude: null, codex: null })
}
},
refreshAccountsForMobileSubscriber: async () => {
for (const listener of accountsListeners) {
listener({ claude: null, codex: null })
}
},
onAccountsChanged: (listener: (snapshot: unknown) => void) => {
accountsListeners.add(listener)
return () => accountsListeners.delete(listener)
@@ -0,0 +1,58 @@
import { describe, expect, it, vi } from 'vitest'
import type { OrcaRuntimeService } from '../../orca-runtime'
import { isStreamingMethod } from '../core'
import { ACCOUNT_METHODS } from './accounts'
function method(name: string) {
const found = ACCOUNT_METHODS.find((candidate) => candidate.name === name)
if (!found) {
throw new Error(`Missing method ${name}`)
}
return found
}
describe('account RPC methods', () => {
it('keeps explicit account-list refreshes on the forced refresh lane', async () => {
const snapshot = { claude: null, codex: null }
const runtime = {
refreshAccountsForMobile: vi.fn().mockResolvedValue(undefined),
getAccountsSnapshot: vi.fn(() => snapshot)
} as unknown as OrcaRuntimeService
const list = method('accounts.list')
if (isStreamingMethod(list)) {
throw new Error('accounts.list must be a request method')
}
await expect(list.handler(undefined, { runtime })).resolves.toBe(snapshot)
expect(runtime.refreshAccountsForMobile).toHaveBeenCalledOnce()
})
it('uses a stale-aware refresh when a connection replays the subscription', async () => {
const snapshot = { claude: null, codex: null }
let cleanup: (() => void) | undefined
const runtime = {
getAccountsSnapshot: vi.fn(() => snapshot),
onAccountsChanged: vi.fn(() => vi.fn()),
registerSubscriptionCleanup: vi.fn((_id: string, nextCleanup: () => void) => {
cleanup = nextCleanup
}),
refreshAccountsForMobile: vi.fn().mockResolvedValue(undefined),
refreshAccountsForMobileSubscriber: vi.fn().mockResolvedValue(undefined)
} as unknown as OrcaRuntimeService
const subscribe = method('accounts.subscribe')
if (!isStreamingMethod(subscribe)) {
throw new Error('accounts.subscribe must be a streaming method')
}
const emit = vi.fn()
const running = subscribe.handler(undefined, { runtime, connectionId: 'connection-1' }, emit)
await vi.waitFor(() => {
expect(runtime.refreshAccountsForMobileSubscriber).toHaveBeenCalledOnce()
})
expect(runtime.refreshAccountsForMobile).not.toHaveBeenCalled()
expect(emit).toHaveBeenCalledWith(expect.objectContaining({ type: 'ready', snapshot }))
cleanup?.()
await running
})
})
+4 -4
View File
@@ -92,11 +92,11 @@ export const ACCOUNT_METHODS: readonly RpcAnyMethod[] = [
)
// Why: emit the current snapshot synchronously so the phone has
// something to render immediately, then kick a forced refresh that
// will broadcast a fresh snapshot through the listener once each
// provider fetch completes.
// something to render immediately, then refresh only stale data.
// Connection cutovers replay this subscription and must not turn the
// manual-force lane into an unbounded provider-fetch loop.
emit({ type: 'ready', subscriptionId, snapshot: runtime.getAccountsSnapshot() })
void runtime.refreshAccountsForMobile()
void runtime.refreshAccountsForMobileSubscriber()
})
}
}),