Fix timeline interaction bugs and add inline text editing.
THREE ISSUES:
CLIPS JUMP BACK THEN FORWARD: When moving clips on the timeline, they visually snap back to their original position for a moment before jumping to the new position. This happens both in the timeline UI and the video preview. The likely cause is a state update race: the library's onChange fires with the new position, but then the React Query refetch or the polling mechanism overwrites it with the old saved state before the save completes. The fix needs to ensure optimistic updates persist without being overwritten by stale server state.
TEXT CLIPS JUMP BACK AFTER MOVE: Same as above but worse for text clips - they consistently jump back to their original position. The text clip handling in the move/resize handlers may not be correctly updating the clip data.
INLINE TEXT EDITING: Currently text content is only editable in the ClipPanel sidebar. Users should be able to double-click a text clip on the preview canvas to edit it inline. Need: (a) double-click on a text clip overlay opens an inline text editor, (b) the editor is a contenteditable div or textarea positioned exactly over the text clip, (c) edits update the clip's text.content in real-time, (d) clicking away or pressing Escape closes the inline editor, (e) the ClipPanel text field stays in sync.
ROOT CAUSE ANALYSIS NEEDED:
Check how onChange in the timeline library interacts with React Query refetch
Check if the save debounce + refetch creates a write-then-read race
Check if the signature comparison in the polling is working correctly
Check if applyTimelineEdit and the React Query mutation are coordinated properly
The fix should ensure:
Optimistic updates are never overwritten by stale fetched data
The save mutation marks the query as stale only AFTER the save completes
The polling/refetch skips updates when there are pending local changes
The viewer app (viewer/) uses React Query with 1-second polling to sync timeline.json from disk. Local edits go through → → debounced save (500ms). A signature-based guard in a (line 279 of ) is supposed to prevent polled data from overwriting unsaved local changes, but two race conditions allow stale server data to clobber optimistic updates:
Assistant
User
Assistant
User
Assistant
applyTimelineEdit
commitData
useEffect
useTimelineData.ts
The commitData dependency problem:commitData depends on selectedClipId and selectedTrackId (line 232). When a clip is selected during a move (which is every move), commitData is recreated, causing the polling useEffect to re-fire. Combined with React Query's structural sharing and timing, this creates windows where stale data is applied.
No "pending edits" guard: The polling effect only checks signature !== lastSavedSignature. During the 500ms debounce window (and while the save is in-flight), there's no mechanism to suppress polling updates. If loadTimelineJson resolves the config with a slightly different registry than saveMutation.onSuccess uses, signatures can differ, triggering an overwrite.
Text clips: May have an additional issue in the move handler where buildRowTrackPatches or the materializeData round-trip doesn't preserve text clip hold metadata correctly.
The inline text editing feature adds a double-click → contenteditable overlay on OverlayEditor.tsx, wired to the same onOverlayChange that handles position/size changes.
Key files:
viewer/src/tools/video-editor/hooks/useTimelineData.ts — state management, polling, save
viewer/src/tools/video-editor/hooks/useTimelineEditing.ts — onChange, onOverlayChange, text clip creation
Also guard the asset registry effect (line 285-302) with the same hasPendingEdits.current check, since it can also overwrite local state.
Also clear hasPendingEdits in saveMutation.onError so the editor doesn't get permanently stuck ignoring polls.
Why this works: The ref is synchronously set before the save debounce starts and cleared only after the save succeeds and lastSavedSignature is updated. During the entire window (edit → debounce → save → success), polling cannot overwrite local state.
Step 2: Stabilize commitData to avoid unnecessary effect re-fires (useTimelineData.ts)
Scope: Small — defense-in-depth for issues 1 and 2
Move selectedClipId and selectedTrackId reads inside commitData to refs instead of closing over the state values. This prevents commitData from being recreated every time selection changes, which avoids re-triggering the polling and asset registry effects unnecessarily.
Then in commitData, replace selectedClipId and selectedTrackId with selectedClipIdRef.current and selectedTrackIdRef.current, and remove them from the dependency array.
Verify that commitData's dependency array becomes [scheduleSave] only, dramatically reducing how often the polling effect re-runs.
Step 3: Audit text clip round-trip in materializeData (timeline-data.ts)
Scope: Small — diagnose issue 2
Trace a text clip through the conversion cycle:rowsToConfig() (line ~191) → configToRows() (line ~142) in timeline-data.ts. Verify that hold, clipType: "text", and text properties survive the round-trip without mutation or loss.
Check buildRowTrackPatches — this function is called from onChange (line 196 in useTimelineEditing.ts). If it generates track patches for text clips that conflict with or overwrite the hold/text metadata, that would explain why text clips jump back more consistently.
Fix any round-trip issues found. The most likely problem is that rowsToConfig doesn't preserve hold duration when recalculating from action.start/action.end, causing text clips to get incorrect durations that then get re-normalized.
Step 4: Add inline text editing to OverlayEditor.tsx
Render inline editor when editingClipId matches the overlay. Inside the overlay div (after the label span, around line 362), conditionally render a <textarea> or contentEditable div:
Suppress drag initiation when editing: modify the overlay's onMouseDown (line 356) to check editingClipId !== overlay.actionId before initiating drag.
Wire onOverlayChange to accept text updates: The existing onOverlayChange in useTimelineEditing.ts (line 200-207) already calls applyTimelineEdit(current.rows, { [actionId]: patch }). Passing { text: { ...clipMeta.text, content: newText } } as the patch should work because applyTimelineEdit does a shallow merge of the patch into existing ClipMeta. Verify that nested text object is properly merged (it should be via { ...nextMeta[clipId], ...patch }), and fix if the text sub-object gets replaced instead of merged.
Expose editingClipId or an onTextEditStart callback to OverlayEditor's props so the component can accept the prop from the parent and coordinate with ClipPanel if needed. The simplest approach: OverlayEditor owns the editing state entirely; ClipPanel stays in sync because both read from the same data.meta[clipId].text.content source.
Step 5: Ensure ClipPanel stays in sync during inline editing (ClipPanel.tsx)
Scope: Small
ClipPanel already reads from selectedClip / data.meta, which is the same source onOverlayChange writes to. As long as the inline editor calls onOverlayChange on each keystroke (which triggers applyTimelineEdit → commitData → setData), the ClipPanel textarea will re-render with the updated content automatically.
Verify that editing text in ClipPanel while the inline editor is open doesn't cause conflicts. The simplest guard: when editingClipId is set, add readOnly to the ClipPanel textarea, or close the inline editor when ClipPanel receives focus.
Step 6: Validation
Scope: Small
Manual test — clip snap-back (issue 1):
Move a media clip on the timeline by dragging
Verify it stays at the new position without any visual snap-back
Move it again rapidly several times; confirm no flicker
Manual test — text clip snap-back (issue 2):
Move a text clip on the timeline
Move a text clip on the preview overlay (drag)
Resize a text clip
Verify all operations persist without snap-back
Manual test — inline text editing (issue 3):
Double-click a text clip on the preview → inline editor opens
Type new text → preview updates in real-time
Check ClipPanel sidebar → text field shows the same content
Press Escape → editor closes, text is saved
Click away → editor closes, text is saved
Edit in ClipPanel → preview updates (existing behavior still works)
Manual test — external edit detection still works:
Edit timeline.json in a text editor while the viewer is open
Verify the viewer picks up the external change within ~1 second
This confirms the hasPendingEdits guard doesn't permanently block polling
Run existing tests:
bash
cd viewer && npx vitest run
Execution Order
Steps 1 + 2 together (both in useTimelineData.ts) — these are the core fix for issues 1 and 2
Step 3 — audit text clip round-trip, fix if needed
Step 4 — inline text editing (independent feature, can be done after or in parallel with step 3)
Step 5 — sync verification (quick, after step 4)
Step 6 — validation (after all changes)
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-03-24T13:23:29Z",
"hash": "sha256:8238edd367045959a5640f8553897593b2b2c74bb5e2efbfc2788cccc6a96e1f",
"questions": [
"In Step 3, if the text clip round-trip audit reveals that hold clips lose their duration through rowsToConfig \u2192 configToRows, should the fix normalize inside rowsToConfig (preserve hold as-is) or inside configToRows (recompute hold from action bounds)? This affects whether text clip duration is driven by the timeline action or by the meta.",
"For the inline text editor (Step 4): should it support multi-line text (textarea) or single-line (input)? Text clips currently use white-space: pre-wrap in the Remotion composition, suggesting multi-line is expected, but the current ClipPanel uses a textarea too. Confirming multi-line is correct.",
"Should the inline editor font size be scaled to match the preview zoom level (composition space \u2192 screen space via projection.scaleX), or should it just use the raw fontSize? Scaling gives WYSIWYG accuracy but may produce very small text at low zoom."
],
"success_criteria": [
"Moving any clip (media or text) on the timeline never visually snaps back to the old position \u2014 the optimistic update persists smoothly until saved",
"Text clips moved on the timeline or dragged on the preview overlay stay at their new position without jumping back",
"Double-clicking a text clip on the preview canvas opens an inline editor positioned and styled to match the text clip",
"Typing in the inline editor updates the preview and ClipPanel text field in real-time",
"Pressing Escape or clicking away closes the inline editor and persists the edited text",
"External edits to timeline.json (outside the viewer) are still detected and applied within ~2 seconds when no local edits are pending",
"Existing vitest suite passes without regressions"
],
"assumptions": [
"The @xzdarcy/react-timeline-editor library's onChange fires synchronously with correct row data \u2014 the snap-back is caused by our state management, not the library reverting its own internal state",
"React Query's structural sharing means timelineQuery.data reference only changes when the fetched data actually differs \u2014 so the polling effect only fires on real data changes (plus when commitData ref changes due to selection state)",
"The hasPendingEdits ref approach is preferred over disabling refetchInterval dynamically, because it's simpler and doesn't risk missing external changes that arrive right after a save",
"Multi-line textarea is the correct choice for inline text editing (matching the existing ClipPanel textarea and pre-wrap rendering)",
"The inline editor should scale font size to match screen projection for WYSIWYG accuracy, falling back to a minimum readable size",
"The text sub-object in ClipMeta is shallow-merged correctly by the existing applyTimelineEdit spread \u2014 if not, we'll fix the merge to be one level deeper for text"
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"out-of-order-save-clears-pending-too-early","concern":"Step 1's single hasPendingEdits ref is not sufficient for this repository's save flow. scheduleSave can queue a second save while the first request is still in flight, but saveMutation.onSuccess currently has no version/request check. An older save completing late would clear the guard and advance lastSavedSignature even if newer local edits still exist, reopening the exact stale-poll overwrite window the plan is trying to close.","category":"correctness","severity_hint":"likely-significant","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/hooks/useTimelineData.ts:142-153 handles every save success as current, and :188-197 can issue later saves without tracking which response is newest."},{"id":"clear-pending-on-save-error-loses-unsaved-edits","concern":"Step 1.6 is unsafe. If a save fails, clearing the pending-edits guard would let the polling effect immediately re-apply disk state over the user's unsaved optimistic edit, which directly violates the stated requirement that optimistic updates must not be overwritten by stale fetched data.","category":"correctness","severity_hint":"likely-significant","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/hooks/useTimelineData.ts:154-156 currently only marks the error; the poller at :279-282 would become free to overwrite local state again if the plan clears the guard here."},{"id":"inline-editor-blocked-by-overlay-hit-testing","concern":"Step 4 does not address a blocker in the existing preview overlay: when no clip is selected, the overlay container disables pointer events entirely. That means a user cannot double-click an unselected text clip to start inline editing, so the proposed feature will not actually open from the normal idle state.","category":"correctness","severity_hint":"likely-significant","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/components/PreviewPanel/OverlayEditor.tsx:317-331 sets pointerEvents to none unless selectedClipId is truthy. The click handlers the plan relies on are on the overlay nodes at :352-360."},{"id":"missing-automated-coverage-for-race-and-inline-editing","concern":"The validation section is too weak for the changes proposed. In this repo, the relevant tests are only export smoke tests, so 'run existing vitest suite' will not verify the polling race, out-of-order save handling, or inline text editing behavior. The plan needs targeted tests for useTimelineData and OverlayEditor rather than only manual checks.","category":"completeness","severity_hint":"likely-significant","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/hooks/useTimelineData.test.ts:1-23 and /Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/components/PreviewPanel/OverlayEditor.test.ts:1-8 currently do not exercise any of the behavior this plan changes."},{"id":"scope-creep-clip-panel-lockout","concern":"Scope creep: Step 5 proposes making the ClipPanel text field read-only or otherwise coordinating focus between the sidebar and the inline editor. The original request only requires the two editors to stay in sync; it does not call for disabling sidebar editing or adding cross-surface focus rules, so this introduces an extra UX change that is not justified by the repository code shown.","category":"other","severity_hint":"likely-minor","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/components/PropertiesPanel/ClipPanel.tsx:296-327 already edits text directly from shared clip state. The plan adds a new locking behavior beyond the requested feature set."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
Fix timeline interaction bugs and add inline text editing.
THREE ISSUES:
CLIPS JUMP BACK THEN FORWARD: When moving clips on the timeline, they visually snap back to their original position for a moment before jumping to the new position. This happens both in the timeline UI and the video preview. The likely cause is a state update race: the library's onChange fires with the new position, but then the React Query refetch or the polling mechanism overwrites it with the old saved state before the save completes. The fix needs to ensure optimistic updates persist without being overwritten by stale server state.
TEXT CLIPS JUMP BACK AFTER MOVE: Same as above but worse for text clips - they consistently jump back to their original position. The text clip handling in the move/resize handlers may not be correctly updating the clip data.
INLINE TEXT EDITING: Currently text content is only editable in the ClipPanel sidebar. Users should be able to double-click a text clip on the preview canvas to edit it inline. Need: (a) double-click on a text clip overlay opens an inline text editor, (b) the editor is a contenteditable div or textarea positioned exactly over the text clip, (c) edits update the clip's text.content in real-time, (d) clicking away or pressing Escape closes the inline editor, (e) the ClipPanel text field stays in sync.
ROOT CAUSE ANALYSIS NEEDED:
Check how onChange in the timeline library interacts with React Query refetch
Check if the save debounce + refetch creates a write-then-read race
Check if the signature comparison in the polling is working correctly
Check if applyTimelineEdit and the React Query mutation are coordinated properly
The fix should ensure:
Optimistic updates are never overwritten by stale fetched data
The save mutation marks the query as stale only AFTER the save completes
The polling/refetch skips updates when there are pending local changes
The viewer app (viewer/) uses React Query with 1-second polling to sync timeline.json from disk. Local edits go through applyTimelineEdit → commitData → debounced save (500ms). A signature-based guard in a useEffect (useTimelineData.ts:279) is supposed to prevent polled data from overwriting unsaved local changes, but race conditions allow stale server data to clobber optimistic updates.
Root causes identified:
No pending-edits guard on polling. The polling effect at :279 only checks signature !== lastSavedSignature. During the debounce window and while saves are in-flight, there is nothing suppressing poll-driven overwrites. Meanwhile, commitData depends on selectedClipId/selectedTrackId (:232), causing the polling effect to re-fire on every selection change.
Text clips likely suffer the same polling race but more visibly due to the hold-based duration model. The round-trip through rowsToConfig → configToRows needs verification.
Inline text editing requires a double-click handler on OverlayEditor.tsx overlays, but the overlay container currently sets pointerEvents: "none" when no clip is selected (:331), blocking click-through to child overlay divs entirely.
Key files:
viewer/src/tools/video-editor/hooks/useTimelineData.ts — state management, polling, save
viewer/src/tools/video-editor/lib/timeline-data.ts — data conversion (rows↔config)
Step 1: Replace hasPendingEdits boolean with a monotonic edit counter (useTimelineData.ts)
Scope: Small — core fix for issues 1 and 2
The save flow allows overlapping requests: scheduleSave can queue a second save while a first is in-flight (:188-197). A single boolean would be cleared by whichever onSuccess fires first, even if newer edits exist. A monotonic counter solves this.
Add counter refs near line 111:
typescript
const editSeqRef = useRef(0); // incremented on every local edit
const savedSeqRef = useRef(0); // the editSeq that was last sent to save
Increment editSeqRef in commitData when save is true (the default), at line ~229:
typescript
if (options?.save ?? true) {
editSeqRef.current += 1;
scheduleSave(nextData);
}
Capture the seq when the save fires — modify scheduleSave (:188-198) to snapshot the current editSeqRef into the data passed to saveTimeline:
In saveMutation.onError (:154-156), do NOT clear any guard — just mark status. The edit counter stays ahead of the saved counter, so the polling guard remains active. Schedule a retry:
Why this works:editSeqRef advances on every local edit. savedSeqRef advances only when a save fires. onSuccess compares them — it only declares "saved" when the counters match. Polling is blocked whenever the counters diverge. An out-of-order or failed save cannot prematurely unblock polling because the counter comparison is always checked fresh from the refs.
Step 2: Stabilize commitData to avoid unnecessary effect re-fires (useTimelineData.ts)
Scope: Small — defense-in-depth for issues 1 and 2
Move selectedClipId and selectedTrackId reads inside commitData to refs instead of closing over the state values. At line ~128:
In commitData, replace selectedClipId with selectedClipIdRef.current and selectedTrackId with selectedTrackIdRef.current. Remove both from the dependency array so it becomes [scheduleSave] only.
This prevents commitData from being recreated on every selection change, which avoids re-triggering the polling and asset registry effects.
Step 3: Audit text clip round-trip in materializeData (timeline-data.ts)
Scope: Small — diagnose and fix issue 2
Trace a text clip through rowsToConfig() (:191) → configToRows() (:142). Verify that hold, clipType: "text", and text properties survive without mutation or loss.
Check buildRowTrackPatches — called from onChange (:196 in useTimelineEditing.ts). If it generates track patches that overwrite hold/text metadata for text clips, that would explain why text clips jump back more consistently.
Fix any round-trip issues found. The most likely problem is rowsToConfig recalculating duration from action.end - action.start without preserving the hold field, causing text clips to get incorrect durations.
Step 4: Add inline text editing to OverlayEditor.tsx
Scope: Medium — new feature (issue 3)
Fix pointer-events on individual overlay divs (:354). The container at :331 sets pointerEvents: "none" when no clip is selected, which blocks all child events. Change the container to always use pointerEvents: "none" and set pointerEvents: "auto" on each individual overlay div explicitly:
Render inline editor when editingClipId matches. Inside the overlay div (after the label span), conditionally render a <textarea>:
tsx
Step 5: Add targeted tests for the edit-counter guard (useTimelineData.test.ts)
Scope: Small
Extract the guard logic into a testable pure function or test the hook with a lightweight harness. The core invariant to test:
When editSeq > savedSeq, polling data is ignored regardless of signature mismatch
When editSeq === savedSeq and signatures differ, polling data is applied
When a save completes for an older seq (edit happened during save), editSeq > savedSeq still holds, so polling stays blocked
On save error, guard remains active and retry is scheduled
Test file:viewer/src/tools/video-editor/hooks/useTimelineData.test.ts — extend the existing smoke test file with tests for the counter logic. If the guard logic is extracted to a helper, tests can be pure unit tests without needing React rendering.
Step 6: Validation
Scope: Small
Manual test — clip snap-back (issue 1):
Move a media clip on the timeline by dragging; verify no visual snap-back
Move rapidly several times; confirm no flicker
Manual test — text clip snap-back (issue 2):
Move a text clip on the timeline and on the preview overlay
Resize a text clip; verify all persist without snap-back
Manual test — inline text editing (issue 3):
With NO clip selected, double-click a text clip on the preview → clip selects and inline editor opens
With a clip already selected, double-click a text clip → inline editor opens
Type new text → preview and ClipPanel sidebar update in real-time
Press Escape → editor closes, text persisted
Click away → editor closes, text persisted
Manual test — external edit detection:
Edit timeline.json externally while the viewer is open
Verify the viewer picks up the change within ~2 seconds (confirms the guard doesn't permanently block)
Run tests:
bash
cd viewer && npx vitest run
Execution Order
Steps 1 + 2 (both in useTimelineData.ts) — core fix for the polling race
Step 5 — add tests for the guard logic while it's fresh
Step 3 — audit text clip round-trip, fix if needed
Step 4 — inline text editing feature
Step 6 — full validation pass
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-03-24T13:29:26Z",
"hash": "sha256:697e06e444e3af8f10b4e7893761c9bd5aa4bbfc237dd07f39b3f738cc33aa03",
"changes_summary": "Changes from v1:\n\n1. Replaced boolean hasPendingEdits with monotonic edit counter (addresses out-of-order-save-clears-pending-too-early). editSeqRef increments on every local edit; savedSeqRef captures the seq when a save fires. onSuccess compares them \u2014 it only declares "saved" when counters match. Polling is blocked whenever they diverge, so an out-of-order save completion cannot prematurely unblock polling.\n\n2. Removed "clear guard on save error" (addresses clear-pending-on-save-error-loses-unsaved-edits). On error, the counter gap persists so polling stays blocked. Added a retry via scheduleSave(current) to recover gracefully.\n\n3. Fixed overlay pointer-events for inline editing (addresses inline-editor-blocked-by-overlay-hit-testing). Container always uses pointer-events: none; individual overlay divs use pointer-events: auto. This allows double-clicking unselected text clips.\n\n4. Added Step 5 with targeted tests for the edit-counter guard (addresses missing-automated-coverage-for-race-and-inline-editing). Tests cover the core invariants: pending edits block polling, completed saves unblock only when counters match, errors keep guard active.\n\n5. Removed scope creep \u2014 dropped the ClipPanel readOnly lockout from old Step 5; both the inline editor and ClipPanel naturally stay in sync through the shared data.meta state.",
"flags_addressed": [
"out-of-order-save-clears-pending-too-early",
"clear-pending-on-save-error-loses-unsaved-edits",
"inline-editor-blocked-by-overlay-hit-testing",
"missing-automated-coverage-for-race-and-inline-editing"
],
"questions": [
"In Step 3, if the text clip round-trip audit reveals that hold clips lose their duration through rowsToConfig \u2192 configToRows, should the fix normalize inside rowsToConfig (preserve hold as-is) or inside configToRows (recompute hold from action bounds)?",
"For the inline text editor font sizing: should we use projection.scaleX with a 12px floor, or is there a preferred minimum size?"
],
"success_criteria": [
"Moving any clip (media or text) on the timeline never visually snaps back to the old position \u2014 the optimistic update persists smoothly until saved",
"Text clips moved on the timeline or dragged on the preview overlay stay at their new position without jumping back",
"When a save is in-flight and the user makes another edit, the second edit is not lost when the first save completes",
"On save error, the user's local edits are preserved (not overwritten by polling) and a retry is scheduled",
"Double-clicking a text clip on the preview canvas \u2014 even when no clip is currently selected \u2014 opens an inline editor positioned and styled to match the text clip",
"Typing in the inline editor updates the preview and ClipPanel text field in real-time",
"Pressing Escape or clicking away closes the inline editor and persists the edited text",
"External edits to timeline.json (outside the viewer) are still detected and applied within ~2 seconds when no local edits are pending",
"New unit tests for the edit-counter guard pass and cover: pending blocks polling, completed save unblocks, out-of-order save keeps guard, error keeps guard",
"Existing vitest suite passes without regressions"
],
"assumptions": [
"The library's onChange fires synchronously with correct row data \u2014 the snap-back is caused by our state management, not the library reverting its own internal state",
"React Query's structural sharing means timelineQuery.data reference only changes when the fetched data actually differs \u2014 so the polling effect only fires on real data changes plus when commitData ref changes",
"Multi-line textarea is the correct choice for inline text editing (matching the existing ClipPanel textarea and pre-wrap rendering)",
"The inline editor font size should be scaled via projection.scaleX with a minimum of 12px for readability",
"The text sub-object in ClipMeta is replaced (not deep-merged) by the applyTimelineEdit spread, so callers must pass the full text object with changes applied \u2014 verified this is correct for the inline editor's onChange handler",
"Setting pointer-events: auto on individual overlay divs while the container stays pointer-events: none is the correct CSS approach \u2014 clicks on empty space will pass through to the video player beneath"
],
"structure_warnings": [],
"delta_from_previous_percent": 55.1
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "out-of-order-save-clears-pending-too-early",
"concern": "Step 1's single hasPendingEdits ref is not sufficient for this repository's save flow. scheduleSave can queue a second save while the first request is still in flight, but saveMutation.onSuccess currently has no version/request check. An older save completing late would clear the guard and advance lastSavedSignature even if newer local edits still exist, reopening the exact stale-poll overwrite window the plan is trying to close.",
"status": "addressed",
"severity": "significant"
},
{
"id": "clear-pending-on-save-error-loses-unsaved-edits",
"concern": "Step 1.6 is unsafe. If a save fails, clearing the pending-edits guard would let the polling effect immediately re-apply disk state over the user's unsaved optimistic edit, which directly violates the stated requirement that optimistic updates must not be overwritten by stale fetched data.",
"status": "addressed",
"severity": "significant"
},
{
"id": "inline-editor-blocked-by-overlay-hit-testing",
"concern": "Step 4 does not address a blocker in the existing preview overlay: when no clip is selected, the overlay container disables pointer events entirely. That means a user cannot double-click an unselected text clip to start inline editing, so the proposed feature will not actually open from the normal idle state.",
"status": "addressed",
"severity": "significant"
},
{
"id": "missing-automated-coverage-for-race-and-inline-editing",
"concern": "The validation section is too weak for the changes proposed. In this repo, the relevant tests are only export smoke tests, so 'run existing vitest suite' will not verify the polling race, out-of-order save handling, or inline text editing behavior. The plan needs targeted tests for useTimelineData and OverlayEditor rather than only manual checks.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-creep-clip-panel-lockout",
"concern": "Scope creep: Step 5 proposes making the ClipPanel text field read-only or otherwise coordinating focus between the sidebar and the inline editor. The original request only requires the two editors to stay in sync; it does not call for disabling sidebar editing or adding cross-surface focus rules, so this introduces an extra UX change that is not justified by the repository code shown.",
"status": "open",
"severity": "minor"
}
]
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"in-flight-save-window-still-allows-stale-polls","concern":"Step 1 still reopens the stale-read race during the in-flight save window. The plan sets savedSeqRef.current = seq when the debounce fires, but the polling guard treats editSeqRef.current === savedSeqRef.current as 'no pending local changes'. For the latest edit, that equality becomes true before the POST succeeds, so a 1s poll can still apply old disk state while the save is in flight.","category":"correctness","severity_hint":"likely-significant","evidence":"The current repo's vulnerable window is the period between scheduleSave dispatch and saveMutation.onSuccess in /Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/hooks/useTimelineData.ts:188-197 and :142-153. The new plan's Step 1.3 moves savedSeqRef forward at dispatch time, while Step 1.6 uses that ref to unblock polling, which recreates the same window."},{"id":"missing-automated-coverage-for-race-and-inline-editing","concern":"This is only partially addressed. Step 5 adds tests for the counter guard, but the plan still does not add any automated coverage for the new inline-editing behavior in OverlayEditor even though the existing OverlayEditor.test.ts is just a smoke test. The original concern covered both the race fix and inline editing.","category":"completeness","severity_hint":"likely-significant","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/components/PreviewPanel/OverlayEditor.test.ts:1-8 currently only checks that the component exports. The revised plan's Step 5 mentions only useTimelineData.test.ts, not tests for double-click, typing sync, Escape, or blur behavior in OverlayEditor."},{"id":"text-roundtrip-root-cause-still-unsupported","concern":"Step 3 still treats rowsToConfig losing hold as the most likely text-clip-specific cause, but that does not match the repository. In the current code, rowsToConfig explicitly preserves hold clips by writing nextClip.hold = action.end - action.start, and buildRowTrackPatches only writes track. This looks more like a speculative side quest than an evidence-backed root cause.","category":"correctness","severity_hint":"likely-minor","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/lib/timeline-data.ts:250-255 preserves hold, and /Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/lib/coordinate-utils.ts:96-106 only returns { track: row.id } patches. The plan should demote this from 'most likely problem' unless new evidence appears."}],"verified_flag_ids":["out-of-order-save-clears-pending-too-early","clear-pending-on-save-error-loses-unsaved-edits","inline-editor-blocked-by-overlay-hit-testing","scope-creep-clip-panel-lockout"],"disputed_flag_ids":[]}
You are an independent reviewer. Critique the plan against the actual repository.
Fix timeline interaction bugs and add inline text editing.
THREE ISSUES:
CLIPS JUMP BACK THEN FORWARD: When moving clips on the timeline, they visually snap back to their original position for a moment before jumping to the new position. This happens both in the timeline UI and the video preview. The likely cause is a state update race: the library's onChange fires with the new position, but then the React Query refetch or the polling mechanism overwrites it with the old saved state before the save completes. The fix needs to ensure optimistic updates persist without being overwritten by stale server state.
TEXT CLIPS JUMP BACK AFTER MOVE: Same as above but worse for text clips - they consistently jump back to their original position. The text clip handling in the move/resize handlers may not be correctly updating the clip data.
INLINE TEXT EDITING: Currently text content is only editable in the ClipPanel sidebar. Users should be able to double-click a text clip on the preview canvas to edit it inline. Need: (a) double-click on a text clip overlay opens an inline text editor, (b) the editor is a contenteditable div or textarea positioned exactly over the text clip, (c) edits update the clip's text.content in real-time, (d) clicking away or pressing Escape closes the inline editor, (e) the ClipPanel text field stays in sync.
ROOT CAUSE ANALYSIS NEEDED:
Check how onChange in the timeline library interacts with React Query refetch
Check if the save debounce + refetch creates a write-then-read race
Check if the signature comparison in the polling is working correctly
Check if applyTimelineEdit and the React Query mutation are coordinated properly
The fix should ensure:
Optimistic updates are never overwritten by stale fetched data
The save mutation marks the query as stale only AFTER the save completes
The polling/refetch skips updates when there are pending local changes
The viewer app (viewer/) uses React Query with 1-second polling to sync timeline.json from disk. Local edits go through applyTimelineEdit → commitData → debounced save (500ms). A signature-based guard in a useEffect (useTimelineData.ts:279) is supposed to prevent polled data from overwriting unsaved local changes, but race conditions allow stale server data to clobber optimistic updates.
Root causes identified:
No pending-edits guard on polling. The polling effect at :279 only checks signature !== lastSavedSignature. During the debounce window and while saves are in-flight, there is nothing suppressing poll-driven overwrites. Meanwhile, commitData depends on selectedClipId/selectedTrackId (:232), causing the polling effect to re-fire on every selection change.
Text clips likely suffer the same polling race but more visibly due to the hold-based duration model. The round-trip through rowsToConfig → configToRows needs verification.
Inline text editing requires a double-click handler on OverlayEditor.tsx overlays, but the overlay container currently sets pointerEvents: "none" when no clip is selected (:331), blocking click-through to child overlay divs entirely.
Key files:
viewer/src/tools/video-editor/hooks/useTimelineData.ts — state management, polling, save
viewer/src/tools/video-editor/lib/timeline-data.ts — data conversion (rows↔config)
Step 1: Add monotonic edit counter to suppress stale polling (useTimelineData.ts)
Scope: Small — core fix for issues 1 and 2
The save flow allows overlapping requests: scheduleSave can queue a second save while a first is in-flight (:188-197). A monotonic counter tracks whether the latest save has completed for the latest edit.
Add counter refs near line 111:
typescript
const editSeqRef = useRef(0); // incremented on every local edit
const savedSeqRef = useRef(0); // advanced ONLY in onSuccess to the seq that was saved
Increment editSeqRef in commitData when save is true (the default), at line ~229:
typescript
if (options?.save ?? true) {
editSeqRef.current += 1;
scheduleSave(nextData);
}
Capture the seq into the save closure, but do NOT advance savedSeqRef yet — modify scheduleSave (:188-198) to capture the current edit seq and pass it through:
Modify saveTimeline to forward the seq to the mutation context so onSuccess can read it:
typescript
const saveTimeline = useCallback(async (nextData: TimelineData, seq: number) => {
setSaveStatus("saving");
await saveMutation.mutateAsync(nextData.config, {
onSuccess: (_value, savedConfig) => {
const current = dataRef.current;
if (!current) return;
// Advance savedSeqRef ONLY here, after the POST succeeds
savedSeqRef.current = seq;
setSaveStatus(seq >= editSeqRef.current ? "saved" : "dirty");
setRenderDirty(true);
lastSavedSignature.current = getConfigSignature(
resolveTimelineConfig(savedConfig, current.registry)
);
},
});
}, [saveMutation]);
Why this works:editSeqRef advances on every local edit. savedSeqRef advances ONLY in onSuccess — never at dispatch time. During the entire window from edit → debounce → HTTP POST → success, editSeqRef > savedSeqRef, so any poll landing during that window is blocked. An out-of-order completion for an older seq advances savedSeqRef but it's still < editSeqRef, so polling stays blocked. Only when the save for the latest edit succeeds does savedSeqRef >= editSeqRef become true.
Step 2: Stabilize commitData to avoid unnecessary effect re-fires (useTimelineData.ts)
Scope: Small — defense-in-depth for issues 1 and 2
Move selectedClipId and selectedTrackId reads inside commitData to refs instead of closing over the state values. At line ~128:
In commitData, replace selectedClipId with selectedClipIdRef.current and selectedTrackId with selectedTrackIdRef.current. Remove both from the dependency array so it becomes [scheduleSave] only.
This prevents commitData from being recreated on every selection change, which avoids re-triggering the polling and asset registry effects.
Step 3: Audit text clip round-trip in materializeData (timeline-data.ts)
Scope: Small — diagnose and fix issue 2
Trace a text clip through rowsToConfig() (:191) → configToRows() (:142). Verify that hold, clipType: "text", and text properties survive without mutation or loss.
Check buildRowTrackPatches — called from onChange (:196 in useTimelineEditing.ts). If it generates track patches that overwrite hold/text metadata for text clips, that would explain why text clips jump back more consistently.
Fix any round-trip issues found. The most likely problem is rowsToConfig recalculating duration from action.end - action.start without preserving the hold field, causing text clips to get incorrect durations.
Step 4: Add inline text editing to OverlayEditor.tsx
Scope: Medium — new feature (issue 3)
Fix pointer-events on individual overlay divs (:354). The container at :331 sets pointerEvents: "none" when no clip is selected, which blocks all child events. Change the container to always use pointerEvents: "none" and set pointerEvents: "auto" on each individual overlay div explicitly:
Extract the guard predicate into a named pure function (e.g. shouldAcceptPolledData(editSeq, savedSeq, polledSig, lastSavedSig): boolean) so it can be unit-tested without rendering the hook. Place it as an exported helper in useTimelineData.ts or in timeline-data.ts.
Test cases using vitest + @testing-library/react (already a project dependency):
Double-click opens editor: Render OverlayEditor with a text clip overlay visible, simulate dblclick on it, assert a <textarea> appears.
Typing calls onOverlayChange: With the textarea open, fire a change event, assert onOverlayChange was called with the updated text content.
Escape closes editor: With the textarea open, fire keyDown with Escape, assert the textarea is removed.
Blur closes editor: With the textarea open, fire blur, assert the textarea is removed.
Test setup: Mock the props that OverlayEditor needs (meta, selectedClipId, trackScaleMap, onOverlayChange, onSelectClip, playerContainerRef). Provide a minimal text clip overlay in meta with clipType: "text" and text.content. Mock playerContainerRef to return a fixed-size element so layout computes.
Step 6: Validation
Scope: Small
Manual test — clip snap-back (issue 1):
Move a media clip on the timeline by dragging; verify no visual snap-back
Move rapidly several times; confirm no flicker
Manual test — text clip snap-back (issue 2):
Move a text clip on the timeline and on the preview overlay
Resize a text clip; verify all persist without snap-back
Manual test — inline text editing (issue 3):
With NO clip selected, double-click a text clip on the preview → clip selects and inline editor opens
With a clip already selected, double-click a text clip → inline editor opens
Type new text → preview and ClipPanel sidebar update in real-time
Press Escape → editor closes, text persisted
Click away → editor closes, text persisted
Manual test — external edit detection:
Edit timeline.json externally while the viewer is open
Verify the viewer picks up the change within ~2 seconds (confirms the guard doesn't permanently block)
Run tests:
bash
cd viewer && npx vitest run
Execution Order
Steps 1 + 2 (both in useTimelineData.ts) — core fix for the polling race
Step 5a — add guard predicate tests while the logic is fresh
Step 3 — audit text clip round-trip, fix if needed
Step 4 — inline text editing feature
Step 5b — add OverlayEditor interaction tests
Step 6 — full validation pass
code
Plan metadata:
{
"version": 3,
"timestamp": "2026-03-24T13:33:48Z",
"hash": "sha256:91817231fa4a2329a2b06749bdc69487bd39cbce7a5da2eed92568db103bd75a",
"changes_summary": "Changes from v2:\n\n1. Fixed in-flight save window race (addresses in-flight-save-window-still-allows-stale-polls). savedSeqRef is now advanced ONLY in onSuccess, never at dispatch time. The scheduleSave closure captures the edit seq and passes it through saveTimeline into the per-call onSuccess handler. During the entire window from edit \u2192 debounce \u2192 POST \u2192 success, editSeqRef > savedSeqRef holds true, so polling is blocked. The guard condition is savedSeqRef.current >= editSeqRef.current (not ===), which correctly blocks during in-flight saves.\n\n2. Added OverlayEditor interaction tests (addresses missing-automated-coverage-for-race-and-inline-editing). Step 5 now has two sub-sections: 5a for the guard predicate unit tests, and 5b for OverlayEditor tests covering double-click opens editor, typing calls onOverlayChange, Escape closes, and blur closes. Tests use vitest + @testing-library/react with mocked props.",
"flags_addressed": [
"in-flight-save-window-still-allows-stale-polls",
"missing-automated-coverage-for-race-and-inline-editing"
],
"questions": [
"In Step 3, if the text clip round-trip audit reveals that hold clips lose their duration through rowsToConfig \u2192 configToRows, should the fix normalize inside rowsToConfig (preserve hold as-is) or inside configToRows (recompute hold from action bounds)?"
],
"success_criteria": [
"Moving any clip (media or text) on the timeline never visually snaps back to the old position \u2014 the optimistic update persists smoothly until saved",
"Text clips moved on the timeline or dragged on the preview overlay stay at their new position without jumping back",
"When a save is in-flight and the user makes another edit, the second edit is not lost when the first save completes",
"Polling is blocked during the entire in-flight save window (edit \u2192 debounce \u2192 POST \u2192 onSuccess), not just during the debounce",
"On save error, the user's local edits are preserved (not overwritten by polling) and a retry is scheduled",
"Double-clicking a text clip on the preview canvas \u2014 even when no clip is currently selected \u2014 opens an inline editor positioned and styled to match the text clip",
"Typing in the inline editor updates the preview and ClipPanel text field in real-time",
"Pressing Escape or clicking away closes the inline editor and persists the edited text",
"External edits to timeline.json (outside the viewer) are still detected and applied within ~2 seconds when no local edits are pending",
"New unit tests for the guard predicate pass and cover: pending blocks polling, completed save unblocks, in-flight save blocks, out-of-order save keeps guard, error keeps guard",
"New OverlayEditor tests pass and cover: double-click opens editor, typing calls onOverlayChange, Escape closes, blur closes",
"Existing vitest suite passes without regressions"
],
"assumptions": [
"The @xzdarcy/react-timeline-editor library's onChange fires synchronously with correct row data \u2014 the snap-back is caused by our state management, not the library reverting its own internal state",
"React Query's structural sharing means timelineQuery.data reference only changes when the fetched data actually differs \u2014 so the polling effect only fires on real data changes plus when commitData ref changes",
"Multi-line textarea is the correct choice for inline text editing (matching the existing ClipPanel textarea and pre-wrap rendering)",
"The inline editor font size should be scaled via projection.scaleX with a minimum of 12px for readability",
"The text sub-object in ClipMeta is replaced (not deep-merged) by the applyTimelineEdit spread, so callers must pass the full text object with changes applied",
"Setting pointer-events: auto on individual overlay divs while the container stays pointer-events: none is the correct CSS approach",
"useMutation's mutateAsync accepts per-call onSuccess overrides that replace the default onSuccess \u2014 this is standard React Query v5 behavior",
"@testing-library/react is available in the viewer project for component tests"
],
"structure_warnings": [],
"delta_from_previous_percent": 20.72
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "missing-automated-coverage-for-race-and-inline-editing",
"concern": "This is only partially addressed. Step 5 adds tests for the counter guard, but the plan still does not add any automated coverage for the new inline-editing behavior in OverlayEditor even though the existing OverlayEditor.test.ts is just a smoke test. The original concern covered both the race fix and inline editing.",
"status": "addressed",
"severity": "significant"
},
{
"id": "in-flight-save-window-still-allows-stale-polls",
"concern": "Step 1 still reopens the stale-read race during the in-flight save window. The plan sets savedSeqRef.current = seq when the debounce fires, but the polling guard treats editSeqRef.current === savedSeqRef.current as 'no pending local changes'. For the latest edit, that equality becomes true before the POST succeeds, so a 1s poll can still apply old disk state while the save is in flight.",
"status": "addressed",
"severity": "significant"
},
{
"id": "text-roundtrip-root-cause-still-unsupported",
"concern": "Step 3 still treats rowsToConfig losing hold as the most likely text-clip-specific cause, but that does not match the repository. In the current code, rowsToConfig explicitly preserves hold clips by writing nextClip.hold = action.end - action.start, and buildRowTrackPatches only writes track. This looks more like a speculative side quest than an evidence-backed root cause.",
"status": "open",
"severity": "minor"
}
]
code
Requirements:
- Consider whether the plan is at the right level of abstraction.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids` should list previously addressed flags that now appear resolved.
- Focus on concrete issues that would cause real problems.
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Verify that the plan remains aligned with the user's original intent.
- Verify that the plan follows the expected structure: one H1 title, `## Overview`, numbered `## Step N:` sections with file references and numbered substeps, plus `## Execution Order` or `## Validation Order`. Missing structure should be flagged as category `completeness` with severity_hint `likely-significant`.
- Flag scope creep explicitly when the plan grows beyond the original idea or recorded user notes. Use the phrase "Scope creep:" in the concern.
- Assign severity_hint carefully. Implementation details the executor will naturally resolve should usually be `likely-minor`.
{"flags":[{"id":"older-save-success-regresses-saved-seq","concern":"Step 1 still mishandles out-of-order save completions. savedSeqRef.current = seq is written unconditionally in every per-call onSuccess, so if save seq=2 succeeds first and save seq=1 finishes later, the older completion will move savedSeqRef backward and overwrite lastSavedSignature with stale data. That can leave the editor stuck in a false 'dirty/pending' state and keep polling blocked even though the newest save already completed.","category":"correctness","severity_hint":"likely-significant","evidence":"The repository already allows overlapping saves via /Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/hooks/useTimelineData.ts:188-197. The revised plan's Step 1.4 assigns savedSeqRef.current = seq and updates lastSavedSignature on every success, but it does not guard against an older request resolving after a newer one."},{"id":"text-roundtrip-root-cause-still-unsupported","concern":"Step 3 still treats rowsToConfig losing hold as the most likely text-clip-specific cause, but that does not match the repository. In the current code, rowsToConfig explicitly preserves hold clips by writing nextClip.hold = action.end - action.start, and buildRowTrackPatches only writes track. This still looks more like a speculative side quest than an evidence-backed root cause.","category":"correctness","severity_hint":"likely-minor","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/lib/timeline-data.ts:250-255 preserves hold, and /Users/user_c042661f/Documents/announcement-video/viewer/src/tools/video-editor/lib/coordinate-utils.ts:96-106 only returns { track: row.id } patches. The plan should demote this from 'most likely problem' unless new evidence appears."},{"id":"testing-library-react-not-available-in-viewer","concern":"Step 5b assumes @testing-library/react is already available in the viewer project, but that is not true in this repository. The package is not declared in viewer/package.json, there are no existing imports under viewer/src, and viewer/node_modules/@testing-library/react is absent. As written, the proposed OverlayEditor tests are not runnable without first adding the dependency.","category":"completeness","severity_hint":"likely-minor","evidence":"/Users/user_c042661f/Documents/announcement-video/viewer/package.json:22-37 does not list @testing-library/react; rg finds no current imports under viewer/src; and the local path viewer/node_modules/@testing-library/react does not exist in this workspace."}],"verified_flag_ids":["missing-automated-coverage-for-race-and-inline-editing","in-flight-save-window-still-allows-stale-polls"],"disputed_flag_ids":[]}
Not yet included in a published release.
typescript
onError: () => {
setSaveStatus("error");
// Re-schedule save for the current local state so edits aren't lost
const current = dataRef.current;
if (current) {
scheduleSave(current);
}
},
Guard the polling useEffect (:279-283) — skip when local edits are ahead of the last completed save:
Verify text sub-object merging.applyTimelineEdit does { ...nextMeta[clipId], ...patch } (:248). Since text is a nested object, the spread replaces it entirely — which is fine as long as the caller passes the full text object (as shown in step 4 above: { ...clipMeta?.text, content: e.target.value }). No code change needed; just verify.
@xzdarcy/react-timeline-editor
Remove the existing onSuccess from the useMutation options (:142-153) since it's now passed per-call.
In saveMutation.onError (:154-156), do NOT advance savedSeqRef. The counter gap persists so the polling guard stays active. Schedule a retry:
typescript
onError: () => {
setSaveStatus("error");
const current = dataRef.current;
if (current) {
scheduleSave(current);
}
},
Guard the polling useEffect (:279-283) — skip when local edits are ahead of the last completed save:
Verify text sub-object merging.applyTimelineEdit does { ...nextMeta[clipId], ...patch } (:248). Since text is a nested object, the spread replaces it entirely — which is fine as long as the caller passes the full text object (as shown in step 4 above: { ...clipMeta?.text, content: e.target.value }). No code change needed; just verify.