Read and review ALL uncommitted changes in the media-lightbox domain. Run git diff HEAD -- src/domains/media-lightbox/ and read the full output.
For each file, evaluate:
Are props being removed safely (no remaining references)?
Is the logic change correct?
Any dead code, missing imports, or broken patterns?
Report back with a detailed assessment of each file's changes, flagging anything that looks wrong or low quality. Include the specific file paths, line numbers, and code snippets for any issues.
User
Read and review ALL uncommitted changes in supabase edge functions. Run git diff HEAD -- supabase/ and read the full output.
For each file, evaluate:
Is the logic change correct?
Any edge cases missed?
Test coverage adequate?
Any security issues?
Report back with a detailed assessment of each file's changes, flagging anything that looks wrong or low quality. Include specific file paths, line numbers, and code snippets for any issues.
User
Read and review ALL uncommitted changes in shared hooks and lib. Run these commands and read the full output:
git diff HEAD -- src/shared/hooks/
git diff HEAD -- src/shared/lib/
git diff HEAD -- src/shared/components/MediaSelectionPanel.tsx
git diff HEAD -- src/shared/components/MediaGalleryItem/
For each file, evaluate:
Is the logic change correct?
Any dead code or broken patterns?
Are tests updated properly?
Any regressions?
Report back with a detailed assessment, flagging anything wrong or low quality. Include specific file paths, line numbers, and code snippets.
User
Read and review ALL uncommitted changes in the tools domain. Run these commands and read the full output:
git diff HEAD -- src/tools/
git diff HEAD -- src/domains/generation/
git diff HEAD -- src/domains/lora/
For each file, evaluate:
Is the logic change correct?
Any dead code, missing imports, or broken patterns?
Are tests updated properly?
Any regressions or poor engineering?
Report back with a detailed assessment of each file's changes, flagging anything that looks wrong or low quality. Include specific file paths, line numbers, and code snippets.
Assistant
Now let me read the new file that was added and check the current state of the files being modified.
Assistant
I'll run all four diff commands in parallel to get the full picture.
Assistant
The output was truncated. Let me get the rest.
Assistant
I'll read the diffs in parallel.
User
Read and review ALL uncommitted changes in these areas. Run these commands and read the full output:
git diff HEAD -- src/shared/components/MediaGallery/MediaGallery.tsx (the main orchestrator - review the full current file for quality)
git diff HEAD -- src/shared/components/MediaGallery/hooks/useMediaGalleryLightboxControllers.ts
git diff HEAD -- src/shared/components/MediaGallery/hooks/useMediaGalleryLightboxSession.test.ts
git diff HEAD -- src/shared/components/MediaGallery/hooks/useMediaGalleryViewInteractions.test.ts
git diff HEAD -- src/shared/components/MediaGallery/hooks/useMediaGalleryLightboxControllers.test.ts
git diff HEAD -- src/shared/components/MediaGallery/index.ts
git diff HEAD -- src/shared/components/MediaGallery/types.ts
git diff HEAD -- src/shared/components/MediaGalleryItem.test.tsx
git diff HEAD -- docs/
git diff HEAD -- eslint.supabase-facade-allowlist.js
git diff HEAD -- src/infrastructure/
git diff HEAD -- src/features/gallery/components/GenerationsPane/hooks/useGenerationsPaneController.test.ts
For each file, evaluate:
Is the change correct and well-engineered?
Any dead code, missing imports, or broken patterns?
Any regressions?
Report back with a detailed assessment, flagging anything wrong or low quality. Include specific file paths, line numbers, and code snippets.
Assistant
Now let me read a few files to understand the full context of the changes better.
Assistant
Now let me check if the removed props are still referenced anywhere in the consumers.
Assistant
I'll run all the diff commands in parallel to review the changes.
Assistant
Let me read the full tools diff output.
Assistant
Now let me check if there's a CompletionError class being added (it's imported but may be a new file).
Assistant
Now let me check the phaseConfig types and verify the settingsMigration changes are complete.
Assistant
There are remaining references in the interface. Let me check the full current state of ImageLightboxControlsPanel.tsx.
Assistant
Let me check if the deleted test has been relocated or if its coverage is now missing.
Assistant
Now let me read the full current state of MediaGallery.tsx and check for the DEFAULT_GALLERY_FILTERS removal in types.ts.
Assistant
The nested read is double-numbering lines. Let me get the raw diff output directly.
Assistant
Now let me check the interface definition still has those stale props.
Assistant
Now let me also look at the handler.ts to understand the full catch block context.
Assistant
Now let me check the remaining issue - the interface in ImageLightboxControlsPanel.tsx still declares props that are no longer destructured.
Assistant
Let me check the types.ts diff more carefully -- the DEFAULT_GALLERY_FILTERS import was removed but the re-export on line 9 still exists. Let me also check a few more things.
Assistant
Now let me verify the callers of updateToolSettingsSupabase have all been updated to the new options-object API.
Assistant
Let me read the file in chunks.
Assistant
Let me check the caller site to see what's being passed.
Assistant
Now let me check the types.ts more carefully -- the diff removes the import of DEFAULT_GALLERY_FILTERS but line 9 still has a re-export export { DEFAULT_GALLERY_FILTERS } from '...'. This is fine because the re-export doesn't need an import -- it's a direct re-export from the source module. No issue there.
Let me check a couple more things for completeness.
Assistant
I see a stale doc reference. Let me check the useDebouncedSettingsSave.ts call and the settings_system.md doc more carefully.
Assistant
Now let me check the settings file to understand migrateLegacyStructureVideos and verify the normalizeStructureVideo function handles the legacy flat fields properly.
Assistant
Now I have a clear picture. Let me also check one more thing about the useVideoLightboxRenderModel - the selectedShotId variable was moved but is it still used?
Assistant
This is a problem. The function signature was changed to take an options object, but this caller at line 205 still passes 'immediate' as a positional string argument.
Assistant
Good -- both new allowlist entries exist as actual files. Let me now verify the deleted test file doesn't leave any dangling references and check a couple more potential issues.
Assistant
Good - selectedShotId is still used at line 298. Now let me check whether the VideoEditPanel docstring is stale.
Assistant
Now let me check the useEffect dependency change and verify the coerceGenerationRowDto is being imported correctly.
Assistant
Confirmed -- this is a bug. The function now expects options: UpdateToolSettingsOptions = {} but line 205 passes the bare string 'immediate'. TypeScript should catch this, but it's worth flagging.
Let me check if there are any other callers still using the old positional API.
Assistant
Now let me check the LightboxShotWorkflowProps and ImageLightboxSharedModel imports - are they still used?
Assistant
Good. No dangling references to the deleted test file. Let me now check the useMediaGalleryLightboxControllers.ts more carefully -- the function now uses fetchGenerationRecordById which returns GenerationRecord (a raw DB row with Record<string, unknown>) instead of GenerationRow. The code afterwards does const row = data as Record<string, unknown> -- let me verify the diff removed that cast properly.
Looking at the diff again: the old code did const row = data as Record<string, unknown> (line removed in diff), and the new code just uses row directly (which is already GenerationRecord -- essentially Row & Record<string, unknown>). The subsequent code accesses row.params, row.based_on, row.thumbnail_url, row.location, row.video_url, row.id, row.created_at, row.starred, row.shot_data. This all works because GenerationRecord is typed as Database['public']['Tables']['generations']['Row'] & Record<string, unknown>, so it has both typed fields and allows arbitrary access.
The error handling also changed correctly: the old code had if (error) throw error and the new repository function throws on error internally, so the outer try/catch still catches it properly.
Now let me verify the useGenerationsPaneController.test.ts diff since git status shows it modified.
Assistant
Let me verify that the normalizeStructureVideo in settings.ts handles the legacy flat fields in the test properly. The test passes structure_video_path, structure_video_motion_strength, and structure_video_type at the top level. Let's trace the code path.
Assistant
Those are fine (single-arg calls using default options). Now let me also verify whether the useDebouncedSettingsSave.ts file is part of the uncommitted changes or not.
Assistant
Empty diff means staged changes only. Let me check.
Assistant
Here is my detailed assessment of all uncommitted changes in the supabase/ directory.
Change: Added an optional options?: { recoverable?: boolean } parameter to completeTaskErrorResponse, allowing callers to override the default recoverable heuristic (status >= 500 || status === 429).
Assessment:
Correctness: Good. The options?.recoverable ?? (default) pattern preserves backward compatibility — existing callers without the argument get the same behavior.
Edge cases: If options is passed but recoverable is omitted (e.g., { } with no recoverable), it falls through to the default, which is correct.
Includes the error code in the markTaskFailed message
Passes the structured error's message, code, and recoverable to completeTaskErrorResponse instead of the generic "Internal server error"
Assessment:
Correctness: Sound. The instanceof check is appropriate since CompletionError is a class extending Error. The fallback for non-CompletionError exceptions preserves the existing behavior.
Potential concern — information leakage: When a CompletionError is caught, its is returned directly to the client (). This is intentional (the class is designed to carry user-facing messages), but worth noting: any code throwing must ensure the is safe to expose. Since this is a structured error class under the project's control, this is fine as long as it's a known convention.
Assistant
Now I see -- normalizeStructureVideo is called with record.structureVideo ?? record (the whole settings record as fallback). When the test passes structure_video_path: 'https://example.com/guide.mp4' at the top level, record.structureVideo is undefined, so it falls through to pass the whole record to normalizeStructureVideo. Inside, asRecord(record) succeeds but asString(record.path) is undefined (since it's structure_video_path not path), so it falls through to migrateLegacyStructureVideos which handles structure_video_path. Good, that traces correctly.
Let me check the useEffect dependency concern -- the diff changes setTurboMode in deps to motionSettings:
Assistant
No changes to that file -- so it's an existing file that was NOT updated when the API signature changed. This is a regression bug: useDebouncedSettingsSave.ts line 205 passes 'immediate' as the second positional argument, but the new signature expects UpdateToolSettingsOptions (an object). The string 'immediate' will be assigned to options, and isSettingsWriteMode(options.mode) will be false, so the mode will silently fall back to 'debounced' instead of 'immediate'. This is a correctness bug -- flushes on unmount/navigation will be debounced instead of immediate.
Now let me check the settings_system.md doc which also shows the old API.
Assistant
Now let me verify the MediaGallery import path change in MediaSelectionPanel.tsx is valid.
Assistant
This is a potential issue. The useEffect now depends on motionSettings (the full object) instead of setTurboMode (a stable setter). If motionSettings is a new object on every render (e.g. from a context), this effect will fire unnecessarily. Let me check if useMotionSettings returns a stable object.
Assistant
Good -- GalleryFilterState and DEFAULT_GALLERY_FILTERS are both exported from src/shared/components/MediaGallery/index.ts. The import change in MediaSelectionPanel.tsx is correct.
Now let me verify the MediaGallery/types import path change in the MediaGalleryItem hooks is valid.
Assistant
OK -- useMotionSettings uses useMemo but the memo depends on handlers (and handlers is likely a new object on every settings change). So the motionSettings object will be recreated when any setting changes (not just turbo/motion-related ones). Using motionSettings as a dependency instead of setTurboMode will cause the effect to re-run more often than necessary. This is a minor inefficiency, not a bug, since the effect's body is guarded by the condition check.
Now let me verify the GenerationRowDto import removal is safe.
Assistant
Good -- the direct GenerationRowDto type import was removed because coerceGenerationRowDto returns the properly typed value now. The return type of coerceGenerationRowDto already includes GenerationRowDto & { params?: Json | null }, so no broken type dependency.
Now let me verify the copyShotSettings change that removed the else branch with toast.error:
Assistant
Good -- both types exist in the new location. The import path changes in useMediaGalleryItemShotWorkflow.ts and useMediaGalleryItemTaskShare.ts are correct.
Let me also verify the params change in transformToGenerationRow is correct.
The change at line 124 is params: gen.params ?? undefined. Previously it was params: gen.params as GenerationRow['params']. Let me check what GenerationRow['params'] expects.
Assistant
Now I have a complete picture. Here is my assessment:
Detailed Assessment of Uncommitted Changes in src/domains/media-lightbox/
1. ImageLightboxControlsPanel.tsx — Two issues found
Issue A: Dead props in interface (lines 15-20)
The interface ImageLightboxControlsPanelProps still declares four props that are no longer destructured in the component:
shotId (line 15)
onOpenExternalGeneration (line 16)
shotWorkflow (line 17)
sharedModel (line 20)
These are removed from the destructuring (correct) but left in the interface. This means TypeScript won't error — the props are optional or still typed — but the caller at /Users/user_c042661f/Documents/reigh/src/domains/media-lightbox/ImageLightbox.tsx (lines 276-281) is still passing them:
These passed values are silently ignored. The interface props and the caller's pass-throughs should both be cleaned up.
Issue B: Stale imports (lines 4-5, 10)LightboxShotWorkflowProps (line 5) and ImageLightboxSharedModel (line 10) are only used in the interface for the dead props. If the dead props are removed, these imports become dead too.
Severity: Medium. No runtime bug, but dead code that will confuse future readers.
2. InfoPanel.tsx — Clean
All removed props (derivedItems, derivedGenerations, paginatedDerived, derivedPage, derivedTotalPages, onSetDerivedPage, onNavigateToGeneration, currentMediaId, currentShotId, onSwitchToPrimary, primaryVariant) are removed from:
The InfoPanelTaskPanelModel interface
The destructuring
The JSX pass-through to TaskDetailsPanelWrapper
The DerivedItem and type imports are also removed since they were only used in the deleted interface fields. No remaining references. Clean.
Assistant
The file has already been committed in a prior commit on this branch. The initial git status snapshot was stale. No uncommitted changes there.
Change: Replaces a 2-line deprecated shim (export { MediaGallery } from '@/features/gallery/...') with the full ~487-line orchestrator component, moving canonical ownership back to src/shared/.
Quality assessment: Well-structured. The component is large but appropriately orchestrated -- it composes many hooks (state, filters, pagination, actions, lightbox session, view interactions) and renders sub-components (Header, ShotNotifier, Grid, Lightbox, MobileBottomBar). The useAspectRatioLayout helper is correctly extracted as a local function at the top of the file.
Potential concerns:
Two destructured props are unused: _currentToolTypeName and _lastShotNameForTooltip (lines ~95, ~101). These are prefixed with _ which is the standard convention for intentionally unused destructured props, so this is fine.
The withPaginationReset callback (line ~147) captures paginationHook in its dependency array. Since paginationHook is a hook return object that changes every render, this callback will re-create every render. However, it's only used in event handlers (not in dependency arrays of other effects), so this is acceptable -- it's not causing cascading re-renders.
No dead code, no missing imports. All sub-component and hook imports resolve to files within the same MediaGallery/ directory tree.
Change: Replaces direct getSupabaseClient().from("generations").select("*").eq(...).single() call with fetchGenerationRecordById(generationId) from the repository layer.
Quality assessment: Clean facade migration. The repository function (/Users/user_c042661f/Documents/reigh/src/integrations/supabase/repositories/generationRepository.ts) uses .maybeSingle() (returns null instead of error for no rows) and throws on actual errors. The calling code correctly:
Checks if (!row) for the not-found case
Assistant
This is a behavior change worth noting. Previously, if sourceSettings was falsy (no settings on the source shot), it would show a toast error "Source shot has no settings". Now normalizeVideoTravelSettings always returns a valid object (falling back to defaults if input is null/undefined), so it will silently apply default settings instead of showing an error. This is arguably correct -- applying defaults is reasonable -- but it's a subtle behavior change.
All change @/features/gallery/components/MediaGallery to @/shared/components/MediaGallery. Straightforward re-pathing as part of the module consolidation. The test mock path in JoinClipsResults.test.tsx is also updated, which is correct. No issues.
2. /src/tools/join-clips/lib/clipBootstrap.ts -- CORRECT, minor style note
Logic change: Extracts legacy-format normalization into a standalone normalizeLegacyJoinClipsSettings() function, then the main buildInitialClipsFromSettings function operates on the normalized canonical shape.
This is a clean refactor. The logic is equivalent to the original. One observation:
Line ~115 (new code): The indentation of the initialClips.push({ block has shifted left by 2 spaces compared to the surrounding if (clip.url). This appears to be a formatting inconsistency in the diff -- the initialClips.push is inside if (clip.url) but looks like it lost a level of indentation. Let me verify.
Assistant
The params field on GenerationRow is PersistedGenerationParams | undefined. The RawGenerationDbRow.params is Record<string, unknown> | null. The old code was gen.params as GenerationRow['params'] -- an unsafe cast. The new code gen.params ?? undefined converts null to undefined but still passes Record<string, unknown> where PersistedGenerationParams is expected. This is actually the same level of type safety (both rely on structural compatibility), but more explicit about the null-to-undefined conversion. Fine.
Now let me run the tests to see if everything passes.
Assistant
The test failures are in the worktree agent environment, not directly relevant to the diff. Let me re-run from the main working directory.
Assistant
There are sub-component and hook tests, but no integration-level test for the MediaGalleryItem component itself. The deleted test covered two key behaviors: (1) rendering the placeholder/skeleton branch when image ID is missing, and (2) rendering the full desktop draggable branch with content and create-shot modal. These are meaningful integration paths that are no longer covered.
Verdict: Test coverage regression. The deleted test was the only integration-level test for MediaGalleryItem. The existing sub-tests cover individual hooks and sub-components but not the top-level render branches.
Both files exist and contain direct Supabase client usage, so adding them to the facade allowlist is correct.
Verdict: Correct.
11. src/infrastructure/ and src/features/gallery/components/GenerationsPane/hooks/useGenerationsPaneController.test.ts
No uncommitted changes in either area (already committed on this branch).
Summary
Area
Verdict
Notes
MediaGallery.tsx (orchestrator)
Good
Clean, well-composed ~487 LOC component
useMediaGalleryLightboxControllers.ts
Good
Clean Supabase facade migration
useMediaGalleryLightboxControllers.test.ts
Good
Assistant
The failures are caused by a worktree resolution issue, not by the changes themselves. The tests that pass (2 passed, 10 tests total) are fine. Let me check if these tests pass when run without the worktree path confusion.
Assistant
The segmentDataTransforms.test.ts and projectSetupRepository.test.ts pass. The toolSettingsWriteService.test.ts failure is an environment/import issue unrelated to this diff. Let me verify.
Assistant
FLAG -- Indentation bug. Lines 72-79 have broken indentation. initialClips.push({ is at 6 spaces (same level as if), but the properties inside the object literal are inconsistently indented -- url, posterUrl, finalFrameUrl, durationSeconds at 10 spaces, loaded, playing at 8 spaces, and the opening initialClips.push at 6. This is inside the if (clip.url) block so it should be at 8+ spaces. The code will still work since JS doesn't care about whitespace, but it's messy and suggests a bad merge/edit.
Adds throw error after normalizeAndPresentError in three catch blocks (updateSegment, deleteSegment, deleteVideo). This is the correct pattern: present the error to the user, then re-throw so the caller can handle it (e.g., React Query can mark the mutation as failed). Previously, errors were silently swallowed after the toast.
Same pattern: adds throw error after normalizeAndPresentError in deleteBatch.
5. Test files for training-data-helper -- CORRECT
useTrainingData.test.ts: Adds mock for normalizeAndPresentError and a test that verifies updateSegment rethrows after presenting the error. The test correctly asserts both the throw and the mock call.
useTrainingDataBatches.test.ts: Same pattern for deleteBatch. Both tests are well-structured.
The big refactor: Extracts the massive useShotEditorController function body into three helper hooks:
useShotEditorBootstrap -- all hook calls and initialization
usePersistedShotEditorSettings -- tool settings and generations pane settings
useShotEditorScreenAssembly -- screen model + layout
Positive: This is a legitimate decomposition of a very large function. The type ShotEditorBootstrapResult makes the contract explicit.
Issues found:
(, line 425)
Assistant
This is a pre-existing issue (missing toolSettingsService module) unrelated to the current diff changes. The test logic itself is correct.
Here is my detailed assessment:
Assessment of Uncommitted Changes in shared/hooks, shared/lib, and shared/components
1. src/shared/lib/toolSettingsWriteService.ts -- API Signature Change
Change: Replaced overloaded positional args (signalOrMode?: AbortSignal | SettingsWriteMode, maybeMode?: SettingsWriteMode) with a single options object (options: UpdateToolSettingsOptions = {}).
Logic: Correct. Cleaner API, no ambiguity.
BUG FOUND -- Missed caller at /Users/user_c042661f/Documents/reigh/src/shared/settings/hooks/useDebouncedSettingsSave.ts line 205:
typescript
updateToolSettingsSupabase({
scope: flushScope,
id: pendingForEntity,
toolId: flushToolId,
patch: pending,
}, 'immediate') // <-- STILL USING OLD POSITIONAL API
This passes the string 'immediate' as the options parameter. Since isSettingsWriteMode(options.mode) will evaluate options.mode on a string (which is undefined), it silently falls back to 'debounced'. This is a correctness regression: settings flush on unmount/navigation will be debounced instead of immediate, potentially losing user changes.
Fix: Change to { mode: 'immediate' }.
Doc staleness: /Users/user_c042661f/Documents/reigh/docs/structure_detail/settings_system.md line 149 still shows the old 3-arg API: await updateToolSettingsSupabase({ scope, id, toolId, patch }, undefined, 'immediate');. Should be updated to { mode: 'immediate' }.
Tests: Updated correctly in both useToolSettings.test.ts and toolSettingsWriteService.test.ts.
Change: Added coerceRawGenerationDbRow / coerceRawGenerationDbRows functions that validate raw DB data at runtime instead of using unsafe as unknown as RawGenerationDbRow[] casts.
User
Review the following uncommitted changes for quality issues. Run each git diff command and read the full output:
git diff HEAD -- src/shared/hooks/useResources.ts — big deletion (-419 lines), check what was removed and if it's safe
git diff HEAD -- src/shared/hooks/projects/services/projectSetupRepository.ts — big deletion (-96 lines)
git diff HEAD -- src/shared/hooks/projects/services/projectSetupService.ts — big deletion (-81 lines)
git diff HEAD -- src/shared/hooks/projects/useProjectCRUD.ts
git diff HEAD -- src/shared/editMedia/navigation.ts
git diff HEAD -- src/features/resources/
git diff HEAD -- src/tools/edit-images/ src/tools/edit-video/
git diff HEAD -- eslint.shared-layer-allowlist.js
git diff HEAD -- structure.md
git diff HEAD -- src/shared/hooks/projects/services/projectSetupService.test.ts
Check if src/features/form-submission/hooks/useFormSubmission.test.ts exists and read it — it appears as a new file
For each change, evaluate:
Is the deletion safe? Are removed functions/exports still referenced anywhere? Use grep to check.
Any dead imports left behind?
Any broken patterns or missing error handling?
Are tests updated?
Report specific file paths, line numbers, and code snippets for any issues found.
Assistant
I'll run all the git diffs in parallel first.
Assistant
Now let me check whether the moved implementations exist at their new locations, and verify no dangling references remain.
Assistant
Let me check the allowlist entry for a path that may not exist, and verify the test file is importing from the right place.
Assistant
Now let me check if useProjectCRUD.ts is still importing from the old shared path or the new features path, and check the test is pointing at the right module.
Assistant
Now let me check the critical issue: the test file imports from ./projectSetupService (the shim), but the shim re-exports from the features path. The test mocks @/features/projects/services/projectSetupRepository. Let me verify the actual service at the features path imports from the features repository path.
Assistant
Let me check whether there's a second copy at src/shared/services/projects/ and look at the supabase allowlist more carefully.
Assistant
Good, useProjectCRUD is still at the shared path and the consumer imports it from there. Now let me check a potential issue with the eslint allowlist -- it adds useProjectCRUD.ts to the shared-layer allowlist but the file was already there before (just checking).
Assistant
Now let me check the new useResources.ts in features and verify it exports all the same types/hooks.
Assistant
Now let me check one more thing -- the useProjectCRUD.ts now imports directly from @/features/projects/services/projectSetupService while it's still in src/shared/. This means a shared-layer module imports from features, which is the direction that needs allowlisting. Let me verify it's in the allowlist.
Assistant
I now have a complete picture. Let me compile the findings.
The entire implementation was moved to /Users/user_c042661f/Documents/reigh/src/features/resources/hooks/useResources.ts. The old file is now a thin re-export shim. The 47 existing consumers all import from @/shared/hooks/useResources, which still works via the shim. Only 3 files (the two ResourceBrowser components and the shim itself) import directly from the new canonical path. No issues.
Implementation moved to /Users/user_c042661f/Documents/reigh/src/features/projects/services/projectSetupRepository.ts. Old file is a re-export shim. No consumers import from the old path anymore (grep confirmed 0 results). The shim is kept for safety but is currently unused.
Same pattern -- moved to /Users/user_c042661f/Documents/reigh/src/features/projects/services/projectSetupService.ts. No consumers import from the old path. The shim is unused.
4. src/shared/hooks/projects/useProjectCRUD.ts -- SAFE, minor note
Import updated from @/shared/hooks/projects/services/projectSetupService to @/features/projects/services/projectSetupService. This file is in the shared layer but now imports from features -- it's correctly allowlisted at line 121 of the eslint allowlist.
5. src/shared/editMedia/navigation.ts -- SAFE
Implementation moved to /Users/user_c042661f/Documents/reigh/src/domains/generation/navigation.ts. Old file is a re-export shim. Zero consumers still import from the old path (both edit-images and edit-video pages updated to import from the new location). The shim is currently unused.
6. src/features/resources/ -- SAFE
Two files updated to import Resource, StyleReferenceMetadata, StructureVideoMetadata directly from @/features/resources/hooks/useResources instead of via the shared shim. Clean change.
7. src/tools/edit-images/ and src/tools/edit-video/ -- SAFE
Both updated navigateToGenerationById import from @/shared/editMedia/navigation to @/domains/generation/navigation. Clean change.
8. eslint.shared-layer-allowlist.js -- ONE ISSUE FOUND
Dataset releases
Not yet included in a published release.
message
normalizedError?.message ?? "Internal server error"
CompletionError
CompletionError
message
The error field still logs the raw toErrorMessage(genErr) string, even for CompletionError. This means the structured log entry includes both error (stringified) and error_code/error_context (structured). Slight redundancy but not harmful — helps with plain-text log searching.
CompletionError is correctly forwarded with structured details (code, recoverable, context, metadata)
Plain Error still produces the generic "Internal server error" response
Assessment:
Coverage: Good. Both the happy path (structured error) and fallback (plain error) are tested. The assertions check the response body, logger calls, markTaskFailed arguments, and completeTaskErrorResponse arguments.
Minor observation: The mock for completeTaskErrorResponse was updated to pass through errorCode and options into the response JSON, which makes the assertions work. This is correct for test purposes.
One subtle thing: In the "wraps plain generation failures" test, the assertion checks recoverable: undefined in the response JSON. This is because completeTaskErrorResponse is called without the options parameter for plain errors, and the mock serializes undefined. In the real completeTaskErrorResponse, the default logic would apply (status >= 500 → true). The test is testing the mock interaction rather than the real behavior, which is appropriate for a unit test of handler.ts.
Change: For non-service-role callers, the function now:
Fetches the parent task's project_id
Adds .eq("project_id", parentProjectId) to the child tasks query
This scopes child task results to only those sharing the same project as the orchestrator task.
Assessment:
Correctness: The logic is correct. authorizeTaskActor already verified the user can access the orchestrator task, so fetching the parent task's project_id and filtering children by it is a sound authorization pattern.
Duplicate DB call: authorizeTaskActor likely already fetches the orchestrator task from the DB to verify access. The new code makes a second query for the same task to get project_id. This is a minor inefficiency. If authorizeTaskActor returned the task data (or at least project_id), this extra query could be avoided. Not a bug, but worth noting for a future cleanup.
Security improvement: Previously, a user-token caller could see child tasks from any project as long as they could access the orchestrator task. Now the child tasks are scoped to the same project. This is a meaningful authorization tightening.
Edge case — project_id is null on the parent task: The code handles this with !parentTask?.project_id check and returns a 500. This is correct since tasks should always have a project_id.
The logger.debug call on line 120 is why the test file needed the loggerDebugMock addition — consistent.
Change: Added loggerDebugMock to the mock logger so the new logger.debug(...) call in the implementation doesn't throw.
Assessment: Mechanical mock addition. Correct. No issues.
Summary
All changes are correct and well-structured. No bugs, security issues, or missed edge cases found. Key observations:
complete_task error handling: Clean enhancement. CompletionError provides structured error propagation without breaking existing behavior for plain errors. Test coverage is good.
get-orchestrator-children authorization: Meaningful security improvement scoping child tasks by project_id for user-token callers. One minor inefficiency: the parent task is queried twice (once in authorizeTaskActor, once for project_id). This could be consolidated in a future pass but is not a problem now.
rateLimit.ts: Trivial JSDoc fix. Correct.
Test coverage: Both changed edge functions have corresponding test updates. The CompletionError path has both positive and negative test cases.
No items flagged as requiring changes before merge.
GenerationRow
3. TaskDetailsPanelWrapper.tsx — Clean
All legacy props are removed from the interface. The VariantInfo local interface is deleted. The GenerationRow and DerivedItem type imports are removed. The component is now a tight 4-prop wrapper. No dead code, no missing imports.
4. VideoEditPanel.tsx — One issue found
Issue: Stale docstring (lines 7-9)
The file-level JSDoc still says:
code
Supports props-first pattern: optional state props (coreState, videoEditState,
variantsState) override context values when provided. This allows the component
to work both within VideoLightbox (using context) and standalone (using props).
The stateOverrides prop and the VideoEditPanelStateOverrides interface have been removed. The component now always reads from context. The docstring is misleading.
The unused type imports (LightboxCoreState, LightboxVariantState, VideoEditState) are correctly removed. The stateOverrides prop is removed from both the interface and destructuring. The ?? fallback pattern (stateOverrides?.coreState ?? contextCore) is replaced with direct context usage. Logic is correct.
Severity: Low. Stale comment only.
5. useTaskGeneration.ts — Clean
The extraction to createInpaintingTaskWorkflow is well-done:
All moved imports (uploadImageToStorage, createImageInpaintTask, createMaskedEditTask, buildMaskedEditTaskParams, convertToHiresFixApiParams, getMediaUrl) are removed from this file and present in the new file.
The createAnnotatedImageEditTask function is moved to the new file.
The TASK_CONFIGS entries correctly retain only the validation-related fields (emptyStrokesError, overlayNotReadyError, taskCreationError) while the task-creation-related fields (logPrefix, fileNamePrefix, createTask) move to the new file's own TASK_CONFIGS.
The actualGenerationId null check is preserved (moved outside the workflow function, checked before calling it).
The useCallback dependency array is unchanged and still correct.
6. createInpaintingTaskWorkflow.ts (new file) — Clean
Pure async function, no hooks, no side effects beyond the upload. Correctly receives StrokeOverlayHandle (not the ref) and calls exportMask. Properly re-creates the createAnnotatedImageEditTask wrapper. The TASK_CONFIGS here holds only what this file needs (fileNamePrefix, createTask). Clean separation.
7. useVideoLightboxRenderModel.tsx — Clean
shotId and onOpenExternalGeneration are removed from the destructuring of props (line 42-43 area). These were only used in the videoInfoPanelModel which no longer needs them.
selectedShotId is moved up (line 187) but is still used correctly at line 298 in the shotSelector model.
The primaryVariant variable is removed — it was only used for onSwitchToPrimary, which is removed.
The useMemo dependency array for videoInfoPanelModel is correctly trimmed to match the remaining values.
All removed lineage/derived props from the taskPanel object match the InfoPanelTaskPanelModel interface changes.
Summary of Issues
File
Issue
Severity
ImageLightboxControlsPanel.tsx
4 dead props in interface + 2 dead imports; caller still passes them silently
Medium
ImageLightbox.tsx (caller)
Passes 4 props that are now ignored
Medium (paired with above)
VideoEditPanel.tsx
Stale docstring references removed stateOverrides pattern
Low
All logic changes are correct. No broken patterns, no missing imports for actually-used code, no runtime issues. The two medium-severity items are dead code that should be cleaned up in this same change to avoid confusion.
Relies on the outer try/catch for error cases (the repository throws)
Removes the intermediate const row = data as Record<string, unknown> cast since the repository return type already includes Record<string, unknown>
Change: Updates test mocks from getSupabaseClient (with chained .from().select().eq().single()) to fetchGenerationRecordById. Simplifies the test significantly by removing 4 lines of chained mock setup.
Quality assessment: Good. The three test paths are preserved:
Successful fetch: mock returns the generation object directly (no wrapper { data, error })
Not found: mock returns null
Error: mock rejects with an error
All three paths correctly match the new repository API contract.
Change: Replaces the deprecated shim (re-exporting from @/features/gallery/) with a direct export from ./MediaGallery plus re-exports of DEFAULT_GALLERY_FILTERS and GalleryFilterState from @/shared/contracts/galleryFilters.
Verdict: Correct. The exports are consumed by multiple tools.
Change: Removes the import { DEFAULT_GALLERY_FILTERS } line. The export { DEFAULT_GALLERY_FILTERS } re-export on line 9 remains -- this works because it's a direct re-export (export { X } from 'source') which doesn't need a prior import.
Concern: This was the test file for the MediaGalleryItem component. I verified there are no references to this file anywhere in the codebase. However, this means MediaGalleryItem now has zero top-level component tests. The component itself still exists at /Users/user_c042661f/Documents/reigh/src/shared/components/MediaGalleryItem/. Unless the tests were relocated elsewhere (e.g., into the MediaGalleryItem/ directory), this is a test coverage regression.
Let me verify:
Simplified mocks, all paths covered
useMediaGalleryLightboxSession.test.ts
Good
Import consistency
useMediaGalleryViewInteractions.test.ts
Good
Import consistency
index.ts
Good
Correct barrel exports
types.ts
Good
Dead import removed
MediaGalleryItem.test.tsx (DELETED)
Flag
Integration test coverage lost for MediaGalleryItem top-level render branches (skeleton placeholder, desktop draggable). Sub-component tests exist but don't cover the same paths.
adding_new_tool.md
Good
Documentation improvements, path fix
eslint allowlist
Good
Both new entries point to real files
One actionable finding: The deletion of src/shared/components/MediaGalleryItem.test.tsx removes the only integration-level test for MediaGalleryItem. If this was intentional (e.g., the test was too brittle or the component is being refactored), it's worth noting. If not, the test should be relocated to src/shared/components/MediaGalleryItem/MediaGalleryItem.test.tsx to maintain coverage.
(a) useEffect dependency widened -- minor performance concern
Previously depended on setTurboMode (a stable function reference). Now depends on motionSettings (the whole memoized object), which re-creates whenever any motion setting changes (its useMemo depends on handlers which changes on every settings update). The effect body is guarded so it won't cause incorrect behavior, but it will fire unnecessarily.
(b) Unused import removed: type RefObject -- correct, no longer used.
(c) Unused import removed: type LoraModel in useApplySettingsHandler.ts -- correct.
(e) ShotEditorBootstrapResult type is verbose -- every field uses ReturnType<typeof useX>['fieldName'], which is correct but makes the interface ~40 lines long. This is a style choice, not a bug.
Replaces videoTravelSettings.defaults with createDefaultVideoTravelSettings() (returns a fresh clone each time, preventing shared-mutable-state bugs). Correct.
Uses normalizeVideoTravelSettings() to validate/coerce persisted data before applying.
Adds defensive spread for steerableMotionSettings with explicit typeof check.
Behavior change in applyShotSettings (line 190-194): Previously showed toast.error('Source shot has no settings') when source shot had no travel settings. Now normalizeVideoTravelSettings(undefined) returns defaults, which get silently applied. This means applying settings from a shot that never had settings configured will reset the target to defaults rather than showing an error. This could be confusing to users -- they click "copy settings from shot X" and their settings get wiped to defaults with no feedback. This is a minor regression in UX.
Wraps toolSettingsQuery.settings and projectSettingsQuery.settings through normalizeVideoTravelSettings(). The null-check guard (? normalizeVideoTravelSettings(...) : undefined) preserves the loading-state semantics.
createDefaultVideoTravelSettings() -- returns a fresh clone
Quality: This is solid defensive programming. Each normalizer validates types before use, filters invalid entries from arrays, and falls back to defaults. The normalizeStructureVideo correctly delegates to migrateLegacyStructureVideos when the canonical shape isn't found.
Note on asRecord duplication: The same asRecord helper appears in both settings.ts and legacyStructureVideo.ts. Not a bug, but worth noting.
(a) thumbUrl -> thumbnailUrl rename: Consistent rename in updateGenerationLocation and useUpdateGenerationLocation. The inner call to updateGenerationLocationInProject already used thumbnailUrl, so this eliminates a naming mismatch at the boundary.
(b) createGeneration now uses coerceGenerationRowDto: Instead of directly casting data as GenerationRowDto & { params?: Json | null }, it now goes through runtime validation via coerceGenerationRowDto. If the shape is invalid, it throws with a clear error message. This is strictly safer than the previous blind cast.
(c) Import cleanup: Removes direct GenerationRowDto type import since the coercion function handles typing internally. Correct.
Adds coerceGenerationRowDto (~60 lines) with helper functions. This function safely coerces an unknown value into a typed GenerationRowDto by:
Verifying it's a non-null, non-array object with a string id
Type-checking each optional field before including it
Using conditional spread to only include fields that pass validation
Quality: The spread-heavy approach (...(condition ? { field: value } : {})) is verbose but correct. The satisfies assertion at the end ensures type safety without runtime cost.
Wraps saveToken call in a try/catch. Previously, if saveToken threw (as opposed to returning { success: false }), the error would be unhandled. Now both failure modes are covered:
result.success === false -> show result.error
Exception thrown -> show error.message
Both paths correctly set state to 'error'. Good defensive fix.
Summary of Flags
Severity
File
Issue
Medium
src/tools/join-clips/lib/clipBootstrap.ts:72-79
Broken indentation in initialClips.push block. Code works but formatting is wrong.
useEffect dependency changed from stable setTurboMode to potentially-unstable motionSettings object. Won't cause bugs but may fire unnecessarily.
Informational
settings.ts + legacyStructureVideo.ts
asRecord helper function duplicated across files.
Everything else looks correct: import migrations are consistent, error re-throwing is properly tested, the coerceGenerationRowDto runtime validation is a clear safety improvement, the normalizeVideoTravelSettings normalizer is thorough and well-tested, and the HuggingFace token error handling fix is sound.
Logic: Correct. Each field is validated with appropriate type guards (asNullableString, asNullableNumber, asRecord). The conditional spread pattern (...(condition ? { field: value } : {})) correctly preserves optional fields -- only including them when the source data has them.
Minor concern: Lines 32-42 are verbose with repeated asNullableString(record.X) !== undefined checks. This is functionally correct but could be DRYer. Not a bug, just stylistic.
Behavior change in transformToGenerationRow: params: gen.params as GenerationRow['params'] changed to params: gen.params ?? undefined. This correctly converts null to undefined to match the GenerationRow.params?: PersistedGenerationParams type. Good fix.
Integration in segmentOutputsQueries.ts: Both fetchParentGenerations and fetchChildGenerations now route through coerceRawGenerationDbRows instead of raw casts. Correct.
Tests: New test case added for coerceRawGenerationDbRows validation. The test checks that a row missing id at index 1 throws 'Invalid generation row at index 1'. Covers the error path. The happy path is implicitly covered by existing tests that call transformToGenerationRow on the output.
Potential concern with coerceRawGenerationDbRows throwing: If Supabase ever returns a malformed row, this will throw and reject the React Query promise, which should surface as an error state. This is acceptable -- failing loudly on corrupt data is better than silently processing garbage.
Change: Two calls updated from 'immediate' positional arg to { mode: 'immediate' } options object.
Logic: Correct, consistent with the API change.
4. src/shared/hooks/projects/services/projectSetupRepository.ts -- Error Cause Chain
Change: throw new Error(message) changed to throw new Error(message, { cause: error }) in throwProjectSetupRepositoryError.
Logic: Correct. Preserves the original error for debugging while keeping the same user-facing message.
Tests: Updated to assert toMatchObject({ message, cause: rawError }) instead of just toThrow('delete failed'). The test now also specifies a realistic code: '23503' on the raw error. Good.
migrateLoraConfig now returns null for invalid entries (missing id/name/path) instead of returning objects with empty strings. Uses toString() and toNumber() helpers instead of unsafe casts.
migrateLoras filters out null entries.
New decodePhaseConfig / decodePhaseSettings / decodePhaseLoraConfig functions replace unsafe toRecord(x) as unknown as SegmentSettings['phaseConfig'] casts.
loras field in readShotSettings now pre-filters with toRecord before passing to migrateLoras.
New import of PhaseConfig, PhaseLoraConfig, PhaseSettings types from @/shared/types/phaseConfig.
Logic: All correct. The decodePhaseConfig function validates all required fields and returns undefined if any are missing. The mode field is correctly optional with 'i2v' | 'vace' validation. The stepsPerPhase uses toNumberArray which validates every element.
One subtlety: decodePhaseConfig returns undefined (not the input) if validation fails. In readShotSettings, phaseConfig: decodePhaseConfig(raw.phaseConfig) means invalid phase configs will silently become undefined, losing the user's (corrupted) data. This is the correct behavior -- better to fall back to defaults than to pass garbage to the video generation worker.
No test updates for settingsMigration: The phase config decoding and LoRA hardening have no dedicated test coverage in this diff. There are no existing settingsMigration.test.ts tests visible. Not blocking, but worth noting.
6. src/shared/lib/joinClips/defaults.ts -- Legacy Field Removal
Change: Removed startingVideoUrl, startingVideoPosterUrl, endingVideoUrl, endingVideoPosterUrl from defaults. Updated comment from "New multi-clip format" to "Canonical multi-clip format".
Logic: Correct cleanup. These were explicitly undefined placeholder fields.
Tests: The test that asserted these fields were undefined was removed. The remaining tests cover clips: [] and other defaults. Correct.
Change: import { MediaGallery, ... } from '@/features/gallery/components/MediaGallery' changed to from '@/shared/components/MediaGallery'.
Logic: Correct. Verified that DEFAULT_GALLERY_FILTERS and GalleryFilterState are both exported from src/shared/components/MediaGallery/index.ts.
8. src/shared/components/MediaGalleryItem/hooks/useMediaGalleryItemShotWorkflow.ts and useMediaGalleryItemTaskShare.ts -- Import Path Changes
Change: Both files change imports of GeneratedImageWithMetadata and SimplifiedShotOption from @/features/gallery/components/MediaGallery/types to @/shared/components/MediaGallery/types.
Logic: Correct. Both types are confirmed exported from the new path.
Concern: This was the only integration test for the MediaGalleryItem component itself. Sub-component/hook tests exist (ItemMetadataBar.test.tsx, ItemShotBadges.test.tsx, useImageLoading.test.ts, etc.) but they don't cover the top-level rendering logic (placeholder skeleton branch, draggable branch, prefetch-on-hover). This is test coverage loss.
Summary of Issues
Must fix (regression bug):
/Users/user_c042661f/Documents/reigh/src/shared/settings/hooks/useDebouncedSettingsSave.ts line 205: Still uses old positional 'immediate' arg. Settings flushes on unmount will silently fall back to debounced mode.
Should fix (doc staleness):
2. /Users/user_c042661f/Documents/reigh/docs/structure_detail/settings_system.md line 149: Shows old 3-arg API example.
Worth noting (coverage loss):
3. Deleted src/shared/components/MediaGalleryItem.test.tsx removes top-level component integration test with no replacement.
4. No test coverage for the new decodePhaseConfig / hardened migrateLoraConfig logic in settingsMigration.ts.
Issue: Phantom allowlist entries. Two entries were added at the bottom:
These files exist at that path and are re-export shims, but they don't actually import from @/features/ or @/domains/ -- they re-export from @/features/projects/services/*. So they may legitimately need allowlisting if the eslint rule flags shared->features re-exports. However, they are duplicates of concept with the other allowlist entries at lines 119-120 (src/shared/hooks/projects/services/projectSetupRepository.ts and projectSetupService.ts). The codebase has two shim locations for the same module:
src/shared/hooks/projects/services/ (the original location)
src/shared/services/projects/ (a second shim location)
This is redundant -- there are two shim paths for the same canonical module. Both are unused (no consumers import from either old path). This isn't a bug, but it's unnecessary duplication.
9. structure.md -- SAFE
Added resources, projects to the features slice description and expanded the guidance about domain-backed helpers. Accurate documentation update.
10. projectSetupService.test.ts -- SAFE
The test mocks @/features/projects/services/projectSetupRepository (line 22), which matches the import path used by the canonical projectSetupService.ts at the features path. The test imports from ./projectSetupService (the shim), which re-exports from the features path. The mock intercepts the repository dependency correctly. Test should pass.
11. useFormSubmission.test.ts -- DOES NOT EXIST
The src/features/form-submission/ directory does not exist at all.
Issues Found
Issue 1 (low): Redundant shim paths. Two sets of compatibility shims exist for the project setup modules:
Neither set has any consumers (all imports have been updated). Both sets are now dead code shims. The second set (shared/services/projects/) appears to be a pre-existing shim that was not cleaned up. Consider removing all four shim files, or at minimum removing the shared/services/projects/ set which appears to have no historical consumers either.
Issue 2 (low): Unused shim for navigation./Users/user_c042661f/Documents/reigh/src/shared/editMedia/navigation.ts is a shim with zero consumers. Could be removed. It is correctly allowlisted.
Issue 3 (info): 47 consumers still use the old @/shared/hooks/useResources path. This is the only shim with active consumers, so it must stay. The other shims (projectSetup, navigation) have zero consumers and could be deleted if the goal is cleanup.
No broken imports, no dead imports in changed files, no missing error handling, and tests are correctly updated.