Files
hapi/e2e/opencode-fork-buttons.spec.ts
T
Junmo KimandGitHub e57df1822a feat: preview forks and rewinds with the boundary the fork will use (#2421)
* refactor(hub): resolve fork and rewind boundaries in one place

Move selectForkTranscriptPrefix into forkBoundary.ts as the single home
for fork and rewind boundary resolution. Fork execution keeps calling
the same function with identical behavior; the forkTranscript module
and its tests move with it, so the next boundary consumers (preview,
token validation) extend one resolver instead of forking the rules.

* feat(shared,hub): read-only fork preview with a boundary token

Add POST /sessions/:id/fork-preview: the hub resolves the preview mode
from the live session (a running Codex with a verified completed turn
previews through it), runs the same admission guards as confirm without
taking the history-action lock, and answers with the kept tail rows,
the excluded rows, counts, and a boundary token.

Confirm accepts the token back on fork and rewind. The public wrappers
re-check it right after the history-action lock: an epoch change, new
invoked rows, or a source that started running since the preview reject
with 409 boundary_moved so the caller re-previews instead of forking a
transcript it never saw. Clients that send no token keep the legacy
behavior, and a latestCompleted preview fails closed on runners that do
not advertise the forkPreview capability, because answering it from hub
rows is the drift this replaces.

* feat(cli): codex shared runtime answers and pins its fork boundary

Add the PreviewForkBoundary RPC: the shared runtime reads its native
history and answers where each fork mode cuts - latestCompleted through
latestCompletedForkCutoff, current through the last turn (falling back
to the completed cut once a turn runs), message through the projected
turn with the steered-cut clientId rule - and names the first excluded
hub row so the hub cuts its preview tail at the same place.

Confirm accepts a preview-pinned lastTurnId: the runtime re-verifies the
turn still exists with a completed native prefix and forks through that
fixed inclusive cutoff instead of re-deriving a moving one, so a turn
that starts between preview and confirm cannot drift the boundary. The
capability is advertised as conversationHistory.forkPreview.

* feat(web): fork preview dialog fed by the hub

Replace the web-side fork boundary mirror with the hub's preview
answer: useForkFlow asks POST /sessions/:id/fork-preview, renders the
returned kept tail and excluded boundary through the regular
normalize/reduce pipeline, and confirms by echoing the boundary token.
A 409 boundary_moved refreshes the preview in place and demands a
re-confirmation, a source that starts running while the dialog is open
re-answers through the hub, and an older hub (404) falls back to the
legacy confirm dialog. forkPreview.ts keeps only the compact text
shaping; its cut rules are gone. SessionChat and SessionList share the
flow, the MessageActions fork button invokes it directly under the
message-fork testid, and the dialog's confirm stays accessible as
Fork. en and zh-CN locales and the e2e fixture/spec come along.

* feat(web): rewind preview dialog

Route rewind through the same hub-fed preview: the MessageActions
rewind button opens the rewind variant of the fork preview dialog,
which emphasizes the region the source would delete (destructive
styling, struck-through rows, and a truncation count) before confirming
with the boundary token. The runner-side fork-safe ambiguity still
offers the fork-at-boundary fallback, an older hub falls back to the
legacy rewind confirm, and the inline rewind confirmation dialog is
removed now that the preview gates the destructive action.

* test(hub): align archive cleanup timeout status with the 503 semantics

* fix(hub): reject the fork preview when the transcript moves during the boundary call

* fix(web): surface fork preview failures in the chat with a connect-error retry

* test(e2e): pin the list fork menu and opencode affordances to the preview flow

* fix(cli): make shared Codex fork previews respect forkable boundaries

The message-mode preview answered boundaries the confirm would refuse: a
historical cut whose completed-turn prefix contains an unfinished turn
only failed after the user confirmed. PreviewForkBoundary now applies
ForkConversation's terminal-status rule on the assertBoundary snapshot it
already fetched, so both sides inspect one history state.

The latestCompleted preview could also name an empty-text userMessage as
the cut row, but the projection never emits a hub row for those, so the
hub resolved a boundary that does not exist and failed with 'Fork
boundary message not found'. firstExcludedUserLocalId now skips items
without hub-visible display text, sharing the projection's rule through
userMessageDisplayText.

* fix(hub): gate the fork preview on the archived-fork admission rules

The inactive-session preview branch answered a boundary without any of
the guards the confirm enforces in forkArchivedCodexSession: an archived
Claude or OpenCode session, a diverged history, queued messages, or an
offline Runner all rendered a preview dialog that could only fail on
confirm. The admission guards now live in assertArchivedForkEligible and
run in both paths.

A latestCompleted token is only minted for a running source, so a runner
exit before the confirm used to fail with the unactionable 'No verified
completed turn' answer instead of refreshing; boundaryMovedReason now
returns boundary_moved when the source went inactive, and the client
re-previews under the archived rules.

* fix(web): replace a stale fork preview with the error dialog and honor the thinking edge

A preview refresh that failed with a non-404 error left the previous
ForkPreviewDialog mounted, so the error dialog — gated on
errorMessage && !preview — never appeared and the stale boundary token
stayed confirmable. The non-404 catch now drops the stale preview first.

The thinking-edge effect also consumed an edge that landed while the
first preview request was still in flight: neither the state nor the
legacy request existed yet, so the stale idle-time answer opened the
dialog after the turn had already started. The in-flight request intent
is now tracked in a ref the effect can re-issue from, and an edge during
a confirm RPC no longer mutates the dialog behind the mutation.

* fix(web): keep the legacy fork confirm locked while the RPC is in flight

confirmLegacy awaited the fork/rewind RPC without any pending flag, and
all three legacy confirm dialogs bind isPending to the preview-loading
state, so the confirm button never showed its confirming label and both
buttons stayed enabled: a double click submitted the fork twice and the
dialog could be dismissed mid-request. A dedicated confirming state now
covers the legacy RPC in useForkFlow and drives the three dialogs.

* fix(web): align the fork error dialogs between the chat and the list

SessionList's error dialog ignored the retry affordance the chat already
had: connect-level preview failures showed only Dismiss with the buttons
unbound to any pending state. Both components now share the same dialog
contract: Retry for connect failures, Dismiss otherwise, one action and
no duplicate Cancel, and the pending state bound to the retry fetch.

The chat's error dialog also introduced every failure as a fork even
when the failed request came from openRewind; useForkFlow now records
the failing intent and the dialog titles itself accordingly. Finally,
HappyThread's historyActionPending was hardcoded false after the preview
flow replaced the direct fork callbacks, so per-message Fork/Rewind
buttons stayed enabled while a preview request was in flight and another
click would supersede it via requestSeq; the loading state now locks them
like the pre-preview flow locked them during its RPCs.

* fix(web): clean up the fork preview dialog's confirm error and rewind footer

A failed confirm quoted the raw ApiError message ('HTTP 409 Conflict:
{...}') inside the dialog while the rest of the flow extracts the hub's
error text; the dialog now shares useForkFlow's apiErrorText. The error
also survived a background view refresh, quoting a stale boundary under
the refreshed one, and a rewind whose excluded rows were all non-text
hid the deletion summary because the section was gated on excludedTurns
being non-empty even though counts.excluded was not zero.

* fix(hub): reject the fork preview when the CLI answers a resolved error envelope

RpcHandlerManager serializes a thrown handler error as a RESOLVED
{error} envelope, so previewForkBoundary's cast answered the preview
with undefined nativeTurnId/cutBeforeLocalId and the runtime failure
was silently swallowed. Unwrap the envelope and throw so the hub
surfaces the failure like any other preview error.

* fix(web): honor the flattened summary capability on the legacy fork fallback

SessionSummary flattens conversationHistory onto metadata while the
full hub Session nests it under metadata.capabilities; the legacy
confirm only read the nested shape, so a 404 fallback from the list
sent a plain current fork for a running session that supports the
latest-completed fork. Accept both shapes.

* fix(web): offer the fork fallback when the legacy rewind is fork-safe

The legacy rewind confirm dropped the ambiguous-native-boundary fork
fallback that the preview confirm and the pre-preview dialog had: a
409 ambiguous_native_boundary_fork_safe surfaced as a dialog error
instead of offering fork-at-boundary. Mirror the preview confirm's
handling on the legacy path.

* fix(hub): catch source active transitions between fork preview and confirm

The boundary token did not record the source's active state, so a
transition between preview and confirm bypassed boundary_moved: a
stopped runner sent the confirm into the archived-fork path (uncoded
admission failure for non-Codex sources, or an archived fork that
silently ignores the previewed live cut), and a reopened session ran
the live fork with a token minted on the archived path. The rewind and
non-Codex message confirms also failed as uncoded 'Session must be
active' / 'Session is busy' on thinking edges.

ForkBoundary now carries sourceActive and boundaryMovedReason rejects
the mismatch across all modes; the rewind and live non-Codex message
cases also reject a thinking edge. latestCompleted keeps its existing
runner-exit guard for tokens minted before this field existed.

* fix(web): keep the preview confirm locked against thinking edges mid-confirm

confirmLegacy set confirmingRef but confirmPreview did not, so a
thinking edge landing while the confirm RPC was in flight re-answered
the preview behind the confirm: the dialog's view was replaced (or
unmounted into the error dialog) under a pending confirm, and the
confirm then navigated over it or threw against a dead dialog. Lock
the confirm the same way the legacy path does, and release it before
the boundary_moved re-preview so the refresh behaves like any other
in-flight preview.

* fix(web): mark the fork boundary on a current preview that excludes a running turn

A shared Codex runtime answers mode 'current' with the last completed
turn while a turn is already running in the CLI (before the hub saw
thinking), so the preview carries an excluded running turn and confirm
pins lastTurnId. The dialog gated the fork-point marker and boundary
box on kind !== 'current' and showed the full-copy footer, hiding the
cut the confirm would apply. Show the boundary section whenever the
preview carries a cut and use the latest-completed footer for a current
preview with exclusions.

* fix(hub): refuse the fork preview when the confirm's pending-fork guards would

forkConversation rejects a confirm outright while a Codex resume is
unconfirmed or an archived-fork child binding is pending on an active
source, but forkPreview ran neither check and opened a dialog whose
confirm always failed. The archived message preview also answered
without the conversationHistoryTurns entry (or pending attempt) that
forkArchivedCodexSession resolves the native turn from. Mirror all
three guards on the fork preview paths; rewind keeps its own, since
the rewind confirm runs different guards.

* fix(cli): answer the idle fork preview with a pin the confirm would accept

The idle current-mode preview pinned the last native turn without
checking its terminal prefix, so a thread holding a non-terminal turn
previewed a 200 whose confirm always failed verifyPinnedTurn with 'The
pinned fork turn no longer has a completed native history prefix'.
Validate the pin before answering and omit it when invalid: preview and
confirm then agree on the unpinned whole-history cut. Message mode also
fetched the thread twice per preview (once up front, once inside
assertBoundary); the up-front read now lives only in the branches that
need it.

* test(hub): pin the rewind route's coded 409 boundary_moved contract

The rewind route tests never sent a boundary token, so the claim that
the route maps a moved rewind boundary to a coded 409 had no coverage.
Mirror the fork route test: the boundary reaches the engine and the
structured code is returned on a 409.

* fix(hub): let a boundary-token rewind confirm reach the engine when the source went inactive

The rewind route answered 409 session_inactive before the engine ran
whenever the source had stopped, so the confirm's sourceActive
re-check was unreachable over HTTP and a confirm after the runner
exited dead-ended instead of refreshing the preview. Every rewind
token is minted on an active source, so an inactive confirm is always
a moved boundary: parse the body first and skip requireActive only
when a token is present, mirroring the fork route. Token-less legacy
rewinds keep the session_inactive 409.

* fix(web): keep the fork preview confirm locked while a refresh replaces the view

A boundary_moved refresh leaves the previous preview mounted until the
fresh answer lands, and the confirm's await only covers the refresh it
started: when a thinking edge fires a second re-preview behind that
refresh, the dialog's local pending resets and Confirm becomes
clickable on a view that is about to be replaced, re-sending the stale
boundary for another refresh. Gate Confirm on the flow's loading state
alongside the pending flag, in both the chat and the list dialogs;
Cancel stays available since closing discards the in-flight refresh.

* fix(web): refuse legacy fork dialog dismissal while the confirm RPC is pending

The legacy confirm dialogs lost the old handlers' pending guard when
they moved onto ConfirmDialog: its Cancel button honors isPending, but
Escape and the dialog's close button reach onClose unconditionally, so
dismissing mid-RPC unmounted the flow while the fork or rewind kept
running, and a later failure had nowhere to surface. Guard the legacy
fork and rewind dismissals with !confirming in the list and the chat;
the preview-route dialog already guards dismissal through its own
pending state.

* fix(hub): refuse archived-fork preview for attached runtimes

* fix(codex): name the original hub message when a fork cut starts at a queued batch
2026-11-18 10:12:23 +08:00

102 lines
5.5 KiB
TypeScript

import { expect, test } from '@playwright/test'
// OpenCode-flavor historical fork affordance: with conversationHistory
// points on every completed user turn, the Fork button must render on
// every historical user message that has a point — not only on the last
// message. The latest completed boundary keeps current-fork-only behavior.
// Holds in both `tail` and `history` view modes.
test('historical fork buttons render on every user message with a history point', async ({ page }) => {
await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html')
const userMessages = page.locator('[data-hapi-message-role="user"]')
await expect(userMessages).toHaveCount(12, { timeout: 15_000 })
const expectForksOnEveryUserCard = async () => {
const count = await userMessages.count()
expect(count).toBe(12)
for (let index = 0; index < count; index += 1) {
const card = userMessages.nth(index)
await expect(card.getByTestId('message-fork')).toHaveCount(1)
await expect(card.getByTestId('message-fork')).toBeVisible()
}
}
// Tail mode: every pointed user card renders its historical Fork button.
await expectForksOnEveryUserCard()
// The latest completed boundary keeps only-current behavior: it is an
// assistant card (not a user card) and carries a single Fork button
// that forks the current conversation rather than a historical point.
const boundaryId = await page.evaluate(() => window.__probe.boundaryId)
expect(typeof boundaryId).toBe('string')
expect(boundaryId).toMatch(/^agent-text:/)
const boundaryForkCount = await page.evaluate((id) => {
const anchor = document.getElementById(`hapi-message-${id}`)
return anchor?.querySelectorAll('[data-testid="message-fork"]').length ?? -1
}, boundaryId)
expect(boundaryForkCount).toBe(1)
// History mode: scroll away from the bottom, then the remembered tail
// boundary still applies and every pointed user card keeps its button.
const viewport = page.locator('.app-scroll-y')
await expect(viewport).toBeVisible()
const overflow = await page.evaluate(() => {
const el = document.querySelector('.app-scroll-y') as HTMLElement
return { scrollHeight: el.scrollHeight, clientHeight: el.clientHeight, scrollTop: el.scrollTop }
})
expect(overflow.scrollHeight).toBeGreaterThan(overflow.clientHeight)
expect(overflow.scrollTop).toBeGreaterThan(0)
// Scroll away from the bottom with a real wheel gesture: the smart-scroll
// controller only honors explicit upward intent (wheel/pointer) as a mode
// switch, and programmatic scrollTop can be swallowed by initial settling.
await viewport.hover()
for (let i = 0; i < 12; i += 1) {
await page.mouse.wheel(0, -800)
await page.waitForTimeout(100)
}
await expect.poll(async () => await page.evaluate(() => window.__probe.viewMode)).toBe('history')
await expectForksOnEveryUserCard()
const historyBoundaryId = await page.evaluate(() => window.__probe.boundaryId)
expect(historyBoundaryId).toBe(boundaryId)
})
test('historical assistant replies fork at the next user boundary; latest forks current', async ({ page }, testInfo) => {
await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html')
const replies = page.locator('[data-hapi-message-role="assistant"]')
await expect(replies).toHaveCount(12)
for (let i = 0; i < 12; i += 1) {
await expect(replies.nth(i).getByTestId('message-fork')).toHaveCount(1)
}
await page.waitForTimeout(2000)
// A plain coordinate click races the tail auto-follow scroll (the card
// intercepts the pointer); dispatch the activation on the button itself.
await replies.nth(2).getByTestId('message-fork').dispatchEvent('click')
// The fork affordance hands the requested boundary straight to the
// preview flow host; the fixture records the call synchronously.
await expect(page.getByTestId('probe-fork-calls')).toHaveText('u-local-4,', { timeout: 10_000 })
await page.screenshot({ path: testInfo.outputPath('historical-fork-fixed.png') })
await replies.last().getByTestId('message-fork').dispatchEvent('click')
// The latest completed boundary forks the current tail (no localId).
await expect(page.getByTestId('probe-fork-calls')).toHaveText('u-local-4,undefined,', { timeout: 10_000 })
})
test('does not offer an assistant fork across a missing native boundary', async ({ page }) => {
await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html?missingPoint=1')
const replies = page.locator('[data-hapi-message-role="assistant"]')
await expect(replies).toHaveCount(12)
await expect(replies.nth(2).getByTestId('message-fork')).toHaveCount(0)
await expect(replies.nth(1).getByTestId('message-fork')).toHaveCount(1)
await expect(replies.last().getByTestId('message-fork')).toHaveCount(1)
})
test('reasoning replies keep historical fork controls on the rendered card', async ({ page }) => {
await page.goto('/e2e-fixtures/opencode-fork-buttons-fixture.html?reasoning=1')
const replies = page.locator('[data-hapi-message-role="assistant"]')
await expect(replies).toHaveCount(12)
for (let i = 0; i < 12; i += 1) {
await expect(replies.nth(i).getByTestId('message-fork')).toHaveCount(1)
}
await page.waitForTimeout(2000)
await replies.nth(2).getByTestId('message-fork').dispatchEvent('click')
await expect(page.getByTestId('probe-fork-calls')).toHaveText('u-local-4,', { timeout: 10_000 })
})