feat(mobile): combine PR sidebar and checks parity (#5641)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Orca <help@stably.ai> Co-authored-by: gsxdsm <gsxdsm@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
Orca
gsxdsm
parent
a61c549d37
commit
c9bd61376f
@@ -75,12 +75,16 @@ function createRuntime() {
|
||||
])
|
||||
const resizes: { ptyId: string; cols: number; rows: number }[] = []
|
||||
const driverEvents: { ptyId: string; driver: { kind: string; clientId?: string } }[] = []
|
||||
let resizeSucceeds = true
|
||||
|
||||
runtime.setPtyController({
|
||||
write: () => true,
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null,
|
||||
resize: (ptyId, cols, rows) => {
|
||||
if (!resizeSucceeds) {
|
||||
return false
|
||||
}
|
||||
ptySizes.set(ptyId, { cols, rows })
|
||||
resizes.push({ ptyId, cols, rows })
|
||||
return true
|
||||
@@ -103,7 +107,15 @@ function createRuntime() {
|
||||
}
|
||||
})
|
||||
|
||||
return { runtime, ptySizes, resizes, driverEvents }
|
||||
return {
|
||||
runtime,
|
||||
ptySizes,
|
||||
resizes,
|
||||
driverEvents,
|
||||
setResizeSucceeds: (next: boolean) => {
|
||||
resizeSucceeds = next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('mobile presence lock — driver state machine', () => {
|
||||
@@ -303,9 +315,9 @@ describe('mobile presence lock — multi-mobile semantics', () => {
|
||||
const before = driverEvents.length
|
||||
|
||||
// Keyboard opens — viewport shrinks.
|
||||
expect(await runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })).toBe(
|
||||
true
|
||||
)
|
||||
await expect(
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
).resolves.toEqual({ updated: true, applied: true })
|
||||
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 16 })
|
||||
expect(runtime.getDriver('pty-1')).toEqual({ kind: 'mobile', clientId: 'phone-A' })
|
||||
@@ -320,9 +332,9 @@ describe('mobile presence lock — multi-mobile semantics', () => {
|
||||
expect(await runtime.handleMobileSubscribe('pty-1', 'phone-A')).toBe(false)
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
|
||||
expect(await runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })).toBe(
|
||||
true
|
||||
)
|
||||
await expect(
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
).resolves.toEqual({ updated: true, applied: true })
|
||||
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 16 })
|
||||
expect(await runtime.reclaimTerminalForDesktop('pty-1')).toBe(true)
|
||||
@@ -339,6 +351,29 @@ describe('mobile presence lock — multi-mobile semantics', () => {
|
||||
expect(runtime.getLastRendererSize('pty-1')).toEqual({ cols: 132, rows: 44 })
|
||||
})
|
||||
|
||||
it('updateMobileViewport records viewport without applying layout in desktop mode', async () => {
|
||||
const { runtime, ptySizes } = createRuntime()
|
||||
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 })
|
||||
runtime.setMobileDisplayMode('pty-1', 'desktop')
|
||||
await runtime.applyMobileDisplayMode('pty-1')
|
||||
|
||||
await expect(
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
).resolves.toEqual({ updated: true, applied: false })
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 150, rows: 40 })
|
||||
})
|
||||
|
||||
it('updateMobileViewport reports applied=false when phone-fit resize fails', async () => {
|
||||
const { runtime, ptySizes, setResizeSucceeds } = createRuntime()
|
||||
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 38 })
|
||||
setResizeSucceeds(false)
|
||||
|
||||
await expect(
|
||||
runtime.updateMobileViewport('pty-1', 'phone-A', { cols: 49, rows: 16 })
|
||||
).resolves.toEqual({ updated: true, applied: false })
|
||||
expect(ptySizes.get('pty-1')).toEqual({ cols: 49, rows: 38 })
|
||||
})
|
||||
|
||||
it('updateDesktopViewport records geometry without resizing while mobile is driving', async () => {
|
||||
const { runtime, ptySizes, resizes } = createRuntime()
|
||||
await runtime.handleMobileSubscribe('pty-1', 'phone-A', { cols: 49, rows: 20 })
|
||||
|
||||
@@ -11,7 +11,29 @@ const MOBILE_DYNAMIC_RPC_METHODS = [
|
||||
'github.updateIssue',
|
||||
'github.updatePRState',
|
||||
'gitlab.updateIssue',
|
||||
'gitlab.updateMR'
|
||||
'gitlab.updateMR',
|
||||
// PR-sidebar reads/mutations: the mobile github-pr-rpc/mutations wrappers pass
|
||||
// the method name as a positional arg to sendGithubPrRead/sendMutation, so the
|
||||
// literal sendRequest('...') scan below cannot see them. List them here so the
|
||||
// allowlist + registration are still enforced.
|
||||
'github.repoSlug',
|
||||
'github.prForBranch',
|
||||
'github.workItemDetails',
|
||||
'github.prChecks',
|
||||
'github.prCheckDetails',
|
||||
'github.listAssignableUsers',
|
||||
'github.mergePR',
|
||||
'github.setPRAutoMerge',
|
||||
'github.requestPRReviewers',
|
||||
'github.removePRReviewers',
|
||||
'github.rerunPRChecks',
|
||||
'github.updatePRTitle',
|
||||
'github.addPRReviewCommentReply',
|
||||
'github.addIssueComment',
|
||||
'github.resolveReviewThread',
|
||||
'github.project.updateIssueCommentBySlug',
|
||||
'github.project.deleteIssueCommentBySlug',
|
||||
'hostedReview.forBranch'
|
||||
]
|
||||
|
||||
const MOBILE_STREAMING_CLEANUP_RPC_METHODS = [
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable max-lines -- Why: runtime behavior is stateful and cross-cutting, so these tests stay in one file to preserve the end-to-end invariants around handles, waits, and graph sync. */
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { EventEmitter } from 'events'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { lstat, mkdir, mkdtemp, rm, writeFile } from 'fs/promises'
|
||||
@@ -472,7 +472,7 @@ vi.mock('../git/repo', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
function resetRuntimeTestMocks(): void {
|
||||
resetPlatform()
|
||||
advertisedUrlWatcher.clear()
|
||||
electronMocks.BrowserWindow.fromId.mockReset()
|
||||
@@ -659,7 +659,10 @@ afterEach(() => {
|
||||
updateGitLabMRReviewersMock.mockResolvedValue({ ok: true, reviewers: [] })
|
||||
getIssueMock.mockReset()
|
||||
getIssueMock.mockResolvedValue(null)
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(resetRuntimeTestMocks)
|
||||
afterEach(resetRuntimeTestMocks)
|
||||
|
||||
function syncSinglePty(
|
||||
runtime: OrcaRuntimeService,
|
||||
@@ -3643,8 +3646,16 @@ describe('OrcaRuntimeService', () => {
|
||||
await expect(runtime.listRepoIssues('id:repo-1', 10)).resolves.toEqual([
|
||||
{ number: 7, title: 'Remote issue list item' }
|
||||
])
|
||||
await expect(runtime.requestRepoPRReviewers('id:repo-1', 7, ['alex'])).resolves.toEqual({
|
||||
ok: true
|
||||
})
|
||||
await expect(runtime.removeRepoPRReviewers('id:repo-1', 7, ['alex'])).resolves.toEqual({
|
||||
ok: true
|
||||
})
|
||||
expect(getIssueMock).toHaveBeenCalledWith('/remote/repo', 12, 'ssh-1')
|
||||
expect(listGitHubIssuesMock).toHaveBeenCalledWith('/remote/repo', 10, undefined, 'ssh-1')
|
||||
expect(requestGitHubPRReviewersMock).toHaveBeenCalledWith('/remote/repo', 7, ['alex'], 'ssh-1')
|
||||
expect(removeGitHubPRReviewersMock).toHaveBeenCalledWith('/remote/repo', 7, ['alex'], 'ssh-1')
|
||||
})
|
||||
|
||||
it('routes runtime GitHub repo identity helpers through the selected WSL project runtime', async () => {
|
||||
@@ -12227,6 +12238,48 @@ describe('OrcaRuntimeService', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('reads the linked-PR state from the renderer repoId-keyed GitHub cache', async () => {
|
||||
// Regression: the renderer keys the PR cache by `repoId::branch`, so reading
|
||||
// only by `path::branch` missed every entry and left mobile's badge muted.
|
||||
const runtimeStore = {
|
||||
...store,
|
||||
getGitHubCache: () => ({
|
||||
pr: {
|
||||
[`${TEST_REPO_ID}::feature/foo`]: {
|
||||
data: { number: 42, state: 'merged' },
|
||||
fetchedAt: 1
|
||||
}
|
||||
},
|
||||
issue: {}
|
||||
})
|
||||
}
|
||||
const runtime = new OrcaRuntimeService(runtimeStore as never)
|
||||
|
||||
const { worktrees } = await runtime.getWorktreePs()
|
||||
const summary = worktrees.find((w) => w.worktreeId === TEST_WORKTREE_ID)
|
||||
expect(summary?.linkedPR).toEqual({ number: 42, state: 'merged' })
|
||||
})
|
||||
|
||||
it('falls back to the path-keyed GitHub cache entry', async () => {
|
||||
const runtimeStore = {
|
||||
...store,
|
||||
getGitHubCache: () => ({
|
||||
pr: {
|
||||
[`${TEST_REPO_PATH}::feature/foo`]: {
|
||||
data: { number: 7, state: 'open' },
|
||||
fetchedAt: 1
|
||||
}
|
||||
},
|
||||
issue: {}
|
||||
})
|
||||
}
|
||||
const runtime = new OrcaRuntimeService(runtimeStore as never)
|
||||
|
||||
const { worktrees } = await runtime.getWorktreePs()
|
||||
const summary = worktrees.find((w) => w.worktreeId === TEST_WORKTREE_ID)
|
||||
expect(summary?.linkedPR).toEqual({ number: 7, state: 'open' })
|
||||
})
|
||||
|
||||
it('attaches inline agent rows from the latest OSC 9999 status', async () => {
|
||||
const runtime = new OrcaRuntimeService(store)
|
||||
const leafId = '22222222-2222-4222-8222-222222222222'
|
||||
|
||||
@@ -4166,6 +4166,16 @@ export class OrcaRuntimeService {
|
||||
return this.ptyController?.getSize?.(ptyId) ?? null
|
||||
}
|
||||
|
||||
// Why: a width reflow on a normal-buffer PTY must re-stream the full
|
||||
// scrollback to mobile so it rewraps at the new cols, but alternate-screen
|
||||
// TUIs (vim, Claude Code) own their repaint and have no scrollback — for
|
||||
// those the mobile client just resizes xterm geometry and consumes the
|
||||
// TUI's own redraw, so the resize re-stream must be skipped. Returns false
|
||||
// when there is no headless emulator (resize falls back to geometry-only).
|
||||
isTerminalAlternateScreen(ptyId: string): boolean {
|
||||
return this.headlessTerminals.get(ptyId)?.emulator.isAlternateScreen ?? false
|
||||
}
|
||||
|
||||
// Why: daemon-backed PTYs that the runtime adopted after an Orca relaunch
|
||||
// start with a fresh headless emulator that has zero scrollback, even though
|
||||
// the daemon's on-disk checkpoint and the desktop xterm both contain the
|
||||
@@ -5422,11 +5432,11 @@ export class OrcaRuntimeService {
|
||||
ptyId: string,
|
||||
clientId: string,
|
||||
viewport: { cols: number; rows: number }
|
||||
): Promise<boolean> {
|
||||
): Promise<{ updated: boolean; applied: boolean }> {
|
||||
const inner = this.mobileSubscribers.get(ptyId)
|
||||
const sub = inner?.get(clientId)
|
||||
if (!sub) {
|
||||
return false
|
||||
return { updated: false, applied: false }
|
||||
}
|
||||
sub.viewport = viewport
|
||||
sub.lastActedAt = Date.now()
|
||||
@@ -5434,12 +5444,12 @@ export class OrcaRuntimeService {
|
||||
const mode = this.getMobileDisplayMode(ptyId)
|
||||
if (mode === 'desktop') {
|
||||
// Watching at desktop dims — viewport is informational only.
|
||||
return true
|
||||
return { updated: true, applied: false }
|
||||
}
|
||||
// Drive PTY dims by the most-recent-actor (just updated to this client).
|
||||
const winner = this.pickMostRecentActor(inner!)
|
||||
if (!winner) {
|
||||
return false
|
||||
return { updated: false, applied: false }
|
||||
}
|
||||
const winnerSub = inner!.get(winner.clientId)
|
||||
const driveViewport = winnerSub?.viewport ?? viewport
|
||||
@@ -5457,8 +5467,9 @@ export class OrcaRuntimeService {
|
||||
if (needsFreshSubscribeGuard) {
|
||||
this.freshSubscribeGuard.add(ptyId)
|
||||
}
|
||||
let result: ApplyLayoutResult
|
||||
try {
|
||||
await this.enqueueLayout(ptyId, {
|
||||
result = await this.enqueueLayout(ptyId, {
|
||||
kind: 'phone',
|
||||
cols: clampedCols,
|
||||
rows: clampedRows,
|
||||
@@ -5469,7 +5480,7 @@ export class OrcaRuntimeService {
|
||||
this.freshSubscribeGuard.delete(ptyId)
|
||||
}
|
||||
}
|
||||
return true
|
||||
return { updated: true, applied: result.ok }
|
||||
}
|
||||
|
||||
// Why: remote desktop clients do not have the local `pty:resize` IPC path.
|
||||
@@ -7017,9 +7028,14 @@ export class OrcaRuntimeService {
|
||||
const repo = repoById.get(worktree.repoId)
|
||||
let linkedPR: { number: number; state: string } | null = null
|
||||
const branch = worktree.branch.replace(/^refs\/heads\//, '')
|
||||
if (repo?.path && branch && ghCache) {
|
||||
const prCacheKey = `${repo.path}::${branch}`
|
||||
const cached = ghCache.pr[prCacheKey]
|
||||
if (branch && ghCache) {
|
||||
// Why: the renderer keys the PR cache by `repoId::branch` (getGitHubPRCacheKey
|
||||
// prefers repo.id over repo.path), so read by id first and fall back to path
|
||||
// for legacy/path-keyed entries. Reading only by path missed every cached
|
||||
// entry, leaving mobile's linked-PR badge stuck on the 'unknown' fallback.
|
||||
const cached =
|
||||
(repo?.id ? ghCache.pr[`${repo.id}::${branch}`] : undefined) ??
|
||||
(repo?.path ? ghCache.pr[`${repo.path}::${branch}`] : undefined)
|
||||
if (cached?.data) {
|
||||
linkedPR = { number: cached.data.number, state: cached.data.state }
|
||||
}
|
||||
@@ -9191,7 +9207,6 @@ export class OrcaRuntimeService {
|
||||
reviewers: string[]
|
||||
): Promise<Awaited<ReturnType<typeof removePRReviewers>>> {
|
||||
const repo = await this.resolveRepoSelector(repoSelector)
|
||||
this.assertHostIntegrationRepoIsLocal(repo, 'repo_pr_reviewers')
|
||||
return removePRReviewers(
|
||||
repo.path,
|
||||
prNumber,
|
||||
@@ -14352,12 +14367,6 @@ export class OrcaRuntimeService {
|
||||
throw new Error('repo_not_found')
|
||||
}
|
||||
|
||||
private assertHostIntegrationRepoIsLocal(repo: Repo, operation: string): void {
|
||||
if (repo.connectionId) {
|
||||
throw new Error(`${operation}_unsupported_for_ssh_repo`)
|
||||
}
|
||||
}
|
||||
|
||||
private requireStore(): Store {
|
||||
if (!this.store) {
|
||||
throw new Error('runtime_unavailable')
|
||||
|
||||
@@ -72,6 +72,10 @@ type TerminalMultiplexStream = {
|
||||
pendingOutput: TerminalOutputChunk[]
|
||||
pendingOutputBytes: number
|
||||
pendingOutputOverflowed: boolean
|
||||
// Why: the cols the mobile client last rewrapped to. Re-stream the full
|
||||
// scrollback only when a reflow actually changes the width.
|
||||
lastResizeCols: number | undefined
|
||||
resizeGeneration: number
|
||||
outputBatcher: ReturnType<typeof createTerminalOutputBatcher>
|
||||
unsubscribeData: () => void
|
||||
unsubscribeResize: () => void
|
||||
@@ -369,18 +373,59 @@ async function serializeBudgetedMobileSnapshot(
|
||||
return null
|
||||
}
|
||||
|
||||
// Why: mobile xterm can only re-wrap SOFT-wrapped lines on a client-side
|
||||
// term.resize(); the restored scrollback snapshot contains HARD newlines from
|
||||
// the host serialization, so a width change leaves prior output wrapped at the
|
||||
// old column count. On a real reflow we re-serialize the FULL buffer at the new
|
||||
// cols and replay it, so scrollback rewraps. Alt-screen TUIs are PTY-repainted
|
||||
// and have no scrollback, so they keep the geometry-only Resized frame.
|
||||
async function sendMobileResizeRestream(
|
||||
runtime: OrcaRuntimeService,
|
||||
ptyId: string,
|
||||
sendFrame: (opcode: TerminalStreamOpcode, payload?: Uint8Array<ArrayBufferLike>) => void,
|
||||
event: { cols: number; rows: number; displayMode: string; reason: string; seq?: number },
|
||||
shouldSend?: () => boolean
|
||||
): Promise<boolean> {
|
||||
// Why: only a true PTY geometry reflow rewraps scrollback; mode-change ticks
|
||||
// that did not change dims would re-send the whole buffer for nothing.
|
||||
if (event.reason !== 'apply-layout' || runtime.isTerminalAlternateScreen(ptyId)) {
|
||||
return false
|
||||
}
|
||||
const serialized = await serializeBudgetedMobileSnapshot(runtime, ptyId, true)
|
||||
if (!serialized) {
|
||||
return false
|
||||
}
|
||||
if (shouldSend && !shouldSend()) {
|
||||
return true
|
||||
}
|
||||
sendSnapshotFrames(sendFrame, {
|
||||
kind: 'resized',
|
||||
cols: serialized.cols,
|
||||
rows: serialized.rows,
|
||||
displayMode: event.displayMode,
|
||||
reason: event.reason,
|
||||
seq: event.seq ?? serialized.seq,
|
||||
source: serialized.source,
|
||||
truncated: false,
|
||||
truncatedByByteBudget: serialized.truncatedByByteBudget,
|
||||
data: serialized.data
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
async function updateViewportForClient(
|
||||
runtime: OrcaRuntimeService,
|
||||
ptyId: string,
|
||||
client: TerminalViewportClient,
|
||||
viewport: { cols: number; rows: number },
|
||||
defaultType: 'mobile' | 'desktop'
|
||||
): Promise<boolean> {
|
||||
): Promise<{ updated: boolean; applied: boolean }> {
|
||||
const type = client.type ?? defaultType
|
||||
if (type === 'mobile') {
|
||||
return runtime.updateMobileViewport(ptyId, client.id, viewport)
|
||||
}
|
||||
return runtime.updateDesktopViewport(ptyId, viewport)
|
||||
const updated = await runtime.updateDesktopViewport(ptyId, viewport)
|
||||
return { updated, applied: updated }
|
||||
}
|
||||
|
||||
const TerminalHandle = z.object({
|
||||
@@ -869,14 +914,14 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
if (!leaf?.ptyId) {
|
||||
throw new Error('no_connected_pty')
|
||||
}
|
||||
const updated = await updateViewportForClient(
|
||||
const viewportUpdate = await updateViewportForClient(
|
||||
runtime,
|
||||
leaf.ptyId,
|
||||
params.client,
|
||||
params.viewport,
|
||||
'mobile'
|
||||
)
|
||||
return { updated, seq: runtime.getLayout(leaf.ptyId)?.seq }
|
||||
return { ...viewportUpdate, seq: runtime.getLayout(leaf.ptyId)?.seq }
|
||||
}
|
||||
}),
|
||||
// Why: desktop remote sessions can have dozens of panes. One streaming RPC
|
||||
@@ -923,6 +968,23 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
sendFrame(streamId, TerminalStreamOpcode.Error, encodeTerminalStreamText(message))
|
||||
emit({ type: 'error', streamId, message })
|
||||
}
|
||||
const sendResizedFrame = (
|
||||
stream: TerminalMultiplexStream,
|
||||
event: { cols: number; rows: number; displayMode: string; reason: string; seq?: number }
|
||||
): void => {
|
||||
stream.lastResizeCols = event.cols
|
||||
sendFrame(
|
||||
stream.streamId,
|
||||
TerminalStreamOpcode.Resized,
|
||||
encodeTerminalStreamJson({
|
||||
cols: event.cols,
|
||||
rows: event.rows,
|
||||
displayMode: event.displayMode,
|
||||
reason: event.reason,
|
||||
seq: event.seq
|
||||
})
|
||||
)
|
||||
}
|
||||
const detachStream = (streamId: number, emitEnd: boolean): void => {
|
||||
const stream = streams.get(streamId)
|
||||
if (!stream) {
|
||||
@@ -1131,6 +1193,8 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
pendingOutput: [],
|
||||
pendingOutputBytes: 0,
|
||||
pendingOutputOverflowed: false,
|
||||
lastResizeCols: undefined,
|
||||
resizeGeneration: 0,
|
||||
outputBatcher: createTerminalOutputBatcher((data, meta) => {
|
||||
for (const chunk of splitTerminalOutputFrameChunks(data, meta)) {
|
||||
sendFrame(request.streamId, TerminalStreamOpcode.Output, chunk.bytes, chunk.seq)
|
||||
@@ -1238,6 +1302,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
source: serialized?.source,
|
||||
data: serialized?.data ?? (read.tail.length > 0 ? `${read.tail.join('\r\n')}\r\n` : '')
|
||||
})
|
||||
// Why: baseline for resize re-stream gating; the client already
|
||||
// rewrapped to these cols via the initial snapshot replay.
|
||||
stream.lastResizeCols = serialized?.cols ?? size?.cols
|
||||
stream.buffering = false
|
||||
for (const chunk of stream.pendingOutput.splice(0)) {
|
||||
stream.outputBatcher.push(chunk.data, chunk.meta)
|
||||
@@ -1248,17 +1315,51 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
|
||||
stream.unsubscribeResize = runtime.subscribeToTerminalResize(ptyId, (event) => {
|
||||
stream.outputBatcher.flush()
|
||||
sendFrame(
|
||||
request.streamId,
|
||||
TerminalStreamOpcode.Resized,
|
||||
encodeTerminalStreamJson({
|
||||
cols: event.cols,
|
||||
rows: event.rows,
|
||||
displayMode: event.displayMode,
|
||||
reason: event.reason,
|
||||
seq: event.seq
|
||||
})
|
||||
)
|
||||
const resizeGeneration = stream.resizeGeneration + 1
|
||||
stream.resizeGeneration = resizeGeneration
|
||||
const widthChanged = stream.isMobile && event.cols !== stream.lastResizeCols
|
||||
if (widthChanged) {
|
||||
stream.lastResizeCols = event.cols
|
||||
// Why: re-serialize+replay the full scrollback at the new cols so
|
||||
// restored hard-wrapped lines rewrap; the await means later live
|
||||
// output still flows on this stream after the snapshot lands.
|
||||
void sendMobileResizeRestream(
|
||||
runtime,
|
||||
ptyId,
|
||||
(opcode, payload) => sendFrame(request.streamId, opcode, payload),
|
||||
event,
|
||||
() =>
|
||||
!closed &&
|
||||
streams.get(request.streamId) === stream &&
|
||||
stream.resizeGeneration === resizeGeneration
|
||||
)
|
||||
.then((restreamed) => {
|
||||
if (
|
||||
closed ||
|
||||
streams.get(request.streamId) !== stream ||
|
||||
stream.resizeGeneration !== resizeGeneration
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (!restreamed) {
|
||||
sendResizedFrame(stream, event)
|
||||
}
|
||||
})
|
||||
// Why: if re-stream serialization/runtime throws, still emit the
|
||||
// geometry-only Resized frame so the client never misses the resize.
|
||||
.catch(() => {
|
||||
if (
|
||||
closed ||
|
||||
streams.get(request.streamId) !== stream ||
|
||||
stream.resizeGeneration !== resizeGeneration
|
||||
) {
|
||||
return
|
||||
}
|
||||
sendResizedFrame(stream, event)
|
||||
})
|
||||
return
|
||||
}
|
||||
sendResizedFrame(stream, event)
|
||||
})
|
||||
void runtime
|
||||
.waitForTerminal(request.terminal, { condition: 'exit' })
|
||||
@@ -1408,6 +1509,10 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
let cursor = 0
|
||||
let closed = false
|
||||
let buffering = true
|
||||
// Why: the cols the mobile client last rewrapped to; gate the
|
||||
// resize re-stream so it only fires on an actual width change.
|
||||
let lastResizeCols: number | undefined
|
||||
let resizeGeneration = 0
|
||||
const pendingOutput: string[] = []
|
||||
let pendingOutputBytes = 0
|
||||
let unsubscribeData = (): void => {}
|
||||
@@ -1565,6 +1670,9 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
scrollbackRows: serialized?.scrollbackRows,
|
||||
truncatedByByteBudget: serialized?.truncatedByByteBudget === true
|
||||
})
|
||||
// Why: baseline for resize re-stream gating; the client already
|
||||
// rewrapped to these cols via the initial snapshot replay.
|
||||
lastResizeCols = serialized?.cols ?? size?.cols
|
||||
buffering = false
|
||||
for (const item of pendingOutput.splice(0)) {
|
||||
outputBatcher.push(item)
|
||||
@@ -1572,11 +1680,14 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
pendingOutputBytes = 0
|
||||
outputBatcher.flush()
|
||||
|
||||
unsubscribeResize = runtime.subscribeToTerminalResize(ptyId, (event) => {
|
||||
// Why: true PTY geometry changes should be followed by the TUI's
|
||||
// redraw output, not a full scrollback replay. The client resizes
|
||||
// xterm geometry and consumes subsequent live output on this stream.
|
||||
outputBatcher?.flush()
|
||||
const sendResizedFrame = (event: {
|
||||
cols: number
|
||||
rows: number
|
||||
displayMode: string
|
||||
reason: string
|
||||
seq?: number
|
||||
}): void => {
|
||||
lastResizeCols = event.cols
|
||||
sendFrame(
|
||||
TerminalStreamOpcode.Resized,
|
||||
encodeTerminalStreamJson({
|
||||
@@ -1587,6 +1698,45 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
|
||||
seq: event.seq
|
||||
})
|
||||
)
|
||||
}
|
||||
unsubscribeResize = runtime.subscribeToTerminalResize(ptyId, (event) => {
|
||||
outputBatcher?.flush()
|
||||
const eventGeneration = resizeGeneration + 1
|
||||
resizeGeneration = eventGeneration
|
||||
// Why: a width reflow rewraps scrollback. xterm can only re-wrap
|
||||
// soft-wrapped lines, so a geometry-only Resized frame leaves the
|
||||
// hard-wrapped restored snapshot at the old cols. Re-serialize and
|
||||
// replay the full buffer at the new width instead. Non-mobile and
|
||||
// alt-screen TUIs keep the geometry-only frame + TUI redraw.
|
||||
const widthChanged = isMobile && event.cols !== lastResizeCols
|
||||
if (widthChanged) {
|
||||
lastResizeCols = event.cols
|
||||
void sendMobileResizeRestream(
|
||||
runtime,
|
||||
ptyId,
|
||||
sendFrame,
|
||||
event,
|
||||
() => !closed && resizeGeneration === eventGeneration
|
||||
)
|
||||
.then((restreamed) => {
|
||||
if (closed || resizeGeneration !== eventGeneration) {
|
||||
return
|
||||
}
|
||||
if (!restreamed) {
|
||||
sendResizedFrame(event)
|
||||
}
|
||||
})
|
||||
// Why: if re-stream serialization/runtime throws, still emit the
|
||||
// geometry-only Resized frame so the client never misses the resize.
|
||||
.catch(() => {
|
||||
if (closed || resizeGeneration !== eventGeneration) {
|
||||
return
|
||||
}
|
||||
sendResizedFrame(event)
|
||||
})
|
||||
return
|
||||
}
|
||||
sendResizedFrame(event)
|
||||
})
|
||||
|
||||
// Legacy fit-override-changed for non-mobile (desktop) subscribers
|
||||
|
||||
@@ -239,6 +239,124 @@ describe('terminal multiplex RPC', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('drops stale mobile resize re-stream completions for multiplex streams', async () => {
|
||||
const messages: string[] = []
|
||||
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
|
||||
const handlers = new Map<
|
||||
number,
|
||||
(frame: NonNullable<ReturnType<typeof decodeTerminalStreamFrame>>) => void
|
||||
>()
|
||||
const cleanups = new Map<string, () => void>()
|
||||
let resizeListener:
|
||||
| ((event: {
|
||||
cols: number
|
||||
rows: number
|
||||
displayMode: string
|
||||
reason: string
|
||||
seq: number
|
||||
}) => void)
|
||||
| undefined
|
||||
const restreamResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = []
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
serializeTerminalBuffer: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ data: 'initial', cols: 80, rows: 24 })
|
||||
.mockImplementation(
|
||||
() =>
|
||||
new Promise<{ data: string; cols: number; rows: number }>((resolve) => {
|
||||
restreamResolves.push(resolve)
|
||||
})
|
||||
),
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
isTerminalAlternateScreen: vi.fn().mockReturnValue(false),
|
||||
handleMobileSubscribe: vi.fn().mockResolvedValue(undefined),
|
||||
handleMobileUnsubscribe: vi.fn(),
|
||||
subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToTerminalResize: vi.fn((_, listener) => {
|
||||
resizeListener = listener as typeof resizeListener
|
||||
return vi.fn()
|
||||
}),
|
||||
subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToDriverChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
getTerminalFitOverride: vi.fn().mockReturnValue(null),
|
||||
getDriver: vi.fn().mockReturnValue({ kind: 'idle' }),
|
||||
registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => {
|
||||
cleanups.set(id, cleanup)
|
||||
}),
|
||||
waitForTerminal: vi.fn(() => new Promise<RuntimeTerminalWait>(() => {})),
|
||||
sendTerminal: vi.fn().mockResolvedValue({ accepted: true }),
|
||||
updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true })
|
||||
})
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
|
||||
|
||||
const dispatchPromise = dispatcher.dispatchStreaming(
|
||||
makeRequest('terminal.multiplex', {}),
|
||||
(msg) => messages.push(msg),
|
||||
{
|
||||
connectionId: 'conn-stale-multiplex-resize',
|
||||
sendBinary: (bytes) => binaryFrames.push(bytes),
|
||||
registerBinaryStreamHandler: (streamId, handler) => {
|
||||
handlers.set(streamId, handler)
|
||||
return () => handlers.delete(streamId)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((msg) => JSON.parse(msg).result?.type === 'ready')).toBe(true)
|
||||
)
|
||||
handlers.get(0)?.(
|
||||
decodeTerminalStreamFrame(
|
||||
encodeTerminalStreamFrame({
|
||||
opcode: TerminalStreamOpcode.Subscribe,
|
||||
streamId: 0,
|
||||
seq: 1,
|
||||
payload: encodeTerminalStreamJson({
|
||||
streamId: 5,
|
||||
terminal: 'terminal-1',
|
||||
client: { id: 'phone-1', type: 'mobile' }
|
||||
})
|
||||
})
|
||||
)!
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(resizeListener).toBeDefined())
|
||||
binaryFrames.splice(0)
|
||||
|
||||
resizeListener?.({ cols: 90, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 2 })
|
||||
resizeListener?.({ cols: 100, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 3 })
|
||||
await vi.waitFor(() => expect(restreamResolves).toHaveLength(2))
|
||||
|
||||
restreamResolves[1]?.({ data: 'newer', cols: 100, rows: 24 })
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
binaryFrames.some((frame) => {
|
||||
const decoded = decodeTerminalStreamFrame(frame)
|
||||
return (
|
||||
decoded?.opcode === TerminalStreamOpcode.SnapshotChunk &&
|
||||
decodeTerminalStreamText(decoded.payload) === 'newer'
|
||||
)
|
||||
})
|
||||
).toBe(true)
|
||||
)
|
||||
restreamResolves[0]?.({ data: 'older', cols: 90, rows: 24 })
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
|
||||
const snapshotData = binaryFrames
|
||||
.map((frame) => decodeTerminalStreamFrame(frame))
|
||||
.filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk)
|
||||
.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : ''))
|
||||
expect(snapshotData).toEqual(['newer'])
|
||||
|
||||
cleanups.get('terminal-multiplex:conn-stale-multiplex-resize')?.()
|
||||
await dispatchPromise
|
||||
})
|
||||
|
||||
it('flushes multibyte live output when encoded bytes reach the batch budget', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
|
||||
@@ -414,4 +414,103 @@ describe('terminal subscribe buffering', () => {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('drops stale mobile resize re-stream completions for legacy binary streams', async () => {
|
||||
const messages: string[] = []
|
||||
const binaryFrames: Uint8Array<ArrayBufferLike>[] = []
|
||||
const cleanups = new Map<string, () => void>()
|
||||
let resizeListener:
|
||||
| ((event: {
|
||||
cols: number
|
||||
rows: number
|
||||
displayMode: string
|
||||
reason: string
|
||||
seq: number
|
||||
}) => void)
|
||||
| undefined
|
||||
const restreamResolves: ((value: { data: string; cols: number; rows: number }) => void)[] = []
|
||||
const serializeTerminalBuffer = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ data: 'initial', cols: 80, rows: 24 })
|
||||
.mockImplementation(
|
||||
() =>
|
||||
new Promise<{ data: string; cols: number; rows: number }>((resolve) => {
|
||||
restreamResolves.push(resolve)
|
||||
})
|
||||
)
|
||||
const runtime = stubRuntime({
|
||||
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
|
||||
readTerminal: vi.fn().mockResolvedValue({ tail: [], truncated: false }),
|
||||
serializeTerminalBuffer,
|
||||
getTerminalSize: vi.fn().mockReturnValue({ cols: 80, rows: 24 }),
|
||||
getMobileDisplayMode: vi.fn().mockReturnValue('auto'),
|
||||
getLayout: vi.fn().mockReturnValue({ seq: 1 }),
|
||||
isTerminalAlternateScreen: vi.fn().mockReturnValue(false),
|
||||
handleMobileSubscribe: vi.fn().mockResolvedValue(undefined),
|
||||
handleMobileUnsubscribe: vi.fn(),
|
||||
subscribeToTerminalData: vi.fn().mockReturnValue(vi.fn()),
|
||||
subscribeToTerminalResize: vi.fn((_, listener) => {
|
||||
resizeListener = listener as typeof resizeListener
|
||||
return vi.fn()
|
||||
}),
|
||||
subscribeToFitOverrideChanges: vi.fn().mockReturnValue(vi.fn()),
|
||||
registerSubscriptionCleanup: vi.fn((id: string, cleanup: () => void) => {
|
||||
cleanups.set(id, cleanup)
|
||||
}),
|
||||
cleanupSubscription: vi.fn((id: string) => {
|
||||
const cleanup = cleanups.get(id)
|
||||
cleanups.delete(id)
|
||||
cleanup?.()
|
||||
}),
|
||||
waitForTerminal: vi.fn(() => new Promise<RuntimeTerminalWait>(() => {})),
|
||||
sendTerminal: vi.fn().mockResolvedValue({ accepted: true }),
|
||||
updateMobileViewport: vi.fn().mockResolvedValue({ updated: true, applied: true })
|
||||
})
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
|
||||
|
||||
const dispatchPromise = dispatcher.dispatchStreaming(
|
||||
makeRequest('terminal.subscribe', {
|
||||
terminal: 'terminal-1',
|
||||
client: { id: 'phone-1', type: 'mobile' },
|
||||
capabilities: { terminalBinaryStream: 1 }
|
||||
}),
|
||||
(msg) => messages.push(msg),
|
||||
{
|
||||
connectionId: 'conn-stale-resize',
|
||||
sendBinary: (bytes) => binaryFrames.push(bytes)
|
||||
}
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(resizeListener).toBeDefined())
|
||||
binaryFrames.splice(0)
|
||||
|
||||
resizeListener?.({ cols: 90, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 2 })
|
||||
resizeListener?.({ cols: 100, rows: 24, displayMode: 'auto', reason: 'apply-layout', seq: 3 })
|
||||
await vi.waitFor(() => expect(restreamResolves).toHaveLength(2))
|
||||
|
||||
restreamResolves[1]?.({ data: 'newer', cols: 100, rows: 24 })
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
binaryFrames.some((frame) => {
|
||||
const decoded = decodeTerminalStreamFrame(frame)
|
||||
return (
|
||||
decoded?.opcode === TerminalStreamOpcode.SnapshotChunk &&
|
||||
decodeTerminalStreamText(decoded.payload) === 'newer'
|
||||
)
|
||||
})
|
||||
).toBe(true)
|
||||
)
|
||||
restreamResolves[0]?.({ data: 'older', cols: 90, rows: 24 })
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
|
||||
const snapshotData = binaryFrames
|
||||
.map((frame) => decodeTerminalStreamFrame(frame))
|
||||
.filter((frame) => frame?.opcode === TerminalStreamOpcode.SnapshotChunk)
|
||||
.map((frame) => (frame ? decodeTerminalStreamText(frame.payload) : ''))
|
||||
expect(snapshotData).toEqual(['newer'])
|
||||
|
||||
runtime.cleanupSubscription('terminal-1:phone-1')
|
||||
await dispatchPromise
|
||||
})
|
||||
})
|
||||
|
||||
@@ -194,6 +194,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
|
||||
'github.mergePR',
|
||||
'github.setPRAutoMerge',
|
||||
'github.requestPRReviewers',
|
||||
'github.removePRReviewers',
|
||||
'github.project.listAccessible',
|
||||
'github.project.listAssignableUsersBySlug',
|
||||
'github.project.listIssueTypesBySlug',
|
||||
@@ -210,8 +211,10 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
|
||||
'github.project.updatePullRequestBySlug',
|
||||
'github.project.viewTable',
|
||||
'github.project.workItemDetailsBySlug',
|
||||
'github.prForBranch',
|
||||
'github.prFileContents',
|
||||
'github.prChecks',
|
||||
'github.prCheckDetails',
|
||||
'github.rerunPRChecks',
|
||||
'github.resolveReviewThread',
|
||||
'github.setPRFileViewed',
|
||||
@@ -239,6 +242,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
|
||||
'host.wsl.isAvailable',
|
||||
'host.wsl.listDistros',
|
||||
'hostedReview.create',
|
||||
'hostedReview.forBranch',
|
||||
'hostedReview.getCreationEligibility',
|
||||
'linear.getCustomView',
|
||||
'linear.getIssue',
|
||||
|
||||
Reference in New Issue
Block a user