Search the codebase for where default presets for I2V (Image to Video) are defined. Look for things like preset arrays, default motion presets, I2V presets, or similar configurations. Check files related to motion presets, phase configs, or I2V settings. Search broadly - try terms like "preset", "i2v", "motion_preset", "defaultPreset", "presets", "PRESETS", "MotionPreset" in settings files and config files. Report back the file paths and the relevant code sections with line numbers.
Assistant
I'll search the codebase for default presets related to I2V (Image to Video). Let me start with broad searches for preset-related terms.
Assistant
Let me search more specifically for preset-related code, especially in settings and defaults files:
Assistant
Great! I found references to default presets. Let me read the key files that define them:
Assistant
Now let me check the phaseConfig type to understand the structure better:
Assistant
Perfect! Let me also check where DEFAULT_VACE_PHASE_CONFIG is defined in the shared types file (I saw it's in phaseConfig.ts, but there was also a vaceDefaults.ts file):
Assistant
Excellent! Now let me create a comprehensive report with all the findings. Let me get a final summary of the key files:
Assistant
Perfect! Now I have all the information needed. Let me compile the comprehensive report.
Summary: I2V (Image to Video) Default Presets
I've found where the default presets for I2V are defined. Here's the complete breakdown:
Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
Before providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
The user's explicit requests and intents
Your approach to addressing the user's requests
Key decisions, technical concepts and code patterns
Specific details like:
file names
full code snippets
function signatures
file edits
Errors that you ran into and how you fixed them
Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Double-check for technical accuracy and completeness, addressing each required element thoroughly.
Your summary should include the following sections:
Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
Assistant
Structure video hover frame label: User asked why the structure video strip shows the current frame of the "actual video" when hovering. After investigation, I found the hover tooltip shows currentTimelineFrame (output timeline frame) instead of the structure video's own frame. User clarified they meant the frame count label at the bottom, not the video content. After discussion, we agreed the structure video frame number is more useful since the timeline position is already shown by the strip's position and f{start}/f{end} labels.
Changes made to GuidanceVideoStrip.tsx: Renamed currentTimelineFrame → currentVideoFrame, removed timeline frame calculation in both handleMouseMove and handleStripTouchEnd, set videoFrame into state instead, updated tooltip display.
Featured I2V preset: User provided UUID e1aad8bf-add9-4d7b-883b-d67d424028c4 which I initially mistook for a screenshot path. User clarified it's a preset ID. Found FEATURED_PRESET_IDS in MotionControl.tsx:54 (empty array) and added the ID.
Git push: Both changes were reverted by linter/user, then re-applied and pushed as commit f24935bc.
SegmentSettingsForm preset issues: User reported presets don't show properly in SegmentSettingsForm and don't persist. I investigated extensively:
Found featuredPresetIds={[]} hardcoded in SegmentSettingsForm.tsx:552
Found persistence bug: buildMetadataUpdate in segmentSettingsUtils.ts cascade-deletes selectedPhasePresetId when phaseConfig is null, and savePairMetadata always passes phaseConfig: null when in basic mode
Found mismatched builtin preset IDs between segment form (__builtin_segment_i2v_default__) and batch view (__builtin_default_i2v__)
Fixes applied:
Removed cascade delete in buildMetadataUpdate
Added SEGMENT_I2V_FEATURED_PRESET_IDS and SEGMENT_VACE_FEATURED_PRESET_IDS to segmentSettingsUtils.ts
Updated SegmentSettingsForm.tsx to use correct featured preset IDs based on generation mode
Aligned builtin preset IDs to match the batch view's IDs
User
I'm investigating why changing the frame count for a trailing segment in SegmentSettingsForm doesn't update the timeline visually. I need to trace the full data flow.
Key things to find:
In src/tools/travel-between-images/components/ShotImagesEditor/hooks/useFrameCountUpdater.ts, find the trailing segment handling code - specifically what happens after it saves metadata.end_frame to the DB. Does it call loadPositions? What is loadPositions?
Search for trailingEndFrame across the codebase - where is it defined as state, how is it initialized/updated, and where is it used in the timeline?
Search for onTrailingEndFrameChange - where is this callback defined and how does it flow?
Check how loadPositions works - does it trigger a re-render that would update trailingEndFrame? Or is trailingEndFrame managed separately from the positions loaded by loadPositions?
Check useSegmentSlotMode.ts around lines 240-260 for how onFrameCountChange is wired for the trailing segment case.
Be very thorough - read the full content of key files rather than just searching for keywords. The goal is to understand why the timeline doesn't visually update when the trailing segment's frame count changes through the form.
Assistant
I'll trace this data flow thoroughly. Let me start by reading the key files in parallel.
Assistant
Good, I have the full picture of useFrameCountUpdater.ts. Now let me read the other key files in parallel.
Assistant
Now let me look at loadPositions to understand exactly what it does - specifically whether it refetches shotGenerations (which would update derivedEndFrame). Let me also check the useTimelineCore hook since that's where loadPositions maps to refetch.
Assistant
Now let me check useShotImages to understand what query key it uses and how loadPositions/refetch triggers data refresh. Also let me check the useSegmentSettingsForm to see how onFrameCountChange is excluded.
Assistant
Now let me check the query key and how useAllShotGenerations works, and also find where SegmentSettingsForm's onFrameCountChange is wired in the SegmentSlotFormView.
Assistant
Now let me check how loadPositions is mapped for the non-preloaded path. In useShotGenerationsData, when there are no preloaded images, loadPositions maps to coreHookData.refetch which is useTimelineCore.refetch(), which is () => refetch() from useShotImages. Let me also verify the query key used.
Assistant
Now I have the complete picture. Let me also check the SegmentRegenerateForm to see how it wires onFrameCountChange, since that's the other path the form appears in.
Assistant
Now I have all the pieces. Here is the complete analysis.
Full Data Flow Trace: Trailing Segment Frame Count Change
1. User changes frame count in SegmentSettingsForm
The slider/input in SegmentSettingsForm triggers handleFrameCountChange:
For the preloaded path, shotGenerations = preloadedImages (the prop), which won't change when loadPositions refetches. For the non-preloaded path, shotGenerations = hookData.shotGenerations = coreHookData.positionedItems, which WILL change on refetch.
But wait -- looking at line 93-94 of useShotGenerationsData:
ts
if (preloadedImages) {
return {
shotGenerations: utilsData.shotGenerations,
And utilsData.shotGenerations is the transformed version from useTimelinePositionUtils, which is derived from generations (the preloadedImages prop). So for the preloaded path, shotGenerations from hookData would actually be from the utilsData which comes from preloadedImages. But then at line 152, it's overridden to be preloadedImages directly.
This is a minor detail -- the key question is about the non-preloaded (normal) path. Let me now provide the complete analysis.
Complete Analysis: Why Trailing Segment Frame Count Change from Form Doesn't Update Timeline
The Data Flow (Non-Preloaded Path)
Here is the complete chain when a user changes the frame count for a trailing segment via SegmentSettingsForm:
Step 1 - User changes slider/input in SegmentSettingsForm
/Users/user_c042661f/Documents/reigh/src/shared/components/SegmentSettingsForm/SegmentSettingsForm.tsx line 239-243
Calls onFrameCountChange(quantizedValue) with a frame count (e.g., 49)
Step 2 - Propagated through parent form view
Either SegmentSlotFormView.tsx (line 136-140) or SegmentRegenerateForm.tsx (line 193-197)
Wraps the call as segmentSlotMode.onFrameCountChange(pairShotGenerationId, frameCount)
User
I need to understand how the timeline position management system works for segments. Explore these specific areas:
usePositionManagement - Find it (likely in src/tools/travel-between-images/components/Timeline/ or nearby). Read the full implementation. How does it manage framePositions, displayPositions, stablePositions? How does it sync from shotGenerations data? What triggers position updates?
How normal segment bars are rendered - In TimelineContainer.tsx, look at segmentEntries useMemo (around line 289-396). How are segment bars built from currentPositions? How does the trailing segment entry differ from normal entries?
How trailingEndFrame flows through rendering - Trace every usage of trailingEndFrame in TimelineContainer.tsx. How is the trailing bar rendered vs normal bars? What's in trailingSegmentMode prop? What renders the actual trailing bar visually?
The useTimelineOrchestrator trailing handling - How does the orchestrator handle trailing segment creation, drag, and persistence? Look at the trailingEffectiveEnd computation and the drag-to-persist flow for trailing segments.
Be thorough - read full implementations, not just signatures.
Assistant
I'll systematically explore each area you've asked about. Let me start by finding the relevant files.
User
I need to understand how single-image mode (1 image with no end image) works on the timeline, since it's conceptually similar to a trailing segment.
In usePairData.ts (src/tools/travel-between-images/components/ShotImagesEditor/hooks/usePairData.ts): How are trailing pairs (endImage: undefined) constructed? What about single-image scenarios (sortedImages.length === 1)?
In TimelineContainer.tsx: Search for images.length === 1 - how does single-image mode render? Does it use trailingEndFrame too? How is it different from the multi-image trailing case?
In useTimelineOrchestrator.ts: How does single-image mode handle the segment? Look for isMultiImage and isSingleImage usage.
In ShotImagesEditor.tsx: How is derivedEndFrame used for single-image vs multi-image trailing? Is trailingEndFrame always set for single-image mode?
Search for is_single_item or isSingleImage in the codebase to understand how single-image mode flows through the system.
The goal is to understand whether single-image and trailing segments share the same mechanism or are handled differently.
Assistant
I'll systematically investigate each of these questions. Let me start by reading the key files and searching for relevant patterns in parallel.
Assistant
Now let me read the remaining key files in parallel.
Assistant
Good, found all three files. Let me read them all in parallel.
Assistant
Now let me read more of the key files to complete the picture, including the rest of TimelineContainer for the rendering section and more of useTimelineOrchestrator.
Assistant
Now I need to read the useTimelinePositions hook that usePositionManagement delegates to, and also look at the SegmentOutputStrip to understand segment bar rendering. Let me also find the TrailingEndpoint component and getPairInfo utility.
Assistant
Now let me also look at how tasks are created for single-image mode to understand the is_single_item flow from the frontend side.
Assistant
Now let me read the getPairInfo and getTimelineDimensions functions from timeline-utils, and also find where trailingEndFrame originates (its derivation from the parent component).
Assistant
Let me also check the task creation side for trailing/single-image segments and the createSingleItemVariant function.
Assistant
Now let me check how is_single_item is set for the travel task specifically, since it comes through as is_first_segment && is_last_segment.
Assistant
Now let me read the derivedEndFrame computation from ShotImagesEditor.tsx.
Assistant
Let me check the trailing segment detection in buildIndividualTravelSegmentParams.
Assistant
Now let me also check how localEndFrame is defined and the onTrailingEndFrameChange handler.
Assistant
Now let me mark the tasks as complete and compile my comprehensive report.
Assistant
Now I have a thorough understanding of the entire flow. Here is the complete analysis.
Single-Image Mode vs. Trailing Segments: Complete Analysis
Answer: They share the same core mechanism -- both use trailingEndFrame and produce pairs with endImage: undefined. The differences are in gating logic (when to show/enable the trailing segment) and default sizes.
usePositionManagement is essentially a compatibility shim. The feature flag USE_NEW_POSITION_SYSTEM = true (hardcoded) means it delegates entirely to useTimelinePositions. The "legacy" code path below the if block is dead code (and actually broken -- it references wrappedSetFramePositions which is only defined inside the if block).
All three (framePositions, displayPositions, stablePositions) are the exact same Map from the new system. The old distinction between "frame," "display," and "stable" positions has been collapsed. There is a single source of truth.
Drag locking: When isDragInProgress changes, it calls lockPositions() / unlockPositions() on the new system to prevent database syncs from overwriting in-flight drag positions.
setFramePositions wrapper: Wraps the new system's updatePositions with setIsPersistingPositions state management (set to true before, cleared 100ms after).
TrailingEndpoint component renders the visual (different from PairRegion)
SegmentOutputStrip receives prop for video output positioning
Assistant
I'll start by thoroughly exploring the codebase to understand the current architecture before designing the plan.
Assistant
Now let me read the other critical files mentioned in the requirements.
Assistant
Now let me read the remaining key files: the TimelineContainer, TrailingEndpoint, SegmentOutputStrip, TimelineModeContent, and the useSegmentSlotMode hook.
Assistant
Now let me look at the Timeline.tsx component and the TimelineContainer to see how trailingEndFrame is used for rendering.
Assistant
The Timeline import must resolve to TimelineContainer. Let me read the TimelineContainer to see how trailingEndFrame is consumed.
Assistant
Now let me also check the usePairData hook and the useSegmentSlotMode to understand how end_frame is read from metadata.
Assistant
Now let me check how useTimelineDrag works to understand how the normal drag system works and whether the trailing endpoint could be integrated.
Assistant
Now I have a thorough understanding of the architecture. Let me look at one more thing -- how the TRAILING_ENDPOINT_ID constant is already defined in TrailingEndpoint.tsx, and check if there are any other consumers of the end_frame metadata field.
Assistant
Good. Let me also check how end_frame is read by the task creation / payload builder (the downstream consumers that must continue to work).
Assistant
These are structure video end_frame fields, not the trailing segment's end_frame metadata. Let me check how the trailing segment's end_frame is read in the task creation path specifically for segment generation.
Assistant
Good -- these are all structure video end_frame fields, unrelated to the trailing segment's metadata end_frame. Now I have a complete picture of the architecture. Let me compose the comprehensive plan.
Here is the detailed implementation plan.
Design: Trailing Segment as First-Class Position Entity
Problem Summary
The trailing endpoint is currently bolted onto the position system via a completely separate state management path:
Storage: metadata.end_frame on the last image's shot_generations row (not timeline_frame)
Read path: derivedEndFrame useMemo in ShotImagesEditor.tsx reads from shotGenerations metadata
Drag state: localEndFrame useState in ShotImagesEditor.tsx for responsive drag UI
Prop chain: trailingEndFrame passed through ShotImagesEditor -> TimelineModeContent -> Timeline (TimelineContainer) -> useTimelineOrchestrator (6+ component boundaries, all React.memo'd)
DB writes: Custom handler in useTimelineOrchestrator.handleEndpointMouseDown (lines 583-660) does direct Supabase writes to metadata.end_frame
Form changes: useFrameCountUpdater has a special isTrailingSegment branch that writes metadata.end_frame then calls loadPositions triggering a full refetch cascade
Normal segments use useTimelinePositions positions map with optimistic updates. The trailing endpoint bypasses all of this.
Design Decisions
Q1: Key for the trailing endpoint in the positions map?
Use the existing TRAILING_ENDPOINT_ID constant ('__trailing_endpoint') already defined in TrailingEndpoint.tsx. This is already a sentinel value used in the drag system (line 42 of TrailingEndpoint.tsx). Using it as the positions map key is natural and avoids any collision with real shot_generations.id UUIDs.
Q2: How does updatePositions handle the trailing key?
The updatePositions method in useTimelinePositions currently builds DB updates by looking up for each ID. The trailing endpoint won't have a matching . The solution: add a small special-case path in that detects and writes to on the last positioned image's row instead of writing . This keeps the routing logic contained in one place.
Here's an example of how your output should be structured:
Key Technical Concepts:
[Concept 1]
[Concept 2]
[...]
Files and Code Sections:
[File Name 1]
[Summary of why this file is important]
[Summary of the changes made to this file, if any]
[Important Code Snippet]
[File Name 2]
[Important Code Snippet]
[...]
Errors and fixes:
[Detailed description of error 1]:
[How you fixed the error]
[User feedback on the error if any]
[...]
Problem Solving:
[Description of solved problems and ongoing troubleshooting]
All user messages:
[Detailed non tool use user message]
[...]
Pending Tasks:
[Task 1]
[Task 2]
[...]
Current Work:
[Precise description of current work]
Optional Next Step:
[Optional Next step to take]
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
Compact Instructions
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
IMPORTANT: Do NOT use any tools. You MUST respond with ONLY the ... block as your text output.
Trailing segment frame count issue: User reported that changing frame count in SegmentSettingsForm opened from the trailing segment doesn't update the timeline. I was investigating the onFrameCountChange flow through useSegmentSlotMode.ts → useFrameCountUpdater.ts when the user interrupted for a different question about the preset UI, then requested this summary.
Let me now compile the complete user messages and track all files.
Key Technical Concepts:
Structure video (guidance video) strips on timeline with hover preview using useVideoHoverPreview hook
Motion preset system with builtin presets + featured presets from database, using MotionPresetSelector shared component
Segment settings persistence via useServerForm auto-save (500ms debounce) → savePairMetadata → buildMetadataUpdate → stored in shot_generations.metadata.segmentOverrides
Line 78: phaseConfig: settings.motionMode === 'basic' ? null : settings.phaseConfig — this is what triggers the cascade delete bug (always passes phaseConfig: null in basic mode)
Shows "Default Preset - Switch modes or select a different preset" for builtin preset IDs that reach this component (happens when builtin ID is not in known list)
Mistook preset ID for screenshot path: User provided e1aad8bf-add9-4d7b-883b-d67d424028c4 which I tried to read as a file. User clarified "That's not a screenshot, that's an ID. Are these not defined as IDs?"
GuidanceVideoStrip edits reverted: Both my edits were reverted (by linter/user). I re-applied them when user asked to push.
MotionControl edit reverted: Same situation, re-applied.
Preset persistence bug: buildMetadataUpdate cascade-deleted selectedPhasePresetId when phaseConfig was null. Fixed by removing the cascade delete line.
Mismatched builtin preset IDs: Segment form used __builtin_segment_i2v_default__ while batch view used __builtin_default_i2v__. Shot defaults with batch view IDs weren't recognized by segment form. Fixed by aligning IDs.
Empty featuredPresetIds: Hardcoded [] in SegmentSettingsForm. Fixed by importing and using mode-appropriate IDs.
User feedback on plan to move preset selector: User said "It's okay to be in Advanced settings" — I had been considering moving it out of the collapsible. User redirected to focus on the persistence and display bugs.
User feedback on complexity: "Why's it not just showing the same input in the same way like the other fields?" — pointing out the preset selector shouldn't need special rendering, the root cause was mismatched IDs.
Problem Solving:
Solved: Structure video hover tooltip showing wrong frame number
Solved: Featured I2V preset not appearing in preset selector
Solved: Preset selection not persisting (cascade delete bug)
In progress: Trailing segment frame count changes in SegmentSettingsForm not updating timeline
All user messages:
"See the structure video stripe on @src/shared/hooks/timeline/ Why does the structure video, when you hover over it, why does it show the current frame of the actual video"
"That's correct that it shows the frames from the structure video. But I'm talking about the count at the bottom of it. The one that shows the number of frames we're taking from the actual overall video."
"what makes sense here? think it through"
"let's do that"
"e1aad8bf-add9-4d7b-883b-d67d424028c4 Can you see where we set the default presets for I2V? Can you add this one to the list?"
"That's not a screenshot, that's an ID. Are these not defined as IDs?"
"push to github"
"yes please" (re-apply changes and push)
"push it" (already pushed)
"Can you see why it doesn't show the presets in @src/shared/components/SegmentSettingsForm/? That should be a proper section like the one on the batch view, not just delaying the view. It also should persist like the other fields"
"Why does it still show this and not the selector? 'Default Preset Switch modes or select a different preset'"
"Why's it not just showing the same input in the same way like the other fields?"
"And see the trailing segment thing on the timeline? Why when i change Frames 18 (1.13s) on the @src/shared/components/SegmentSettingsForm/ that a click into from that does it not update on the timeline while it does normally?"
Pending Tasks:
Commit and push the SegmentSettingsForm preset fixes (segmentSettingsUtils.ts and SegmentSettingsForm.tsx changes)
Investigate and fix: trailing segment frame count changes in SegmentSettingsForm not updating timeline
The onFrameCountChange flow was being traced through useSegmentSlotMode.ts → useFrameCountUpdater.ts when the conversation was interrupted
Current Work:
Investigating why changing the frame count slider in SegmentSettingsForm (opened from a trailing segment on the timeline) doesn't update the timeline. The user said: "Why when i change Frames 18 (1.13s) on the @src/shared/components/SegmentSettingsForm/ that a click into from that does it not update on the timeline while it does normally?"
onFrameCountChange is explicitly excluded from useSegmentSettingsForm's formProps (Omit<..., 'onSubmit' | 'isSubmitting' | 'onFrameCountChange'>)
In useSegmentSlotMode.ts:246-253, onFrameCountChange is wired to debounce + call updatePairFrameCount
useFrameCountUpdater.ts handles trailing segments by updating metadata.end_frame in DB then calling loadPositions
I had just finished reading useFrameCountUpdater.ts and was about to determine why the trailing segment case specifically doesn't update the timeline visually. The investigation was interrupted by the summary request.
Optional Next Step:
Continue investigating the trailing segment frame count issue. The useFrameCountUpdater saves end_frame to metadata and calls loadPositions, but the timeline's trailingEndFrame state may not be reading from the same source. Need to check how trailingEndFrame is derived and whether loadPositions triggers an update to it. The disconnect is likely that the trailing endpoint position is driven by a different state (trailingEndFrame / onTrailingEndFrameChange in TimelineContainer) that isn't connected to the metadata update path.
Where refetch comes from useShotImages(shotId), a React Query useQuery that queries shot_generations joined with generations. The query key is ['all-shot-generations', shotId].
So loadPositions triggers a React Query refetch of shot_generations, which will return updated metadata (including the new end_frame).
Key insight:trailingEndFrame = localEndFrame ?? derivedEndFrame. localEndFrame is only set during drag operations (by handleTrailingEndFrameChange / onTrailingEndFrameChange). For the form path, localEndFrame is NOT set -- only the DB is updated.
So the chain is:
updatePairFrameCount writes end_frame to DB metadata
loadPositions triggers a refetch of useShotImages (query key ['all-shot-generations', shotId])
When the query resolves, shotGenerations updates
derivedEndFrame recomputes from the new shotGenerations data
Since localEndFrame is undefined, trailingEndFrame = derivedEndFrame (the new value)
trailingEndFrame is passed down to Timeline -> TimelineContainer
7. How trailingEndFrame reaches the timeline visual
But for the trailing segment, the pair data is computed in TimelineContainer, not in pairDataByIndex from useSegmentSlotMode. The trailing segment pair data is constructed on-the-fly in TimelineContainer.tsx (lines 339-351):
ts
if (pairIndex === pairInfo.length && trailingEndFrame !== undefined && currentPositions.size > 0) {
// ... trailing segment pair data built here using trailingEndFrame ...
const effectiveEndFrame = trailingEndFrame ?? (imageFrame + defaultOffset);
However, the timeline visual (the rendering of the trailing segment bar) reads trailingEndFrame directly, so it SHOULD update when trailingEndFrame changes.
9. Root cause analysis
The actual data flow for the timeline visual update is:
DB write of metadata.end_frame -- OK
loadPositions() calls refetch() on React Query -- OK
React Query refetches shot_generations from DB -- OK
shotGenerations updates with new metadata -- OK
derivedEndFrame recomputes from shotGenerations -- OK
trailingEndFrame updates -- OK
Timeline re-renders with new trailingEndFrame -- this should work
BUT, there is a subtle issue. Look at useFrameCountUpdater.ts line 102-104:
And loadPositions in useShotGenerationsData.ts (line 131):
ts
loadPositions: coreHookData.refetch,
Where coreHookData.refetch is useTimelineCore's refetch (line 660):
ts
refetch: () => refetch(),
This refetch() is void -- it does NOT return a promise. The React Query refetch() returns Promise<QueryObserverResult>, but the wrapper () => refetch() just calls it and returns undefined. Meanwhile, loadPositions is typed as returning Promise<void>.
However, this should still trigger the refetch -- it just means the await in useFrameCountUpdater doesn't actually wait for the refetch to complete. The refetch still happens asynchronously and when it resolves, shotGenerations will update, derivedEndFrame will recompute, and the timeline should re-render.
10. The ACTUAL likely root cause
Looking more carefully at the SegmentSettingsFormhandleFrameCountChange:
So the value should be correct. The timeline visual refresh chain should work. Let me check one more thing -- whether the segmentSlotModeData.pairData.frames that's displayed in the form header updates.
Actually, let me re-examine lines 480-482 from SegmentSlotFormView.tsx:
This reads from segmentSlotMode.pairData.frames which comes from the stale activePairData in useSegmentSlotMode. This label would NOT update. But the question is about the timeline visual, not the form label.
Let me check whether the TimelineContainer re-renders with the new trailingEndFrame. The key dependency chain is:
loadPositions triggers React Query refetch
shotGenerations in ShotImagesEditor updates (it's the query data)
derivedEndFrame useMemo recomputes (depends on [shotGenerations])
trailingEndFrame = localEndFrame ?? derivedEndFrame recomputes on re-render
TimelineModeContent receives new trailingEndFrame prop
Timeline receives it
TimelineContainer receives it and re-renders
This chain should work. The refetch from React Query should cause shotGenerations to update, which causes derivedEndFrame to recalculate, which causes trailingEndFrame to update.
Let me double-check one more thing -- whether loadPositions in useShotGenerationsData for the preloaded path is different.
Step 3 - Debounced in useSegmentSlotMode
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/ShotImagesEditor/hooks/useSegmentSlotMode.ts line 246-253
Debounces 150ms, then calls updatePairFrameCount(pairShotGenerationId, frameCount)
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/ShotImagesEditor.tsx line 192-211
derivedEndFrame is a useMemo that depends on [shotGenerations]
It reads metadata.end_frame from the last positioned image
When shotGenerations updates with the new metadata, derivedEndFrame returns the new value
Step 7 - trailingEndFrame updates and propagates
Line 214: const trailingEndFrame = localEndFrame ?? derivedEndFrame
Since localEndFrame is undefined (only set during drag), trailingEndFrame equals the new derivedEndFrame
This is passed as a prop through: ShotImagesEditor -> TimelineModeContent -> Timeline -> TimelineContainer
The Likely Issue: activePairData Staleness in the Form
The timeline visual itself should update correctly via the trailingEndFrame prop chain. However, there is a significant staleness issue with the form's own display of the pair data.
In useSegmentSlotMode.ts, the segmentSlotModeData (line 156-308) is built from activePairData, which is a React state variable set once when the pair is clicked (line 144-150):
ts
const handlePairClick = useCallback((pairIndex: number, passedPairData?: PairData) => {
const pairData = passedPairData || pairDataByIndex.get(pairIndex);
if (pairData) {
setActivePairData(pairData); // <-- Set once, never updated
}
setSegmentSlotLightboxIndex(pairIndex);
}, [pairDataByIndex]);
The segmentSlotModeData.pairData.frames and segmentSlotModeData.pairData.endFrame will remain stale because activePairData is never updated after updatePairFrameCount completes. This means:
The header in SegmentSlotFormView showing {segmentSlotMode.pairData.frames} frames (line 481) will show the old frame count
The pairData.endFrame used for structure video frame range calculations will be stale
But for the actual timeline bar rendering...
The TimelineContainer constructs trailing segment rendering data on-the-fly using the trailingEndFrame prop directly (lines 339-351, 275, 497-504), NOT from activePairData. So the timeline bar width should update.
Possible Reasons the Timeline Does NOT Visually Update
React Query refetch timing: loadPositions in useTimelineCore is () => refetch() -- this calls refetch() but does NOT return the promise. The await loadPositions(...) in useFrameCountUpdater resolves immediately (as undefined), meaning the function returns { finalFrameCount } before the data is actually refreshed. However, the refetch still fires and should eventually cause a re-render.
The useTimelineOrchestratorcurrentPositions: The timeline visual uses currentPositions from dynamicPositions() which comes from useTimelineDrag. The trailingEndFrame affects the timeline dimensions (trailingEffectiveEnd on line 217-224 of useTimelineOrchestrator.ts) and the trailing bar rendering, but only if trailingEndFrame actually changes value from the Timeline's perspective.
trailingEndFrame is undefined vs a number: If derivedEndFrame was previously undefined (no trailing segment configured), then after the update it becomes a number. But if the form is open for a trailing segment, it means trailingEndFrame must already have been defined. The question is whether the timeline can tell it changed from, say, 66 to 82.
Potential memoization issue in TimelineContainer: The TimelineContainer receives trailingEndFrame as a prop. If TimelineContainer is wrapped in React.memo, it should still re-render because the number value changed. The segmentEntries useMemo (line 289) depends on trailingEndFrame, so it should recompute.
Most likely root cause -- the preloaded path: If this is happening in a context where preloadedImages is provided, then shotGenerations = preloadedImages (the prop from the parent). Even though loadPositions calls refetchQueries, the preloadedImages prop doesn't change (it comes from the parent component), so derivedEndFrame will never see the updated metadata. The loadPositions for the preloaded path (useTimelinePositionUtils.loadPositions) DOES refetch the query, but shotGenerations in ShotImagesEditor is set to preloadedImages directly (line 152 of useShotGenerationsData), bypassing the refetched data.
trailingEffectiveEnd includes trailingEndFrame in dimension calculations
Recommended Investigation
Check whether the context where this bug manifests uses preloadedImages. If it does, that's the root cause -- loadPositions refetches the query but shotGenerations stays as the original preloadedImages prop.
If NOT using preloadedImages, add a console.log in the derivedEndFrame useMemo to see if it recomputes after loadPositions. The refetch should cause shotGenerations to update and trigger the memo.
Check whether handleTrailingEndFrameChange (which sets localEndFrame) is somehow being called with a stale value that masks the new derivedEndFrame. The cleanup effect on lines 217-221 clears localEndFrame when it matches derivedEndFrame, but there could be a race condition if localEndFrame is set to some other value during the process.
So the data structure is identical -- the difference is just whether regular pairs exist before the trailing one.
This is a separate code path from the multi-image trailing handler at line 339, but they produce the same shape of data (endImage: null).
c) Trailing endpoint rendering (lines 738-821):
The TrailingEndpoint component renders for both cases, but the gating logic differs:
typescript
// Multi-image: skip rendering if no explicit trailing segment AND no existing trailing video
if (isMultiImage && !hasTrailingSegment && !hasExistingTrailingVideo) {
return null; // <-- only skips for multi-image
}
// Single-image: always renders (this condition is never true for single-image)
const defaultEndFrame = imageFrame + (isMultiImage ? 17 : 49); // <-- different defaults
Key rendering differences:
Aspect
Single-image
Multi-image trailing
Default frame offset
49 frames
17 frames
Gating
Always shows (never gated)
Only shows when trailingEndFrame is set OR a trailing video exists
compact prop
false (isMultiImage is false)
true (isMultiImage is true)
Remove button
Never shown (onRemoveTrailingSegment requires isMultiImage, line 512)
Shown when trailingEndFrame is set
Add button
Never shown (already always present)
Shown via onAddTrailingSegment in SegmentOutputStrip
The orchestrator computes trailingEffectiveEnd which is used for timeline dimensions (lines 215-224):
typescript
const isMultiImage = images.length > 1;
const trailingDefaultOffset = isMultiImage ? 17 : 49;
const trailingEffectiveEnd = (() => {
if (images.length === 0) return null;
// For multi-image, only include trailing in dimensions when:
// 1. Explicitly enabled (trailingEndFrame is set), OR
// 2. A trailing video already exists
if (isMultiImage && trailingEndFrame === undefined && !hasExistingTrailingVideo) return null;
return trailingEndFrame ?? (Math.max(...Array.from(framePositions.values()), 0) + trailingDefaultOffset);
})();
For single-image: trailingEffectiveEnd is always computed (never returns null after the length === 0 check). It uses a default offset of 49 if trailingEndFrame isn't explicitly set.
For multi-image: trailingEffectiveEnd is null unless trailingEndFrame is set or a trailing video exists. Uses default offset of 17.
The duplicate handler (line 422) also branches:
typescript
if (images.length === 1) {
duplicateTargetFrame = trailingEndFrame ?? (timeline_frame + 49);
// Single-image: duplicate goes to the trailing endpoint position
} else if (nextImage) {
duplicateTargetFrame = Math.floor((timeline_frame + nextImage.timeline_frame) / 2);
}
4. ShotImagesEditor.tsx -- derivedEndFrame and trailingEndFrame
derivedEndFrame (lines 192-211) reads end_frame from the last positioned image's metadata. It validates that endFrame > lastImageFrame. This is the source of truth for both single and multi-image.
typescript
const trailingEndFrame = localEndFrame ?? derivedEndFrame; // line 214
For single-image mode, trailingEndFrame is always set because:
The single image is the "last" image.
If the user has set an end_frame in its metadata, derivedEndFrame returns it.
If not, derivedEndFrame is undefined, but the timeline orchestrator and container use default offsets (49 frames for single-image).
However, there is a subtle point: trailingEndFrame being undefined vs having a value matters. When it is undefined for single-image, the orchestrator still computes trailingEffectiveEnd using the default offset. But usePairData will NOT create a trailing pair (it checks lastImageEndFrame !== undefined from metadata). So end_frame metadata must be set for single-image to have a generatable segment.
So single-image mode (segment_index=0, no end image) implies is_first_segment=true AND is_last_segment=true, which the backend interprets as isSingleItem.
When isSingleItem is true (/Users/user_c042661f/Documents/reigh/supabase/functions/complete_task/generation-child.ts, lines 49-62):
It creates a variant on the parent generation (via createSingleItemVariant) AND a child generation.
The comment says: "Travel sends is_single_item for n=1; Join doesn't use single-item handling."
Duplication in useGenerationActions.ts (line 452):
For single-image, the duplicate targets the trailing endpoint position and uses the original image's frame as the source.
Summary: Shared Mechanism, Different Gating
Layer
Shared mechanism
Single-image difference
Data (usePairData)
Both produce endImage: undefined pairs from end_frame metadata
Single-image: trailing pair is the only pair (index 0)
Dimensions (useTimelineOrchestrator)
Both use trailingEffectiveEnd for timeline bounds
Single-image: never gated (always included), default offset 49 vs 17
Rendering (TimelineContainer)
Both use TrailingEndpoint component with same props shape
Single-image: always visible, not compact, no remove button, default 49 frames
Click handling (handleOpenPairSettings)
Both produce endImage: null pair data
Separate code paths (line 312 vs 339) but identical output shape
Task creation (individualTravelSegment)
Both omit end_image_url, set is_last_segment: true
Single-image also has is_first_segment: true (segment_index=0), triggering isSingleItem
Task completion (complete_task)
Both create child generations under parent
isSingleItem: also creates variant on parent (dual write)
The core insight: single-image mode IS a trailing segment -- it is a trailing segment that happens to be the only segment. The trailingEndFrame mechanism, endImage: undefined pair structure, and end_frame metadata storage are all shared. The differences are purely about UX gating (always show vs opt-in), default sizes (49 vs 17 frames), and backend handling (single-item gets a parent variant too).
syncFromDatabase
pendingUpdatesRef -- tracks optimistic updates that haven't been verified by server yet
snapshotRef -- stores pre-update positions for rollback on error
How it syncs from shotGenerations data:
The syncFromDatabase callback builds a new Map<string, number> from shotGenerations (the React Query data). It:
Skips sync if isLocked or status === 'updating'
Iterates shotGenerations, adding entries where timeline_frame >= 0 (sentinel -1 means unpositioned)
Merges with pending updates: If pendingUpdatesRef has entries, it checks each:
If server matches the pending position (within 0.01 tolerance) -> verified, remove from pending
If pending update is > 10 seconds old -> timed out, accept server state
Otherwise -> override server data with local pending position (protects dragged items from jumping back)
Compares via JSON serialization to skip no-op updates
Calls setPositions(newPositions) and onPositionsChange callback
What triggers position updates:
useEffect watching [shotId, shotGenerations, syncFromDatabase] -- any time React Query delivers new generation data
updatePositions() -- called on drag-end via the setFramePositions wrapper. This does optimistic update + DB persist (batch RPC or fallback sequential updates). Positions are quantized to 4N+1 gaps for Wan model compatibility.
addItemsAtPositions() / removeItems() -- optimistic-only operations for drops/deletions
2. How Normal Segment Bars Are Rendered
Note: there is no segmentEntries useMemo in TimelineContainer. The user may have been thinking of the SegmentOutputStrip component, which handles segment bar rendering. Here is the full flow:
getPairInfo (/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/Timeline/utils/timeline-utils.ts, line 176) sorts all positions and creates sequential pairs:
The SegmentOutputStrip receives pairInfo, fullMin, fullRange, containerWidth, and trailingSegmentMode. It builds:
displaySlots (useMemo, line 484): Merges data from useSegmentOutputsForShot hook (actual video segments) with placeholder slots. For each pair, there is either a 'child' slot (has video) or a 'placeholder' slot.
segmentPositions (useMemo, line 644): Calculates pixel positions for each slot using the same formula as timeline items. Each entry has { pairIndex, leftPercent, widthPercent }.
Rendering (line 818): Maps displaySlots to InlineSegmentVideo components, positioned absolutely using leftPercent and widthPercent from segmentPositions.
How the trailing segment entry differs from normal entries
Normal segment slots have index matching a pair index (0, 1, 2...) and correspond to a pair of images. The trailing segment:
Has index = pairInfo.length (one past the last pair)
Has startImage but endImage: null
Its pairShotGenerationId is the last image's shot_generation_id
Gets an isTrailingSegment: true flag in displaySlots
When isTrailingSegment and it is a placeholder (no video yet), a small X button to remove it is rendered
The position uses trailingSegmentMode.imageFrame to trailingSegmentMode.endFrame instead of pair start/end
// Local UI state for responsive drag
const [localEndFrame, setLocalEndFrame] = useState<number | undefined>(undefined);
// Derived from DB: reads last image's metadata.end_frame
const derivedEndFrame = useMemo(() => {
const sortedImages = [...(shotGenerations || [])]
.filter((img) => img.timeline_frame != null && img.timeline_frame >= 0)
.sort((a, b) => (a.timeline_frame ?? 0) - (b.timeline_frame ?? 0));
if (sortedImages.length === 0) return undefined;
const lastImage = sortedImages[sortedImages.length - 1];
const lastImageFrame = lastImage.timeline_frame ?? 0;
const metadata = lastImage.metadata as Record<string, unknown> | null;
const endFrame = metadata?.end_frame;
if (typeof endFrame !== 'number' || endFrame <= lastImageFrame) return undefined;
return endFrame;
}, [shotGenerations]);
// Merge: local drag state takes priority over DB-derived value
const trailingEndFrame = localEndFrame ?? derivedEndFrame;
The onTrailingEndFrameChange callback is setLocalEndFrame -- so during drag, local state updates instantly; the DB value catches up after persist.
Every usage in TimelineContainer.tsx:
Line 81: Received as prop trailingEndFrame
Line 179: Passed to useTimelineOrchestrator which uses it to compute trailingEffectiveEnd for timeline dimensions
Lines 275-276 (handleExtractFinalFrame): const effectiveEndFrame = trailingEndFrame ?? (lastImageFrame + 17) -- to calculate where to place the extracted frame
Lines 293-296 (handleReset): For single-image mode, resets trailing to resetGap value
Lines 312-335 (handleOpenPairSettings, single-image): Uses trailingEndFrame to construct pair data with endFrame: trailingEndFrame
Lines 339-376 (handleOpenPairSettings, multi-image trailing): const effectiveEndFrame = trailingEndFrame ?? (imageFrame + defaultOffset) for the trailing segment's pair data
Lines 497-505 (SegmentOutputStrip trailingSegmentMode prop): Only passed when lastEntry && trailingEndFrame !== undefined:
Lines 508-515 (SegmentOutputStrip onAddTrailingSegment / onRemoveTrailingSegment): The add handler sets trailingEndFrame to lastImageFrame + 17; the remove handler clears it to undefined.
Lines 741-821 (TrailingEndpoint rendering): The main visual rendering. Key logic:
For multi-image: only renders if trailingEndFrame !== undefined OR hasExistingTrailingVideo
Passes effectiveEndFrame as framePosition to TrailingEndpoint
gapToImage = effectiveEndFrame - imageFrame
How the trailing bar renders vs normal bars
Normal bars (PairRegion): Rendered between two image positions. Colored background region with a pair label showing frame count. Each pair gets a different color from a palette.
Trailing bar (TrailingEndpoint):/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/Timeline/TrailingEndpoint.tsx
The TrailingEndpoint renders three visual elements:
Highlighted region (like PairRegion) -- div from imageLeftPercent to endpointLeftPercent with blue-themed background
Connecting line -- horizontal 2px line between the image and endpoint
Duration label -- centered between image and endpoint, shows "Duration - Xs", clickable to open settings. In compact mode (multi-image), only shows on hover or during drag.
Endpoint marker -- a vertical line with a draggable grip handle (blue pill with GripVertical icon). Has optional "extract final frame" button on hover when a trailing video exists.
The key visual difference: the trailing segment ends at a draggable endpoint marker rather than at another image. It uses a consistent blue color scheme rather than the rotating pair colors.
trailingSegmentMode prop
This prop is passed from TimelineContainer to SegmentOutputStrip (line 497):
ts
trailingSegmentMode={lastEntry && trailingEndFrame !== undefined ? {
imageId, // shot_generation_id of the last image
imageFrame, // frame position of the last image
endFrame: trailingEndFrame // the trailing endpoint frame
} : undefined}
SegmentOutputStrip uses it to:
Create a trailing placeholder slot in displaySlots (if no existing trailing video)
Calculate segment positions in segmentPositions for the trailing segment
In single-image mode (no pairs), the trailing becomes the ONLY slot (index 0)
const isMultiImage = images.length > 1;
const trailingDefaultOffset = isMultiImage ? 17 : 49; // Multi=17, single=49
const trailingEffectiveEnd = (() => {
if (images.length === 0) return null;
// Multi-image: only include in dimensions when explicitly enabled OR existing video
if (isMultiImage && trailingEndFrame === undefined && !hasExistingTrailingVideo) return null;
return trailingEndFrame ?? (Math.max(...Array.from(framePositions.values()), 0) + trailingDefaultOffset);
})();
This value is passed to getTimelineDimensions as a pending frame (line 226-234). This ensures the timeline coordinate system (fullMin/fullMax/fullRange) expands to include the trailing endpoint. The key logic:
Single-image: Always includes trailing in dimensions (default offset 49)
Multi-image: Only includes trailing when trailingEndFrame is set (user explicitly added) or hasExistingTrailingVideo is true
When neither condition is met, trailingEffectiveEnd = null, so the timeline dimensions ignore the trailing space
This is the core drag handler for the trailing endpoint. It does NOT use the useTimelineDrag hook (which handles image dragging). Instead, it implements its own mouse event listeners:
On mousedown:
Freezes timeline dimensions in dragStartDimensionsRef (prevents the timeline from resizing during drag)
Captures the last image's [id, frame] from dynamicPositions()
On mousemove (handleMouseMoveLocal):
Uses frozen dimensions from dragStartDimensionsRef
Converts mouse pixel position to frame number
Clamps frame between imageFrame + 5 and imageFrame + maxFrameLimit
Quantizes the gap: quantizedGap = max(5, round((gap - 1) / 4) * 4 + 1) -- ensures 4N+1 frame gaps for model compatibility
Calls onTrailingEndFrameChange(currentEndFrame) -- this is setLocalEndFrame in ShotImagesEditor, providing instant visual feedback
On mouseup (handleMouseUpLocal):
Clears dragStartDimensionsRef and isEndpointDraggingRef
Persists to database: Reads current metadata from shot_generations for the last image, merges end_frame: currentEndFrame into it, and writes back
Invalidates queryKeys.generations.byShot(shotId) so derivedEndFrame in ShotImagesEditor picks up the persisted value
The full cycle:
User drags endpoint -> handleEndpointMouseDown fires
During drag -> onTrailingEndFrameChange(frame) updates localEndFrame in ShotImagesEditor
trailingEndFrame = localEndFrame ?? derivedEndFrame immediately reflects the new value
This flows through TimelineContainer to TrailingEndpoint, SegmentOutputStrip, and the orchestrator's dimension calculations
On mouseup -> persists end_frame to metadata in DB
React Query invalidation -> shotGenerations refetch -> derivedEndFrame updates to match
useEffect in ShotImagesEditor clears localEndFrame when it matches derivedEndFrame
How hasExistingTrailingVideo affects dimensions
hasExistingTrailingVideo is computed synchronously in TimelineContainer (line 93-103) using findTrailingVideoInfo(). It checks videoOutputs for a video whose pair_shot_generation_id matches the last image. When true:
The orchestrator includes trailing in timeline dimensions even when trailingEndFrame === undefined
TimelineContainer renders the TrailingEndpoint component even without explicit trailing configuration
This ensures an existing trailing video's extent is always visible on the timeline
trailingSegmentMode
Key Files
useTimelinePositions.ts — core position state
usePositionManagement.ts — thin wrapper, delegates to useTimelinePositions
Timeline/SegmentOutputStrip.tsx — video output strip positioning
Goal
Make the trailing endpoint a position-managed entity so:
It goes through the same optimistic-update path as image positions
No separate trailingEndFrame prop chain through 3+ memo'd components
Form frame count changes provide immediate feedback (same as drag, same as normal segments)
Single state management system, no split between derivedEndFrame/localEndFrame/positions
Design Constraints
Visual rendering should stay as TrailingEndpoint (it looks different from PairRegion intentionally)
The drag behavior is different from image drag (constrained range, endpoint-specific) — can stay as custom handler but should read/write through positions
SegmentOutputStrip needs to know the trailing segment bounds for video output positioning
Single-image mode works the same as trailing but is always enabled (no gating)
usePairData reads metadata.end_frame for pair construction — this should still work
getPairInfo() in timeline-utils creates pairs from positions — the trailing entry would create a "pair" between last image and trailing end
Questions to address in the plan
What key to use for the trailing endpoint in the positions map? (e.g., __trailing_end__ sentinel vs composite key)
How to handle updatePositions for the trailing key (needs to write metadata instead of timeline_frame)?
How does the rendering code distinguish the trailing endpoint from real images?
What happens to the drag handler — stay separate or move into useTimelineDrag?
How to handle the gating logic (multi-image: only show when explicitly enabled)?
What's the migration path (can we do it incrementally)?
Propose a concrete implementation plan with file-by-file changes.
shotGenerations
shotGeneration
updatePositions
TRAILING_ENDPOINT_ID
metadata.end_frame
shot_generations
timeline_frame
Q3: How does rendering code distinguish the trailing endpoint from real images?
The rendering code in TimelineContainer already iterates images for TimelineItem rendering and pairInfo for PairRegion rendering. The trailing endpoint is rendered via the dedicated TrailingEndpoint component. We keep this separation: the TrailingEndpoint component reads its position from positions.get(TRAILING_ENDPOINT_ID) instead of from a prop. The images.map() loop naturally skips it because it is not in the images array.
Q4: Drag handler -- stay separate or move into useTimelineDrag?
Keep the drag handler separate in useTimelineOrchestrator. The trailing endpoint has fundamentally different drag constraints (min/max relative to the last image, quantization rules, no reordering logic). However, instead of directly writing to Supabase, the handler will call updatePositions with the new trailing position. This gives us optimistic updates for free while keeping the constraint logic specialized.
Q5: Gating logic (multi-image: only show when explicitly enabled)?
The gating stays the same -- the trailing endpoint position is only added to the positions map when trailingEndFrame is defined (user has enabled it) OR when a trailing video exists. The difference is that when present, it flows through the positions map rather than a separate prop. The syncFromDatabase method will handle reading metadata.end_frame and populating the TRAILING_ENDPOINT_ID entry.
Q6: Migration path (incremental)?
Yes. The plan is structured in 4 phases that can be landed independently. Each phase is self-contained and the system works correctly at every intermediate state.
Implementation Plan
Phase 1: Add trailing endpoint to the positions map (read path)
Goal: The positions map becomes the single source of truth for where the trailing endpoint is. No rendering changes yet -- just wire the data in.
Import TRAILING_ENDPOINT_ID from '../TrailingEndpoint'
After building newPositions from shotGenerations, add trailing endpoint logic:
Find the last positioned image (highest timeline_frame)
Read metadata.end_frame from that image's shotGeneration
If valid (> last image frame), add newPositions.set(TRAILING_ENDPOINT_ID, endFrame)
This replaces derivedEndFrame computation in ShotImagesEditor.tsx
Changes to updatePositions() (around line 441-460):
When building dbUpdates, detect if change.id === TRAILING_ENDPOINT_ID
For the trailing endpoint, instead of writing timeline_frame, write metadata.end_frame on the last positioned image's shot_generations row
This requires finding the last image's shot_generation from shotGenerations (already available)
The DB write is: fetch current metadata, merge end_frame: newPos, update
Add a new exported helper:
typescript
export const [REDACTED];
export function isTrailingEndpointKey(id: string): boolean {
return id === TRAILING_ENDPOINT_KEY;
}
Note: Reuse the existing TRAILING_ENDPOINT_ID from TrailingEndpoint.tsx to avoid duplication. Either re-export from there or move the constant to a shared location (e.g., constants.ts in the Timeline directory).
Filter out TRAILING_ENDPOINT_ID from positions before computing pairs (it should NOT create a "pair" between the last image and the trailing endpoint in the normal pair array -- that is handled separately)
Add a new helper getTrailingInfo(positions) that returns { imageId, imageFrame, endFrame } | null by reading the trailing endpoint from positions
Changes to getTimelineDimensions():
No changes needed -- the trailing endpoint frame is already in the positions map, so Math.max(...positions.values()) naturally includes it
Changes to quantizePositions():
Filter out TRAILING_ENDPOINT_ID before quantizing (it has its own quantization rules)
Preserve the trailing endpoint's original position in the result
Phase 2: Wire rendering to read from positions map instead of props
Goal: Remove the trailingEndFrame prop chain. Components read from the positions map.
Remove trailingEndFrame and onTrailingEndFrameChange from props
Remove trailingEffectiveEnd computation (lines 217-224) -- the positions map handles this
Remove isEndpointDraggingRef (it was needed for dimension freezing during trailing drag -- can be replaced by checking dragState.activeId === TRAILING_ENDPOINT_ID)
The handleEndpointMouseDown handler changes: instead of doing direct Supabase writes, it:
Computes the new endpoint frame (same constraint logic)
Calls setFramePositions(newPositions) where newPositions has the trailing endpoint updated
On mouse up: calls setFramePositions which goes through updatePositions -> DB write
Remove handleEndpointMouseDown's direct Supabase code (lines 626-655)
Phase 3: Unify the frame count update path
Goal: useFrameCountUpdater trailing segment branch uses updatePositions instead of direct DB writes.
Remove onTrailingEndFrameChange prop (no longer needed)
The trailing segment branch (lines 71-113) changes:
Instead of direct Supabase write to metadata.end_frame, call a new callback that updates the positions map
This callback should be updateTrailingPosition(newEndFrame: number) which creates a new positions map with TRAILING_ENDPOINT_ID set to newEndFrame and calls updatePositions
The loadPositions call after the update becomes unnecessary because updatePositions already handles optimistic update + cache invalidation
In updatePositions, handle the removal case: if TRAILING_ENDPOINT_ID was in old positions but not in new, clear metadata.end_frame from the last image
In removeItems, handle TRAILING_ENDPOINT_ID specifically
Downstream Consumers That Must Continue Working
usePairData.ts: Reads metadata.end_frame to construct trailing pair data. This continues to work unchanged because the DB storage is the same (metadata.end_frame on the last image's shot_generations row). The position system writes to the same field.
SegmentOutputStrip.tsx: Receives trailingSegmentMode prop. In Phase 2, this is derived from the positions map in TimelineContainer instead of from the trailingEndFrame prop:
Task creation paths (individualTravelSegment.ts, payloadBuilder.ts): These read end_frame in the context of structure videos, not the trailing segment metadata. They are unaffected.
useSegmentSlotMode.ts: Uses useFrameCountUpdater which has the trailing branch. Fixed in Phase 3.
Risks and Mitigations
Quantization interference: quantizePositions operates on all positions and normalizes the first to 0. The trailing endpoint must be excluded from this normalization. Mitigation: filter it out before quantizing, re-add after.
getPairInfo accidentally creating a trailing "pair": If the trailing endpoint is in the positions map, getPairInfo would create a pair between the last image and the trailing endpoint. Mitigation: filter out TRAILING_ENDPOINT_ID in getPairInfo.
Pending update merging: syncFromDatabase merges pending updates. The trailing endpoint needs to participate in this correctly. Since it is written to metadata.end_frame (not timeline_frame), the server-side verification in syncFromDatabase needs to check metadata.end_frame rather than timeline_frame for the trailing key. Mitigation: special-case the TRAILING_ENDPOINT_ID in the sync logic.
Batch update RPC: batch_update_timeline_frames RPC only handles timeline_frame. The trailing endpoint write must bypass this and do a separate update. Mitigation: partition the updates in updatePositions into normal (RPC) and trailing (direct write).
Lines of Code Impact Estimate
Removed: ~120 lines of prop threading, duplicate state management, and direct Supabase writes
Added: ~60 lines of trailing-specific handling in useTimelinePositions
Modified: ~80 lines across rendering components switching from props to positions map reads
Net: ~40 lines removed
Critical Files for Implementation
Critical Files for Implementation
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/Timeline/hooks/useTimelinePositions.ts - Core: add trailing endpoint to positions map sync and updatePositions DB write path
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/Timeline/TimelineContainer/TimelineContainer.tsx - Primary consumer: switch from trailingEndFrame prop to positions map reads for all rendering
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/Timeline/hooks/useTimelineOrchestrator.ts - Drag handler: remove direct Supabase writes, use updatePositions; remove trailingEffectiveEnd computation
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/ShotImagesEditor.tsx - Remove derivedEndFrame/localEndFrame/trailingEndFrame state and prop threading
/Users/user_c042661f/Documents/reigh/src/tools/travel-between-images/components/Timeline/utils/timeline-utils.ts - Filter trailing key from getPairInfo and quantizePositions; add getTrailingInfo helper