Files
orca/config/scripts/linux-wayland-terminal-exercise.mjs
T
Brennan Benson 80e0bee23b fix(floating-workspace): keep agent launches from moving the main window's tab (#22603)
* fix(floating-workspace): keep agent launches from moving the main window's tab

Launching an agent from the floating workspace's "+" menu switched the main
window off whatever chat or editor tab it was showing and onto its terminals.

The main window's selection is supposed to move only for the worktree it is
showing: browser and editor tab creation, splits, moves and drops all check
`activeWorktreeId === worktreeId` before touching it. Two places did not:

- `launchAgentInNewTab` called `setActiveTabType('terminal')` without a
  worktree, which targets the active worktree whatever worktree the launch
  landed in.
- terminal `createTab` wrote the global `activeTabId` for a tab in any
  worktree.

Both now follow the store rule. The launch still selects its tab within its
own worktree, which is what the floating panel renders.

The floating titlebar button had side-stepped this with an `activate: false`
opt-out plus manual selection. That opt-out had no other caller and is removed;
the button now launches and focuses like every other entry point.

* fix(tabs): scope the remaining launch surface writes to the launch's worktree

Three more launch paths create a terminal tab and then call
`setActiveTabType('terminal')` without a worktree, which targets whatever
worktree is active when the call runs rather than the one the tab landed in:

- the paired-host agent launch, after the host's asynchronous create
- Session History resume, which can target a worktree the user is not viewing
  and activates it only afterwards
- sleeping-agent resume, which the activation gate runs after asynchronous
  readiness checks, by which time the user may have moved to another worktree

Each now names its worktree, like the local agent launch. The new tab still
lands selected when the user switches to that worktree.

* test(tabs): pin the paired-host launch scope in its existing web-runtime test

* test(tabs): type the left-worktree resume fixture instead of casting it

* refactor(tabs): require the worktree that setActiveTabType applies to

`setActiveTabType(type, worktreeId?)` quietly fell back to the active
worktree when the caller left the worktree out. A caller acting on a tab in
another worktree (the floating workspace, a background launch, a reveal that
lands after an async step) therefore retyped whatever the main window was
showing. The launch paths fixed earlier in this branch were instances of that;
54 other callers still relied on the fallback.

The worktree is now a required argument (nullable only for the no-active-
worktree case), so every caller states which worktree it means and a new
unscoped call fails to compile. Each call site passes the worktree of the tab
it acts on; where that is by construction the active worktree (shortcuts,
palette, tab strip), the result is unchanged. `activateTabAndFocusPane`
resolves the tab's owning worktree the same way `setActiveTab` does.

End-to-end helpers that drive the store directly pass the active worktree,
which keeps their previous behaviour.

* fix(floating-workspace): let the floating New Terminal activate its own tab

The floating "+" New Terminal created its tab with `activate: false` and then
selected it with `activateTab`, because creating an active tab used to write
the main window's selected tab even for another worktree. `createTab` now
activates a tab only within its own worktree's group unless that worktree is
the one on screen, so the workaround is no longer needed.

Creating the tab active also moves the floating workspace's remembered tab to
the new one; before, it stayed on the previously selected floating tab, which
auto-acknowledge reads to decide which floating agent the user is looking at.

* refactor(floating-workspace): route every floating New Terminal through one creator

The floating "+" New Terminal had stopped deferring activation, but Cmd+T with the
floating panel focused still went through a separate creator that created the tab
inactive and activated it by hand, which left the floating workspace's remembered tab
on the previous tab. Both now call createFloatingWorkspaceTerminalTab, which creates
the tab active in its own group and focuses it.

* docs(tabs): say why an unowned tab id keeps the on-screen worktree scope
2026-09-24 10:54:43 -07:00

358 lines
12 KiB
JavaScript

import { writeFileSync } from 'node:fs'
import path from 'node:path'
import { runWithTimeout } from './linux-wayland-validation-watchdog.mjs'
const terminalWaitTimeoutMs = 45_000
const pollTimeoutMs = 2_500
const rendererActionTimeoutMs = 10_000
const rendererSetupTimeoutMs = 30_000
const typingSamples = 'abcdefghijklmnop'
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function interactivePromptScript(runId) {
return `
process.stdin.setEncoding('utf8')
if (process.stdin.isTTY) process.stdin.setRawMode(true)
process.stdin.resume()
let seq = 0
const interrupt = String.fromCharCode(3)
process.stdout.write('WAYLAND_TYPING_READY_${runId}\\n')
process.stdin.on('data', (chunk) => {
if (chunk.includes(interrupt)) {
process.exit(0)
}
for (const char of chunk) {
if (char === '\\r' || char === '\\n') continue
seq += 1
process.stdout.write('WAYLAND_TYPED_${runId}_' + seq + ':' + char + '\\n')
}
})
`
}
async function pollWithTimeout(label, read) {
const readPromise = Promise.resolve().then(read)
readPromise.catch(() => undefined)
// Why: the unfixed Wayland GPU stall can freeze renderer protocol calls, so
// each poll needs its own deadline instead of relying only on waitFor's loop.
const result = await Promise.race([
readPromise.then((value) => ({ timedOut: false, value })),
delay(pollTimeoutMs).then(() => ({ timedOut: true, value: null }))
])
if (result.timedOut) {
throw new Error(`Timed out polling ${label} after ${pollTimeoutMs}ms.`)
}
return result.value
}
async function waitFor(label, read, timeout = terminalWaitTimeoutMs) {
const startedAt = Date.now()
let lastValue
while (Date.now() - startedAt < timeout) {
lastValue = await pollWithTimeout(label, read)
if (lastValue) {
return lastValue
}
await delay(50)
}
throw new Error(`Timed out waiting for ${label}; last value: ${JSON.stringify(lastValue)}`)
}
async function getTerminalContent(page, charLimit = 12_000) {
return page.evaluate((limit) => {
const store = window.__store
if (!store || !window.__paneManagers) {
return ''
}
const state = store.getState()
const worktreeId = state.activeWorktreeId
const tabId =
state.activeTabType === 'terminal'
? state.activeTabId
: worktreeId
? (state.activeTabIdByWorktree?.[worktreeId] ?? null)
: null
const manager = tabId ? window.__paneManagers.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
return (pane?.serializeAddon?.serialize?.() ?? '').slice(-limit)
}, charLimit)
}
async function sendToTerminal(page, ptyId, text) {
await runWithTimeout(
'terminal input write',
() =>
page.evaluate(
({ ptyId: id, text: input }) => {
window.api.pty.write(id, input)
},
{ ptyId, text }
),
rendererActionTimeoutMs
)
}
async function focusActiveTerminal(page) {
await runWithTimeout(
'active terminal focus',
() =>
page.evaluate(() => {
const store = window.__store
const state = store?.getState()
const worktreeId = state?.activeWorktreeId
const tabId =
state?.activeTabType === 'terminal'
? state.activeTabId
: worktreeId
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
: null
const manager = tabId ? window.__paneManagers?.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
if (!pane) {
throw new Error('No active terminal pane to focus.')
}
pane.terminal.focus()
pane.container.querySelector('.xterm-helper-textarea')?.focus()
}),
rendererActionTimeoutMs
)
}
export async function setupTerminal(page, repoPath, logPhase) {
logPhase('setup.wait-store')
await waitFor('renderer store exposure', () => page.evaluate(() => Boolean(window.__store)))
logPhase('setup.wait-hydration')
await waitFor('workspace session hydration', () =>
page.evaluate(() => {
const state = window.__store?.getState?.()
return Boolean(state?.workspaceSessionReady && state?.hydrationSucceeded)
})
)
logPhase('setup.add-repo')
const repoId = await runWithTimeout(
'repo registration',
() =>
page.evaluate(async (pathToAdd) => {
const result = await window.api.repos.add({ path: pathToAdd, kind: 'git' })
if ('error' in result) {
throw new Error(result.error)
}
const store = window.__store
if (!store) {
throw new Error('window.__store is not available.')
}
await store.getState().fetchRepos()
await store.getState().fetchWorktrees(result.repo.id, { requireAuthoritative: true })
return result.repo.id
}, repoPath),
rendererSetupTimeoutMs
)
// Why: startup hydration can reset activeWorktreeId; after it completes, set
// worktree, tab, and visible type in one renderer transaction for CI setup.
logPhase('setup.activate-worktree')
await waitFor('active terminal workspace setup', () =>
page.evaluate((id) => {
const store = window.__store
if (!store) {
return false
}
let state = store.getState()
const worktree = state.worktreesByRepo[id]?.[0]
if (!worktree) {
return false
}
state.setActiveWorktree(worktree.id)
state = store.getState()
const tabs = state.tabsByWorktree[worktree.id] ?? []
const tab =
tabs[0] ??
state.createTab(worktree.id, undefined, undefined, {
activate: true,
pendingActivationSpawn: true
})
state = store.getState()
state.setActiveTab(tab.id)
state.setActiveTabType('terminal', worktree.id)
state = store.getState()
if (
state.activeWorktreeId !== worktree.id ||
state.activeTabType !== 'terminal' ||
state.activeTabId !== tab.id
) {
return false
}
return true
}, repoId)
)
logPhase('setup.wait-pty')
const ptyId = await waitFor('active terminal PTY binding', () =>
page.evaluate(() => {
const store = window.__store
const state = store?.getState()
const tabId = state?.activeTabId
const manager = tabId ? window.__paneManagers?.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
return pane?.container?.dataset?.ptyId ?? null
})
)
logPhase('setup.pty-bound', `ptyId=${String(ptyId)}`)
return ptyId
}
export async function assertScrollbackBufferWorks(page, ptyId, runId, logPhase) {
logPhase('scroll.send-start')
await sendToTerminal(
page,
ptyId,
`for i in $(seq 1 160); do echo WAYLAND_SCROLL_${runId}_$i; done\r`
)
logPhase('scroll.send-done')
await waitFor('terminal scrollback marker', async () =>
(await getTerminalContent(page)).includes(`WAYLAND_SCROLL_${runId}_160`)
)
logPhase('scroll.marker-seen')
await focusActiveTerminal(page)
logPhase('scroll.focused')
const before = await waitFor('scrollable terminal buffer', () =>
page.evaluate(() => {
const store = window.__store
const state = store?.getState()
const worktreeId = state?.activeWorktreeId
const tabId =
state?.activeTabType === 'terminal'
? state.activeTabId
: worktreeId
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
: null
const manager = tabId ? window.__paneManagers?.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
if (!pane) {
return null
}
const buffer = pane.terminal.buffer.active
if (buffer.baseY < 40) {
return null
}
pane.terminal.scrollToBottom()
if (buffer.viewportY < buffer.baseY - 1) {
return null
}
const target =
pane.container.querySelector('.xterm-screen') ??
pane.container.querySelector('.xterm-viewport') ??
pane.terminal.element ??
pane.container
if (!(target instanceof HTMLElement)) {
return null
}
const viewport = pane.container.querySelector('.xterm-viewport')
const rect = target.getBoundingClientRect()
if (rect.width <= 0 || rect.height <= 0) {
return null
}
return {
viewportY: buffer.viewportY,
baseY: buffer.baseY,
scrollTop: viewport instanceof HTMLElement ? viewport.scrollTop : null,
screenWidth: rect.width,
screenHeight: rect.height
}
})
)
logPhase('scroll.buffer-ready', `baseY=${before.baseY} viewportY=${before.viewportY}`)
// Why: headless Wayland does not provide a reliable native wheel path in CI,
// so verify xterm's scrollback buffer can move without bypassing the renderer.
await runWithTimeout(
'terminal scrollback API scroll',
() =>
page.evaluate(() => {
const store = window.__store
const state = store?.getState()
const worktreeId = state?.activeWorktreeId
const tabId =
state?.activeTabType === 'terminal'
? state.activeTabId
: worktreeId
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
: null
const manager = tabId ? window.__paneManagers?.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
if (!pane) {
throw new Error('No active terminal pane for scrollback API scroll.')
}
pane.terminal.scrollLines(-10)
}),
rendererActionTimeoutMs
)
logPhase('scroll.api-scroll-sent')
const after = await waitFor('terminal scrollback API response', () =>
page.evaluate((previousViewportY) => {
const store = window.__store
const state = store?.getState()
const worktreeId = state?.activeWorktreeId
const tabId =
state?.activeTabType === 'terminal'
? state.activeTabId
: worktreeId
? (state?.activeTabIdByWorktree?.[worktreeId] ?? null)
: null
const manager = tabId ? window.__paneManagers?.get(tabId) : null
const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null
if (!pane) {
return null
}
const buffer = pane.terminal.buffer.active
const viewport = pane.container.querySelector('.xterm-viewport')
return buffer.viewportY < previousViewportY
? {
viewportY: buffer.viewportY,
previousViewportY,
baseY: buffer.baseY,
scrollTop: viewport instanceof HTMLElement ? viewport.scrollTop : null
}
: null
}, before.viewportY)
)
logPhase('scroll.response', `viewportY=${after.viewportY} previous=${after.previousViewportY}`)
return {
beforeScrollTop: before.scrollTop,
afterScrollTop: after.scrollTop,
beforeViewportY: before.viewportY,
afterViewportY: after.viewportY,
baseY: after.baseY,
screenWidth: before.screenWidth,
screenHeight: before.screenHeight
}
}
export async function assertKeyboardInputWorks(page, ptyId, repoPath, runId, logPhase) {
const scriptPath = path.join(repoPath, `.orca-wayland-typing-${runId}.mjs`)
writeFileSync(scriptPath, interactivePromptScript(runId))
logPhase('typing.prompt-send')
await sendToTerminal(page, ptyId, `node ${JSON.stringify(scriptPath)}\r`)
await waitFor('interactive prompt readiness', async () =>
(await getTerminalContent(page)).includes(`WAYLAND_TYPING_READY_${runId}`)
)
logPhase('typing.ready')
await focusActiveTerminal(page)
for (const [index, char] of [...typingSamples].entries()) {
logPhase('typing.char', `index=${index + 1}`)
await runWithTimeout(
`keyboard type ${index + 1}`,
() => page.keyboard.type(char),
rendererActionTimeoutMs
)
await waitFor(`typed marker ${index + 1}`, async () =>
(await getTerminalContent(page)).includes(`WAYLAND_TYPED_${runId}_${index + 1}:${char}`)
)
}
logPhase('typing.complete')
await sendToTerminal(page, ptyId, '\x03').catch(() => undefined)
return typingSamples.length
}