Skip to content

feat(studio): play a scenario with a paused or a running clock - #32

Merged
92Infinitus92 merged 23 commits into
feat/scenarios/override/scenario-playback-supportfrom
feat/studio/play-clock-modes
Nov 2, 2026
Merged

92Infinitus92 merged 23 commits into
feat/scenarios/override/scenario-playback-supportfrom
feat/studio/play-clock-modes

Conversation

@92Infinitus92

@92Infinitus92 92Infinitus92 commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #31 (feat/studio/play-modes).

What

Play becomes a menu with two options for every scenario:

  • Play with paused clock: what fix(studio): play a scenario one column per produced slot #31 does. Register the column, pause, advance one slot so the column lands; Step registers the next column and advances one slot.
  • Play with running clock: register the column only. The surfnet produces the next block on its own and the column lands with it; Step registers the next column. No pause, no time travel.

Either way a column is registered only when the user reaches it, so nothing lands early. While Play starts, the menu button is locked and shows a spinner, so a second Play is ignored; Step and Stop are locked the same way while a step runs (from #31).

When a column uses a template tagged clock-sensitive, one line under the player says: "Time-sensitive scenario: pausing the clock may make the program refuse transactions due to time mismatches. Running clock is recommended."

Why

This is the proposal from the Slack thread with Micaiah: a way to play without pausing the clock, and a warning for scenarios where pausing breaks them. A paused clock leaves accounts fetched from mainnet ahead of the surfnet's time, and programs that compare the two refuse transactions (Whirlpool InvalidTimestamp, Project 0 PythPushStalePrice). The tag comes from LimeChain/surfpool#39.

Fetch before use in presets

The PumpSwap price shock preset and the four Phoenix presets (market price move, oracle price, collateral liquidation, maintenance margin) get a Fetch before use switch. PumpSwap keeps it on by default as before; Phoenix keeps it off, as upstream's presets set it, because a refetch replaces one Phoenix account apart from the market's others (the Phoenix README explains what breaks). With it on, Play replaces the account with the upstream copy before writing it, which overwrites state prepared in the local VM, for example by a script. With it off, Play writes the account as it is in the local VM; an account that is not there is skipped, and the line under the switch says so.

Changes

apps/studio/src/components/svm/scenario-editor.tsx

  • PlayClock ('paused' | 'running') kept while playing; startPlay(clock) behind upstream's handlePlay guard, with handlePlayPaused / handlePlayRunning; Step advances the clock only in paused mode.
  • Stop now resumes the clock in paused mode (it never did); Stop and Complete share resumeClock. When a paused Play cannot advance, the clock is resumed and the next Play registers the first column again.
  • templateTags from the unfiltered template list; isClockSensitive drives the warning line.
  • The Play button is a Dropdown from @surfpool/ui, disabled with a spinner while Play starts.

apps/studio/src/lib/surfnet-clock.ts

  • setSurfnetClockPaused(rpcUrl, paused): one pause/resume call that dispatches clockPauseStateChanged. It replaces the four hand-written copies in the editor, explorer-header.tsx and slot-grid.tsx.

apps/studio/src/components/svm/slot-grid.tsx

  • ignoreSlotEvents is gone: nothing has read it since the auto-resume check it guarded was removed.

apps/studio/src/components/svm/fetch-before-use-switch.tsx

  • The switch and one line on what Play does in each position.

pump-swap-price-shock-dialog.tsx, phoenix-state-dialog.tsx, apps/studio/src/lib/scenarios-api.ts

  • The dialogs pass the switch to createPumpSwapPriceShockScenario and to the Phoenix scenario builders (fetchBeforeUse = false unless given), which used to hard-code it.

Tests: running Play never pauses or time travels and registers one column per Play and Step; paused Stop resumes the clock; a paused Play that cannot advance resumes the clock and registers the column again next time; a second Play while the first registers is ignored, and so is a second Step with the running clock; both menu items always present, the warning only with a clock-sensitive template; setSurfnetClockPaused success and failure; the switch defaults, its value reaches the scenario JSON (PumpSwap and Phoenix). Upstream's processed-slot Step test now opens the Play menu.

Verification

step price slot
paused Play 85, mainnet publish time frozen
paused Step 90, same publish time +1, frozen
Complete 90 running again
running Play 85, newer publish time running
running Step 90, same publish time running

The warning line and the Play menu show for this scenario. Phoenix market move created with the switch off and on: both overrides carry fetchBeforeUse false and true.

  • Live before the upstream merge, real swaps on the Whirlpool SOL/USDC pool (fee 1000 in column 1, fee 2000 in column 2):
state fee_rate 1 SOL -> USDC output / price
before Play 400 101.702373 0.99960
running Play, column 1 1000 101.624391 0.99900
Step, column 2 2000 101.522584 0.99800
after Complete 2000 101.522504 0.99800
  • Fetch before use, live before the upstream merge on the canonical PumpSwap pool of 288k7P6sZA7cHGPATbKBHjqgditapKkVXjkAXKH3pump, with lp_supply set to 777 in the local VM before each running-clock Play:
switch lp_supply after Play virtual_quote_reserves after Play
off 777, the local value 15000000000000
on 4193388285737, the mainnet value 20000000000000

Not in this PR

A per-column slot number (gaps between columns), and Play with the running clock while the clock was paused from the header (nothing lands until it is resumed). The switch for Pump graduation: its MCP tool sets the flag itself, so it needs a backend change first.

🤖 Generated with Claude Code

https://claude.ai/code/session_01CkgCK6kr7c138a1U8kmaN4

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Play becomes a dropdown with two modes. Paused keeps the #31 behaviour: register the column, pause, then time-travel one slot. Running only registers the column and lets the next block apply it. A warning line appears when a template is tagged clock-sensitive. Four hand-written pause/resume RPC calls are replaced by one shared helper, setSurfnetClockPaused. The refactor is clean and tested. Stop now resumes the clock in paused mode, which fixes a real gap.

Concerns

  • Running mode has no landing guarantee or in-flight guard. Step registers column N+1 and marks it current right away. If the user clicks Step again before the surfnet produces a block, column N+1 can replace column N before N lands (both use the same scenario id), so a column is silently skipped. Ways to fix this:

    • wait for a slot change (getSlot or the websocket) before allowing the next Step, or
    • at least disable Step while a step is in progress.

    This also applies to the gap between Play and the first Step.

  • Paused-mode Play failure leaves the clock paused. If advanceOneSlot fails, handlePlay returns while still in read mode, so there is no Stop button to resume the clock. Also, registeredColumnRef stays 0, so a retry skips registration. The same happens when the pause call itself fails: the code only logs it, then time-travels with the clock still running. Calling resumeClock() on the failure path, or aborting on pause failure, would keep things consistent. This was partly true before the PR, but now that a resume helper exists it is an easy fix.

  • Stop/Complete in paused mode always resume the clock, even when the user had paused it from the header before pressing Play. You could record the earlier pause state and restore it instead. Minor.

  • The PR notes that running mode with a clock paused from the header lands nothing. Since the header already tracks isClockPaused through clockPauseStateChanged, a small hint or a disabled menu item would be cheap to add.

Overall it looks good to merge once the running-mode Step race is addressed or acknowledged.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In running mode nothing waits for the registered column to land. A second Step (or the first Step right after Play) inside one block interval registers column N+1 over column N, since both use the same scenario id, so N may never apply. You could wait for the slot to advance before moving currentPlaybackSlot forward, or disable Step while a step is in progress.

if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');
} else {
console.error('Error pausing clock');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A failed pause is only logged, and the code then goes on to advanceOneSlot() with the clock still running. That is not the paused-clock behaviour the user picked. It is probably better to abort Play here.

if (firstSlot && !(await advanceOneSlot())) {
return;
if (firstSlot && !(await advanceOneSlot())) {
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return leaves the clock paused while the editor stays in read mode, so Stop is not available to resume it. registeredColumnRef.current also stays 0, so a retry skips re-registration. Consider calling await resumeClock() here, or setSurfnetClockPaused(rpcUrl, false), before returning.

const handlePlayRunning = () => handlePlay('running');

const handleStop = async () => {
if (playClock === 'paused') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resumes the clock even if the user had paused it from the header before pressing Play. You could capture the pause state before Play and restore it instead. Minor.

</div>
</div>
</div>
{!!isClockSensitive && mode === 'read' && (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: isClockSensitive is already a boolean, so the !! is redundant.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Play becomes a menu with two choices, paused clock and running clock. When a scenario uses a template tagged clock-sensitive, a warning appears under the player. The four hand-written pause/resume RPC calls are merged into one helper, setSurfnetClockPaused. That helper is a good cleanup: it also tightens success detection by requiring result in the response, and it keeps the clockPauseStateChanged event in one place.

Overall the change is clean and well tested. The points below are about edge cases.

Scope: the PR also contains d85dc17, which adds a fetchBeforeUse switch to the PumpSwap and Phoenix presets. Neither the PR title nor the body mentions it. Move it to its own PR, or at least describe it in this one so reviewers know it's there.

Edge cases:

  • Running mode, fast Step clicks: each Step re-registers the scenario under the same id, which replaces the column registered before it. If the user clicks Step again before the surfnet has produced the next block (about 400ms), the previous column is overwritten and never lands. Paused mode avoids this because it waits for advanceOneSlot. Running mode has no matching wait, such as for the slot to change, before it allows the next Step.
  • Paused Play fails after pausing: if advanceOneSlot fails, handlePlay('paused') returns while the clock is paused and the editor is still in read mode. There's no Stop button in that mode, so nothing resumes the clock. A later "Play with running clock" then sees nothing land, because the clock is still paused.
  • Stop and Complete override a header pause: in paused mode both resume the clock unconditionally, even if the user had paused it from the header before pressing Play. Complete already did this before the PR, but Stop now does it too. It may be worth remembering the clock state before Play and restoring that instead.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In running mode, nothing waits here for the registered column to land before the next Step is allowed. Re-registering under the same scenario id replaces the pending column, so a quick second click (inside one block time) silently drops it. Consider waiting until the slot has advanced, or until the column is confirmed applied, before re-enabling Step.


if (firstSlot && !(await advanceOneSlot())) {
return;
if (firstSlot && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If advanceOneSlot fails here, the clock was already paused on line 1046 and the mode stays read, so no Stop button is shown and nothing resumes the clock. Resume the clock before returning (or await resumeClock() on this path).

const handlePlayRunning = () => handlePlay('running');

const handleStop = async () => {
if (playClock === 'paused') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This resumes the clock even if it was already paused from the header before Play. Consider recording whether the clock was paused before Play and restoring that state on Stop and Complete. Also, the UI only leaves play mode after the RPC round-trip finishes, so Stop can feel laggy. You could update the state first and resume the clock afterwards.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

This PR turns Play into a menu with two options: play with a paused clock (register, pause, time-travel one slot) or play with a running clock (register only). It adds a clock-sensitive warning and moves the four hand-written pause/resume RPC calls into setSurfnetClockPaused. The range also includes the fetchBeforeUse switch for the PumpSwap and Phoenix presets (d85dc17), which the PR body does not mention. It is worth calling out, or splitting into its own PR.

Overall the change is clean and the refactor removes real duplication. Stop now resumes the clock in paused mode, which is a good fix.

Issues

  • Failed paused Play leaves the surfnet stuck. If advanceOneSlot fails, the clock stays paused, the UI stays in read mode with no Stop button, and registeredColumnRef stays 0. A retry with "Play with running clock" skips registration and never resumes the clock, so nothing lands.
  • Running mode can lose columns. Step re-registers the same scenario id right away. If the user clicks Step before the surfnet produces the next block, column N may be replaced before it ever lands.
  • Pause state is not checked. As the PR notes, running Play while the clock was paused from the header does nothing. A cheap guard would help: read the current pause state and either warn or resume.
  • Minor: event dispatched from the helper. setSurfnetClockPaused now fires clockPauseStateChanged itself, so the header and slot grid also get their own event. That is harmless but redundant with their local setIsClockPaused.


if (firstSlot && !(await advanceOneSlot())) {
return;
if (firstSlot && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the time travel fails, this returns with the clock still paused, the UI in read mode (no Stop button), and registeredColumnRef.current === 0. A retry with 'Play with running clock' then skips registration (ref is 0) and never resumes the clock, so column 0 never lands. On this failure path, consider resuming the clock (or at least resetting the ref).

})
);
if (clock === 'paused') {
if (await setSurfnetClockPaused(rpcUrl, true)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A failed pause is only logged, and the flow still time-travels and enters play mode with playClock='paused'. With the clock actually running, Step will time-travel on top of normal block production. Consider aborting Play here, like the advanceOneSlot failure path does.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In running mode nothing confirms that the previous column has landed before the next one is registered under the same scenario id. A quick Step (within one slot, about 400 ms) may overwrite column N before the surfnet produces its block. Consider waiting for a slot change (for example via the slot websocket event) before allowing the next Step in running mode.


const handleStop = async () => {
if (playClock === 'paused') {
await resumeClock();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stop now awaits an RPC round-trip before it updates the UI, so on a slow or unreachable RPC the Stop button seems to do nothing, and repeated clicks send repeated resumes. Consider switching to read mode first and resuming the clock afterwards (same for handleComplete).

throw new Error('Failed to fetch protocols');
}
const templates = await response.json();
setTemplateTags(Object.fromEntries(templates.map((template: any) => [template.id, template.tags ?? []])));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

template: any. A small { id: string; tags?: string[] } type would keep this typed. Also, if the templates fetch fails, templateTags stays {}, so the clock-sensitive warning silently never shows.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds a Play menu (paused vs. running clock), a clock-sensitive warning, a shared setSurfnetClockPaused helper that replaces four copy-pasted RPC calls, and a Fetch before use switch on the PumpSwap and Phoenix market presets. The refactor is clean and the tests cover the new branches well.

Most of the issues are about overrides that stay registered but haven't landed yet, and how they interact with resuming the clock or with a running clock:

  • When paused Play fails, or the user presses Stop after a failed Step, the code resumes the clock while a column is still registered. That column then lands outside playback, and registeredColumnRef still treats it as pending.
  • In running mode, Step registers the next column without waiting for the previous one to land. Clicking Step twice within one slot can overwrite a column before it lands.
  • If pausing fails in paused Play, the code still time-travels on a running clock.

Minor: handlePlay has no in-flight guard. Each call makes several RPC round trips, so clicking a menu item twice can register or advance twice. This was already true before this PR, but the dropdown makes it easier to hit.

if (firstSlot && !(await advanceOneSlot())) {
return;
if (firstSlot && !(await advanceOneSlot())) {
await resumeClock();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When advanceOneSlot fails, column 0 is still registered (registeredColumnRef.current === 0). Resuming the clock here lets the surfnet produce the next slot on its own, so column 0 lands even though playback never started.

A retry then skips registration because the ref is still 0. A paused retry advances a slot with nothing registered, so column 0 doesn't land again.

Fix: reset registeredColumnRef.current = null here. The surfnet probably also needs an unregister or clear call before resuming. Otherwise, only resume if the clock was running before Play.

if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');
} else {
console.error('Error pausing clock');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If pausing fails, the code logs the error and continues to advanceOneSlot() anyway, so it time-travels while the clock is still running. Paused mode would then behave like neither mode. I'd abort Play here and return instead.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Running mode: Step registers column next right away, even if column next-1 hasn't landed yet. Re-registering the same scenarioId within one slot (~400 ms) would likely replace the earlier column, so it never lands.

Options: wait for the next slot notification (or poll for a higher processed slot) before allowing the next Step, or disable Step until the previous column has landed.


const handleStop = async () => {
if (playClock === 'paused') {
await resumeClock();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same issue as the failed-Play path. If a paused Step registered column next and then advanceOneSlot failed, registeredColumnRef.current is still next. Resuming the clock here applies that column after the user pressed Stop.

Also, this resumes the clock even if the user had paused it from the header before playing. Complete already did this before, but Stop never did. Consider restoring the clock state from before Play instead.

# Conflicts:
#	apps/studio/src/components/svm/scenario-editor.test.tsx
#	apps/studio/src/components/svm/scenario-editor.tsx
# Conflicts:
#	apps/studio/src/components/svm/phoenix-state-dialog.test.tsx
#	apps/studio/src/components/svm/phoenix-state-dialog.tsx
#	apps/studio/src/components/svm/scenario-editor.test.tsx
#	apps/studio/src/components/svm/scenario-editor.tsx
#	apps/studio/src/lib/scenarios-api.test.ts
#	apps/studio/src/lib/scenarios-api.ts

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The PR turns Play into a menu with two choices: paused clock (the #31 behaviour) or running clock (register the column only). It shows a warning when a column uses a template tagged clock-sensitive. It moves the four hand-written pause/resume RPC calls into setSurfnetClockPaused, removes the unused ignoreSlotEvents, and adds a "Fetch before use" switch to the PumpSwap and Phoenix preset dialogs. Overall the change is clean. The shared clock helper makes the editor, header and grid code simpler, and running mode is wired in with little code.

Issues

  • The PR description does not match the Phoenix dialog code. The description says Phoenix collateral hides the switch and that a test checks this. The head code renders FetchBeforeUseSwitch for every mode, including collateral, and passes fetchBeforeUse to createPhoenixCollateralLiquidationScenario. I found no test that checks the switch is absent in collateral mode. The description also says the switch is "on by default as before" for the Phoenix presets, but the Phoenix dialog defaults to false. That does keep the earlier behaviour for Phoenix, so only the text is wrong. Either the code or the description needs fixing.
  • Paused Stop/Complete resume the clock whatever its state was before Play. If the user paused the clock from the header before Play, Stop now resumes it. Consider remembering the clock state from before Play and restoring that.
  • A failed pause in paused mode is only logged. startPlay then goes on to advanceOneSlot (time travel) with the clock still running. Consider aborting there, or falling back to running mode.
  • Nit: !!isClockSensitive is already a boolean, so the !! is redundant.

</div>
)}
{amountField}
<FetchBeforeUseSwitch checked={fetchBeforeUse} onChange={setFetchBeforeUse} disabled={isCreating} />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR body says Phoenix collateral hides this switch and that a test covers it. Here the switch renders in every mode, and its value goes to createPhoenixCollateralLiquidationScenario on line 322. If collateral should not offer it (its flag is set on the backend side, per 'Not in this PR'), wrap the switch in {!isCollateralLiquidation && …} and pass false for collateral. Otherwise, update the description.

const [depth, setDepth] = useState<LiquidationDepth>(LiquidationDepth.OneLiquidation);
const [movePercent, setMovePercent] = useState('2');
const [unit, setUnit] = useState<PhoenixUnit>('percent');
const [fetchBeforeUse, setFetchBeforeUse] = useState(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This defaults to false, while the PR body says the Phoenix mark and maintenance-margin presets keep their default of on. false does match the earlier hard-coded Phoenix value (the comment moved into createPhoenixScenario), so the code is probably right and the description is wrong. Please fix one of them so they agree.

if (clock === 'paused') {
if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the pause fails, the code logs the error and still calls advanceOneSlot() (time travel) with the clock running. The user then gets a mode that is neither paused nor cleanly running. Consider returning here (the column is already registered, so it will land on the running clock), or switching to 'running' mode.

const handlePlayRunning = () => handlePlay('running');

const handleStop = async () => {
if (playClock === 'paused') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stop and Complete now resume the clock unconditionally in paused mode. If the user paused the clock from the header before pressing Play, ending playback silently unpauses it. Consider recording whether the clock was already paused when Play started, and resuming only if Play paused it.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The PR turns Play into a menu with two modes: paused clock (register, pause, advance one slot) and running clock (register only). It also adds a warning for clock-sensitive templates, moves the pause/resume RPC calls into setSurfnetClockPaused, and adds a Fetch before use switch to the PumpSwap and Phoenix presets.

The refactor reads cleanly. Stop now resumes the clock in paused mode, which fixes a real gap. The issues I found:

The description no longer matches the final commit (2a6185b) for Phoenix

  • The description says the switch is "on by default as before" and that "Phoenix collateral hides the switch." In the code, the Phoenix switch is off by default (useState(false)), which matches the old hard-coded false. It is also shown in every mode, including collateral liquidation, and its value reaches createPhoenixCollateralLiquidationScenario.
  • The description also says the API functions "used to hard-code true". That was only true for PumpSwap.
  • Either update the description or restore the collateral-mode hiding.

Running-clock mode has no in-flight guard

  • In paused mode, the time-travel round trip slowed Step down, which hid the missing guard. In running mode, Step just calls registerColumn and returns.
  • handleStepForward has no busy flag, and the Step button is never disabled. A fast double-click, or a Step before the surfnet produces a block, can register column N+1 over column N before N lands, so column N is skipped silently.
  • Add an isStepping guard, as handlePlay already has with isStartingPlay, and disable the Step button while it is set.

Minor points are in the inline comments.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With a running clock, this path is now just registerColumn followed by setCurrentPlaybackSlot. There is no time travel to slow it down, and nothing stops a second click: the Step button is never disabled and this handler has no busy flag. A double-click, or a Step before the next block, can register column N+1 over column N before N lands, so N is skipped. Add an in-flight guard, as handlePlay already has with isStartingPlay, and disable the Step button while it is set.

);
if (clock === 'paused') {
if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If pausing fails, Play still goes on in 'paused' mode while the clock keeps running. Each Step then time travels on a live clock, which is the mismatch this PR is trying to avoid. Consider returning early here, or falling back to 'running'.


const handlePlayRunning = () => handlePlay('running');

const handleStop = async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handleStop and handleComplete now await an RPC call before leaving play mode. During that wait, both buttons can still be clicked: a second Stop sends another resume, and a Step can register another column. Consider setting mode/isExecuting first and resuming afterwards, or disabling the buttons while the resume is pending.

</div>
</div>
</div>
{!!isClockSensitive && mode === 'read' && (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: isClockSensitive is already a boolean, so the !! is redundant.

</div>
)}
{amountField}
<FetchBeforeUseSwitch checked={fetchBeforeUse} onChange={setFetchBeforeUse} disabled={isCreating} />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The switch now shows in every mode, including collateral liquidation, and its value reaches createPhoenixCollateralLiquidationScenario. The PR description says collateral hides the switch.

The comment in createPhoenixScenario also explains why fetching is risky here: a refetch resets this account apart from the market's other accounts. The generic hint in FetchBeforeUseSwitch doesn't warn about that. Either hide the switch for collateral, which the description says this PR does, or add a Phoenix-specific warning when it is on.

const [depth, setDepth] = useState<LiquidationDepth>(LiquidationDepth.OneLiquidation);
const [movePercent, setMovePercent] = useState('2');
const [unit, setUnit] = useState<PhoenixUnit>('percent');
const [fetchBeforeUse, setFetchBeforeUse] = useState(false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This defaults to false, which matches the old Phoenix behavior. The PR description says "on by default as before" for the Phoenix presets, which doesn't match. Please update the description so reviewers and QA know what to expect.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The PR adds a Play menu with two modes (paused clock or running clock), shows a warning for templates tagged clock-sensitive, and moves four hand-written pause/resume RPC calls into one setSurfnetClockPaused helper. It also adds a Fetch before use switch to the PumpSwap and Phoenix presets. The changes are small and readable, and the tests cover the main paths. Stop now resumes the clock in paused mode and Complete does too. A paused Play that cannot advance resumes the clock and clears the registered column. Both are real fixes.

Main concerns

  • Running-clock Step does not wait for the column to land. handleStepForward registers column N+1 as soon as the user clicks. Nothing checks that column N has landed in a produced block. If the next surfnet_registerScenario replaces the previous registration (same scenarioId), a fast Step can drop a column that never applied. The same happens if the clock is paused from the header; the PR lists that case as out of scope. One fix is to keep Step disabled until a slot event arrives after the registration.
  • A failed pause is only logged. In startPlay('paused'), when the pause call fails the code still time-travels and enters play mode as paused. The clock is actually still running, so later Steps time-travel on a live clock. Consider aborting, or falling back to 'running'.
  • Stricter success check. setSurfnetClockPaused now requires data.result !== undefined. The editor's old paused-Play path only checked response.ok. This is fine as long as the RPC always returns a result field; worth a quick check.

Minor

  • !!isClockSensitive is redundant because the value is already a boolean.
  • The "on" hint in FetchBeforeUseSwitch says nothing about the risk the Phoenix README describes (a refetch puts one account out of sync with the market's other accounts). A preset-specific warning there would help users who turn it on.
  • After a successful create, the PumpSwap dialog resets the mint and reserves fields but leaves the switch where the user set it. That may be intended, but it is inconsistent.

Overall the PR is in good shape; the running-mode Step race is the main thing I'd resolve or document before merging.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With a running clock, the next column is registered right away, and nothing confirms that the previous column has landed. If the user steps within one slot (about 400ms), or the clock is paused from the header, and the next surfnet_registerScenario with the same scenarioId replaces the pending registration, column N is silently dropped. Consider waiting for a slot websocket event, or for the processed slot to pass the slot seen at registration, before enabling the next Step in running mode.

logger.log('🎬 Clock paused after scenario registration');
} else {
console.error('Error pausing clock');
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the pause fails, we still time-travel and enter play mode with playClock = 'paused', even though the clock is still running. Every later Step then time-travels a live clock, and Stop/Complete call resume on a clock that was never paused. Consider returning here (clearing the registered column the way the advance-failure branch does), or falling back to 'running'.

</div>
</div>
</div>
{!!isClockSensitive && mode === 'read' && (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: isClockSensitive is already a boolean, so the !! isn't needed.

if (!response.ok) return false;

const data = await response.json();
if (data?.result === undefined) return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check is stricter than the editor's old pause/resume path, which only checked response.ok. If surfnet_pauseClock/surfnet_resumeClock can return without a result (or with a JSON-RPC error), paused Play now logs an error but still continues (see the comment on startPlay). Consider also checking data.error, so failures are reported the same way across callers.

export default function FetchBeforeUseSwitch({ checked, onChange, disabled }: FetchBeforeUseSwitchProps) {
// DERIVED STATE
const hint = checked
? 'Play fetches each account from the upstream datasource before changing it.'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Phoenix, turning this on is the risky choice (a refetch puts one account out of sync with the market's other accounts), but the "on" hint describes it neutrally. Consider an optional warning prop so the Phoenix dialog can say this next to the switch.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overview. Play becomes a menu with two choices, paused clock or running clock. The PR also adds a clock-sensitive warning line and a "Fetch before use" switch to the PumpSwap and Phoenix presets. It merges four hand-written pause/resume RPC calls into setSurfnetClockPaused. The changes are clean and well tested, and the refactor makes the pause and resume calls stricter: data.result must be present, so JSON-RPC errors now count as failures.

Assessment. The PR looks good overall. A few things to check:

  • Pause failure is ignored in paused mode. If surfnet_pauseClock fails, Play still time-travels and the session runs with playClock = 'paused' while the clock is actually running. See the inline comment.
  • Race when Play starts with a paused clock. The first column is registered before the clock is paused. A slot produced in that window can land the column, and then advanceOneSlot moves one more slot. This came over from #31, but now that two modes exist, pausing before registering seems the safer order for paused mode.
  • Stop and Complete always resume the clock in paused mode. If the user had paused the clock from the header before pressing Play, Stop or Complete leaves it running. This may be intended, but it differs from the state the user started in. Consider saving the earlier pause state and restoring it.
  • Switch state persists. The fetchBeforeUse state in both dialogs is never reset: not after a scenario is created, and not when the dialog is reopened. PumpSwap clears tokenMint and virtualQuoteReserves after creation but keeps the switch, so a later scenario can silently reuse the previous choice.
  • Warning placement. The warning div is placed with absolute inset-x-0 top-full, so it can overlap whatever sits below the player bar. Check it on small screens.

if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');
} else {
console.error('Error pausing clock');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the pause fails, the code logs the error and keeps going. It then calls advanceOneSlot() and, at line 1051, sets playClock to 'paused' while the surfnet clock is still running. Every later Step then registers a column and time-travels on a running clock, which can land a column twice or skip slots. Consider aborting here instead: return, and set registeredColumnRef.current = null, because the registered column will land on its own. Another option is to fall back to 'running' mode.


const startPlay = async () => {
// A running clock produces the registered column's slot by itself, so only a paused one is stepped
const startPlay = async (clock: PlayClock) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In paused mode the first column is registered (above) before surfnet_pauseClock is sent. If the running clock produces a slot in between, the column lands then, and advanceOneSlot advances one slot more than intended. For clock === 'paused', pausing before registerColumn(firstSlot) would close this window.


const handlePlayRunning = () => handlePlay('running');

const handleStop = async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In paused mode, Stop always resumes the clock, even if the user had paused it from the header before pressing Play. It may be worth reading the pause state when Play starts and restoring that state here and in handleComplete.

// STATE
const [tokenMint, setTokenMint] = useState('');
const [virtualQuoteReserves, setVirtualQuoteReserves] = useState('');
const [fetchBeforeUse, setFetchBeforeUse] = useState(true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After a successful create, the dialog resets tokenMint and virtualQuoteReserves but not fetchBeforeUse. If a user turns the switch off once, the next scenario is silently created with it off. Consider resetting it to true together with the other fields. The same applies to the Phoenix dialog, which should reset to false when it opens.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Play becomes a menu with two options: paused clock (as in #31) and running clock (register the column only, and the surfnet's own next block lands it). The PR adds a clock-sensitive warning line, moves the four copies of the pause/resume code into setSurfnetClockPaused, and adds a Fetch before use switch to the PumpSwap and Phoenix presets. Overall it's clean and well tested. The shared helper removes real duplication, and dropping ignoreSlotEvents is correct because nothing reads it.

Main concerns

  • Running clock: a quick Step can overwrite a column before it lands. In running mode, Step registers the next column and moves the playhead at once, with no check that the surfnet has produced a block since the last registration. If surfnet_registerScenario replaces the scenario with the same id, Play followed by a fast Step (inside one slot, about 400 ms) replaces column N before its slot is produced, so column N never lands. The same thing happens, worse, when the clock was paused from the header. That case is listed under "Not in this PR", but nothing in the UI warns about it.
  • A failed pause still takes the paused path. If surfnet_pauseClock fails, Play still time travels and saves playClock = 'paused', even though the clock is running.
  • Stop now always resumes the clock in paused mode. It resumes it even if the user had paused the clock from the header before pressing Play. Complete already did this, but Stop now does too. You could save the pause state from before Play and restore that instead.

Minor

  • handleStop is now async and leaves play mode only after the resume RPC returns. The Stop button isn't locked in the meantime, so a double click sends two resume calls.
  • Both dialogs keep fetchBeforeUse from earlier use. PumpSwap clears its other fields after it creates a scenario but not the switch, so the next scenario silently inherits a switch the user turned off.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the running clock, nothing checks that the previous column has landed before the next one is registered. If surfnet_registerScenario replaces the scenario with the same id, a Step inside the same slot as Play (or as the previous Step) replaces column N before the surfnet produces its block, so column N never applies. Consider waiting for a new processed slot (via getEpochInfo or the slot websocket) before registering the next column, or before marking the step done.

if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');
} else {
console.error('Error pausing clock');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the pause call fails, this only logs the error and carries on. It still time travels, and line 1051 saves playClock = 'paused', but the clock is running. Then each Step time travels on a running clock, and the next produced block could land a column early. Consider resetting and returning here, as the advance-failure branch does, or falling back to 'running'.

const handlePlayRunning = () => handlePlay('running');

const handleStop = async () => {
if (playClock === 'paused') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two points. (1) This resumes the clock even if the user had paused it from the header before pressing Play. You could save the pause state from before Play and restore that. (2) Stop now waits for the RPC before it leaves play mode, and the Stop button isn't locked, so a double click sends two resume calls. Consider resetting the UI state first, or locking the button as Step is.

// STATE
const [tokenMint, setTokenMint] = useState('');
const [virtualQuoteReserves, setVirtualQuoteReserves] = useState('');
const [fetchBeforeUse, setFetchBeforeUse] = useState(true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After a successful create, tokenMint and virtualQuoteReserves are cleared, but fetchBeforeUse keeps its last value. If the user turned it off once, the next scenario silently gets false even though the default is true. Reset it with the other fields; the Phoenix dialog has the same issue.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What the PR does

Play becomes a menu with two choices. Play with paused clock keeps #31's flow: pause, then advance one slot per column. Play with running clock only registers each column and lets the surfnet produce the next slot. The PR also adds:

  • a shared setSurfnetClockPaused helper, which replaces four hand-written copies;
  • a warning line for scenarios that use a template tagged clock-sensitive;
  • a Fetch before use switch in the PumpSwap and Phoenix presets.

Assessment

The change is clean and well scoped. Stop and Complete now share resumeClock, and dropping the unread ignoreSlotEvents is a good cleanup. The tests cover the new branches.

Concerns:

  1. Leftover column after a failed paused Play. When the pause call or the first time travel fails, column 1 stays registered on the surfnet (see inline comments).
  2. No wait for the previous column with the running clock. Step registers column N+1 as soon as column N's request returns. Nothing checks that a slot was produced in between. If surfnet_registerScenario with the same scenarioId replaces what was registered before, a quick double Step can drop a column. One fix is to wait for the next slot event before allowing Step. Another is to state in the UI that a Step should not come faster than one slot.
  3. Minor: handleStop can run while a Step is in flight. Both the Stop and Step buttons stay enabled during a step. In paused mode, the step's advanceOneSlot can then time travel after Stop has resumed the clock, and the column it registered stays on the surfnet. This existed before the PR, but it matters more now that Stop resumes the clock.

if (await setSurfnetClockPaused(rpcUrl, true)) {
logger.log('🎬 Clock paused after scenario registration');
} else {
console.error('Error pausing clock');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If surfnet_pauseClock fails, Play still continues in 'paused' mode while the clock keeps running. Step then calls surfnet_timeTravel to processed + 1 on a running clock, which can race with the slot the surfnet produces on its own. Suggestion: abort here (and say why), or fall back to setPlayClock('running') and skip advanceOneSlot.

if (firstSlot && !(await advanceOneSlot())) {
return;
if (firstSlot && !(await advanceOneSlot())) {
await resumeClock();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When advanceOneSlot fails here, column 1 has already been registered by registerColumn and is never cleared. Resuming the clock makes the surfnet produce the next slot, so column 1 lands anyway while the UI goes back to read mode. The next Play then registers it again, so its overrides land twice, or once for a user who gives up. Consider clearing the registration first (if the surfnet has an unregister RPC), or at least telling the user that column 1 may still land.

}
registeredColumnRef.current = next;
if (!(await advanceOneSlot())) {
if (playClock === 'paused' && !(await advanceOneSlot())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the running clock, nothing checks that column N has landed before column N+1 is registered. steppingRef only blocks a second Step until the register RPC returns. That can take less time than one slot, so two quick Steps can replace column N before any slot was produced (if registering with the same scenarioId overwrites). Consider waiting for the next slot event before allowing Step in running mode.

</div>
</div>
</div>
{!!isClockSensitive && mode === 'read' && (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: isClockSensitive is already a boolean (it comes from .some(...)), so the !! isn't needed.

@92Infinitus92
92Infinitus92 changed the base branch from feat/studio/play-modes to feat/scenarios/override/scenario-playback-support November 2, 2026 08:30
@92Infinitus92
92Infinitus92 merged commit 642f4c4 into feat/scenarios/override/scenario-playback-support Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant