diff --git a/apps/premiere-uxp/shumai-premiere.ccx b/apps/premiere-uxp/shumai-premiere.ccx index 7c30ffb2..498bdc6c 100644 Binary files a/apps/premiere-uxp/shumai-premiere.ccx and b/apps/premiere-uxp/shumai-premiere.ccx differ diff --git a/apps/premiere-uxp/src/App.tsx b/apps/premiere-uxp/src/App.tsx index bac0c910..b86142ba 100644 --- a/apps/premiere-uxp/src/App.tsx +++ b/apps/premiere-uxp/src/App.tsx @@ -102,12 +102,7 @@ export const App: React.FC = () => { )} {view !== 'auth' && mainTab === 'sequences' && ( - setMainTab('browse')} - onLinkCountChange={setLinkedCount} - /> + )} {view !== 'auth' && mainTab === 'browse' && view === 'projects' && ( diff --git a/apps/premiere-uxp/src/components/FileItem.test.tsx b/apps/premiere-uxp/src/components/FileItem.test.tsx index ad15b6f7..a1d30d02 100644 --- a/apps/premiere-uxp/src/components/FileItem.test.tsx +++ b/apps/premiere-uxp/src/components/FileItem.test.tsx @@ -299,6 +299,46 @@ describe('FileItem and FileCardItem UI Components', () => { expect(screen.getByText(/v2 •/)).toBeTruthy() }) + + it('FileCardItem renders createdAt time when provided', () => { + const assetWithDates: AssetSummary = { + id: 'date-1', + name: 'render.mp4', + type: 'file', + createdAt: new Date(Date.now() - 3600 * 1000).toISOString(), + updatedAt: new Date(Date.now() - 60 * 1000).toISOString(), + } + + render() + expect(screen.getByText('1h ago')).toBeTruthy() + expect(screen.queryByText('1m ago')).toBeNull() + }) + + it('FileCardItem falls back to updatedAt if createdAt is absent', () => { + const assetWithUpdatedOnly: AssetSummary = { + id: 'date-2', + name: 'render2.mp4', + type: 'file', + updatedAt: new Date(Date.now() - 60 * 1000).toISOString(), + } + + render() + expect(screen.getByText('1m ago')).toBeTruthy() + }) + + it('FileItem renders createdAt time in subtext when provided', () => { + const assetWithDates: AssetSummary = { + id: 'date-3', + name: 'render3.mp4', + type: 'file', + createdAt: new Date(Date.now() - 3600 * 1000).toISOString(), + updatedAt: new Date(Date.now() - 60 * 1000).toISOString(), + } + + render() + expect(screen.getByText(/1h ago/)).toBeTruthy() + expect(screen.queryByText(/1m ago/)).toBeNull() + }) }) describe('getAssetVersionLabel', () => { diff --git a/apps/premiere-uxp/src/components/FileItem.tsx b/apps/premiere-uxp/src/components/FileItem.tsx index a4387bb8..d2a00680 100644 --- a/apps/premiere-uxp/src/components/FileItem.tsx +++ b/apps/premiere-uxp/src/components/FileItem.tsx @@ -130,7 +130,7 @@ export const FileItem: React.FC = ({ const isFolder = category === 'folder' const versionLabel = getAssetVersionLabel(asset) const effectiveSize = asset.sizeByte ?? asset.size - const updatedText = formatDateAgo(asset.updatedAt) + const timeText = formatDateAgo(asset.createdAt || asset.updatedAt) const thumbUrl = resolveAssetUrl(asset.preview?.thumbnailUrl, endpoint) const iconFallback = ( @@ -209,7 +209,7 @@ export const FileItem: React.FC = ({ {versionLabel ? `${versionLabel} • ` : ''} {isFolder ? 'Folder' : formatBytes(effectiveSize)} - {updatedText ? ` • ${updatedText}` : ''} + {timeText ? ` • ${timeText}` : ''} @@ -305,7 +305,7 @@ export const FileCardItem: React.FC = ({ const category = getFileTypeCategory(asset) const isFolder = category === 'folder' const effectiveSize = asset.sizeByte ?? asset.size - const updatedText = formatDateAgo(asset.updatedAt) + const timeText = formatDateAgo(asset.createdAt || asset.updatedAt) const thumbUrl = resolveAssetUrl(asset.preview?.thumbnailUrl, endpoint) const duration = asset.preview?.duration ?? asset.media?.metadata?.duration const durationText = formatDuration(duration) @@ -407,11 +407,11 @@ export const FileCardItem: React.FC = ({ - {(creatorName || updatedText) && ( + {(creatorName || timeText) && (
{creatorName && {creatorName}} - {creatorName && updatedText && •} - {updatedText && {updatedText}} + {creatorName && timeText && •} + {timeText && {timeText}}
)} diff --git a/apps/premiere-uxp/src/components/LinkSequenceDialog.test.tsx b/apps/premiere-uxp/src/components/LinkSequenceDialog.test.tsx index 9332d73b..639fa5b3 100644 --- a/apps/premiere-uxp/src/components/LinkSequenceDialog.test.tsx +++ b/apps/premiere-uxp/src/components/LinkSequenceDialog.test.tsx @@ -82,7 +82,7 @@ describe('LinkSequenceDialog Component', () => { expect(screen.getByText(/no active premiere pro project found/i)).toBeDefined() }) - it('lists project sequences and highlights active sequence', async () => { + it('lists project sequences and highlights active sequence without sequence icon', async () => { const mockSeq1 = { guid: 'seq-1', name: 'Rough Cut' } const mockSeq2 = { guid: 'seq-2', name: 'Fine Cut' } const mockProject = { guid: 'proj-1' } @@ -99,8 +99,9 @@ describe('LinkSequenceDialog Component', () => { ) vi.spyOn(linkStorage, 'getAllLinkedSequences').mockResolvedValue([]) + let renderedContainer: HTMLElement = null! await act(async () => { - render( + const { container } = render( { onLinkSuccess={mockOnLinkSuccess} />, ) + renderedContainer = container }) expect(screen.getByText('Rough Cut')).toBeDefined() expect(screen.getByText('Fine Cut')).toBeDefined() expect(screen.getByText('Active')).toBeDefined() + expect(renderedContainer.querySelectorAll('.shumai-option-card sp-icon-filmstrip').length).toBe( + 0, + ) }) it('executes sync and invokes onLinkSuccess on confirmation', async () => { @@ -173,7 +178,16 @@ describe('LinkSequenceDialog Component', () => { 'test-key', 'asset-vid-1', ) - expect(markersService.syncCommentsToSequence).toHaveBeenCalled() + expect(markersService.syncCommentsToSequence).toHaveBeenCalledWith( + mockProject, + mockSeq1, + expect.any(Array), + expect.objectContaining({ + endpoint: 'https://api.shumai.test', + sequenceGuid: 'seq-1', + assetId: 'asset-vid-1', + }), + ) expect(mockOnLinkSuccess).toHaveBeenCalledWith(mockUpdatedLink, 1) expect(mockOnClose).toHaveBeenCalled() }) diff --git a/apps/premiere-uxp/src/components/LinkSequenceDialog.tsx b/apps/premiere-uxp/src/components/LinkSequenceDialog.tsx index 1e985ac7..31726e69 100644 --- a/apps/premiere-uxp/src/components/LinkSequenceDialog.tsx +++ b/apps/premiere-uxp/src/components/LinkSequenceDialog.tsx @@ -5,7 +5,7 @@ import type { LinkedSequenceAsset } from '../types/link' import { getActiveProject, getAllSequences, getActiveSequence } from '../services/premiere' import { getAllLinkedSequences, normalizeGuid, removeSequenceLink } from '../services/linkStorage' import { fetchAssetComments, syncCommentsToSequence } from '../services/markers' -import { resolveAssetUrl } from '../utils/url' +import { resolveAssetUrl, isSameEndpoint } from '../utils/url' import { formatBytes, formatDuration } from '../utils/format' import { ProgressCircle } from '@swc-react/progress-circle' @@ -91,7 +91,9 @@ export const LinkSequenceDialog: React.FC = ({ const activeGuid = normalizeGuid(activeSeq?.guid) const linksMap = new Map() for (const link of existingLinks) { - linksMap.set(normalizeGuid(link.sequenceGuid), link) + if (!link.endpoint || isSameEndpoint(link.endpoint, endpoint)) { + linksMap.set(normalizeGuid(link.sequenceGuid), link) + } } const options: SequenceOption[] = allSeqs.map((seq) => { @@ -129,7 +131,7 @@ export const LinkSequenceDialog: React.FC = ({ return () => { isMounted = false } - }, [isOpen, asset]) + }, [isOpen, asset, endpoint]) // Escape key handler useEffect(() => { @@ -170,6 +172,7 @@ export const LinkSequenceDialog: React.FC = ({ assetId: asset.id, assetName: asset.name, assetThumbnailUrl: asset.preview?.thumbnailUrl, + endpoint: endpoint.trim().replace(/\/+$/, ''), projectId: prGuidStr, syncedCommentIds: targetOption.currentLink?.assetId === asset.id @@ -312,11 +315,6 @@ export const LinkSequenceDialog: React.FC = ({ }} >
-
{opt.name} diff --git a/apps/premiere-uxp/src/services/autoSyncService.test.ts b/apps/premiere-uxp/src/services/autoSyncService.test.ts index 3759a376..eb55763b 100644 --- a/apps/premiere-uxp/src/services/autoSyncService.test.ts +++ b/apps/premiere-uxp/src/services/autoSyncService.test.ts @@ -105,6 +105,73 @@ describe('autoSyncService', () => { ) }) + it('skips linked sequences configured for a different server endpoint', async () => { + const mockSeq1 = { guid: 'seq-foreign', name: 'Seq Foreign' } + const mockSeq2 = { guid: 'seq-local', name: 'Seq Local' } + const mockProject = { guid: 'proj-1' } + + const foreignLink = { + sequenceGuid: 'seq-foreign', + sequenceName: 'Seq Foreign', + assetId: 'asset-foreign', + assetName: 'foreign.mp4', + endpoint: 'http://localhost:3000', + syncedCommentIds: [], + lastSyncAt: 0, + totalCommentsSynced: 0, + } + + const sameLink = { + sequenceGuid: 'seq-local', + sequenceName: 'Seq Local', + assetId: 'asset-local', + assetName: 'local.mp4', + endpoint: 'https://staging.shumai.one/', // trailing slash variation + syncedCommentIds: [], + lastSyncAt: 0, + totalCommentsSynced: 0, + } + + vi.spyOn(premiereService, 'getActiveProject').mockResolvedValue( + mockProject as unknown as Project, + ) + vi.spyOn(premiereService, 'getAllSequences').mockResolvedValue([ + mockSeq1 as unknown as Sequence, + mockSeq2 as unknown as Sequence, + ]) + vi.spyOn(linkStorage, 'getAllLinkedSequences').mockResolvedValue([foreignLink, sameLink]) + vi.spyOn(markersService, 'fetchAssetComments').mockResolvedValue([ + { id: 'comm-1', second: 2, message: 'comment' } as unknown as CommentInfo, + ]) + vi.spyOn(markersService, 'syncCommentsToSequence').mockResolvedValue({ + updatedLink: { ...sameLink, syncedCommentIds: ['comm-1'] }, + addedCount: 1, + }) + + autoSyncService.start('https://staging.shumai.one', 'test-key') + await autoSyncService.triggerImmediateSync() + + // Foreign link should be skipped + expect(markersService.fetchAssetComments).not.toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + 'asset-foreign', + ) + + // Matching link should be synced + expect(markersService.fetchAssetComments).toHaveBeenCalledWith( + 'https://staging.shumai.one', + 'test-key', + 'asset-local', + ) + expect(markersService.syncCommentsToSequence).toHaveBeenCalledWith( + mockProject, + mockSeq2, + expect.any(Array), + sameLink, + ) + }) + it('aborts syncing when stop() is called and credentials are reset', async () => { const fetchSpy = vi.spyOn(markersService, 'fetchAssetComments') autoSyncService.start('https://api.shumai.test', 'test-key') diff --git a/apps/premiere-uxp/src/services/autoSyncService.ts b/apps/premiere-uxp/src/services/autoSyncService.ts index bbcb4e01..860b06e9 100644 --- a/apps/premiere-uxp/src/services/autoSyncService.ts +++ b/apps/premiere-uxp/src/services/autoSyncService.ts @@ -2,6 +2,7 @@ import type { Sequence } from '@adobe/premierepro' import { getActiveProject, getAllSequences, getPremiereModule } from './premiere' import { getAllLinkedSequences, normalizeGuid } from './linkStorage' import { fetchAssetComments, syncCommentsToSequence } from './markers' +import { isSameEndpoint } from '../utils/url' const SYNC_INTERVAL_MS = 12000 // 12 seconds @@ -144,6 +145,11 @@ class AutoSyncService { for (const link of linkedItems) { if (this.endpoint !== currentEndpoint || this.apiKey !== currentApiKey) break + // Skip links created against a different server endpoint + if (link.endpoint && !isSameEndpoint(link.endpoint, currentEndpoint)) { + continue + } + const targetSeq = seqsMap.get(normalizeGuid(link.sequenceGuid)) if (!targetSeq) continue diff --git a/apps/premiere-uxp/src/services/commentUtils.test.ts b/apps/premiere-uxp/src/services/commentUtils.test.ts new file mode 100644 index 00000000..a3595e39 --- /dev/null +++ b/apps/premiere-uxp/src/services/commentUtils.test.ts @@ -0,0 +1,124 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { fetchAssetComments, formatCommentBody } from './commentUtils' +import * as clientModule from '../api/client' +import type { CommentInfo } from '@shumai/dtos' + +describe('commentUtils', () => { + beforeEach(() => { + vi.restoreAllMocks() + }) + + describe('fetchAssetComments', () => { + it('returns comments array when response is ok', async () => { + const mockComments: Partial[] = [ + { id: 'c1', message: 'First comment', second: 12 }, + { id: 'c2', message: 'Second comment', second: 45 }, + ] + + const mockGet = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ data: mockComments }), + }) + + vi.spyOn(clientModule, 'getShumaiClient').mockReturnValue({ + api: { + files: { + ':fileId': { + comments: { + $get: mockGet, + }, + }, + }, + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + const result = await fetchAssetComments('https://api.shumai.test', 'test-key', 'asset-1') + + expect(mockGet).toHaveBeenCalledWith({ + param: { fileId: 'asset-1' }, + query: { first: '100' }, + }) + expect(result).toEqual(mockComments) + }) + + it('throws error with message from server response when res.ok is false', async () => { + const mockGet = vi.fn().mockResolvedValue({ + ok: false, + status: 404, + json: async () => ({ error: 'Asset not found on this server' }), + }) + + vi.spyOn(clientModule, 'getShumaiClient').mockReturnValue({ + api: { + files: { + ':fileId': { + comments: { + $get: mockGet, + }, + }, + }, + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + await expect( + fetchAssetComments('https://api.shumai.test', 'test-key', 'asset-missing'), + ).rejects.toThrow('Asset not found on this server') + }) + + it('throws fallback HTTP status error when res.ok is false and response has no error field', async () => { + const mockGet = vi.fn().mockResolvedValue({ + ok: false, + status: 500, + json: async () => { + throw new Error('Invalid JSON') + }, + }) + + vi.spyOn(clientModule, 'getShumaiClient').mockReturnValue({ + api: { + files: { + ':fileId': { + comments: { + $get: mockGet, + }, + }, + }, + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any) + + await expect( + fetchAssetComments('https://api.shumai.test', 'test-key', 'asset-crash'), + ).rejects.toThrow('Failed to fetch comments (HTTP 500)') + }) + }) + + describe('formatCommentBody', () => { + it('formats single comment without replies', () => { + const comment = { + message: 'Review cut at 01:23', + replies: [], + } as unknown as CommentInfo + + expect(formatCommentBody(comment)).toBe('Review cut at 01:23') + }) + + it('formats comment with nested replies and authors', () => { + const comment = { + message: 'Needs color correction', + replies: [ + { creator: { name: 'Alice' }, message: 'Applied LUT' }, + { creator: { name: 'Bob' }, message: 'Looks better' }, + ], + } as unknown as CommentInfo + + const result = formatCommentBody(comment) + expect(result).toContain('Needs color correction') + expect(result).toContain('--- Replies ---') + expect(result).toContain('Alice: Applied LUT') + expect(result).toContain('Bob: Looks better') + }) + }) +}) diff --git a/apps/premiere-uxp/src/services/commentUtils.ts b/apps/premiere-uxp/src/services/commentUtils.ts index 28c2fcb2..c22df48b 100644 --- a/apps/premiere-uxp/src/services/commentUtils.ts +++ b/apps/premiere-uxp/src/services/commentUtils.ts @@ -9,22 +9,19 @@ export async function fetchAssetComments( apiKey: string, assetId: string, ): Promise { - try { - const client = getShumaiClient(endpoint, apiKey) - const res = await client.api.files[':fileId'].comments.$get({ - param: { fileId: assetId }, - query: { first: '100' }, - }) - if (!res.ok) { - console.warn('[commentUtils] Failed to fetch comments for asset:', res.status) - return [] - } - const data = await res.json() - return (data?.data as CommentInfo[]) || [] - } catch (err) { - console.error('[commentUtils] Error fetching asset comments:', err) - return [] + const client = getShumaiClient(endpoint, apiKey) + const res = await client.api.files[':fileId'].comments.$get({ + param: { fileId: assetId }, + query: { first: '100' }, + }) + + if (!res.ok) { + const errData = (await res.json().catch(() => ({}))) as { error?: string } + throw new Error(errData.error || `Failed to fetch comments (HTTP ${res.status})`) } + + const data = await res.json() + return (data?.data as CommentInfo[]) || [] } /** diff --git a/apps/premiere-uxp/src/services/linkStorage.test.ts b/apps/premiere-uxp/src/services/linkStorage.test.ts index 8b45f053..998ebcd7 100644 --- a/apps/premiere-uxp/src/services/linkStorage.test.ts +++ b/apps/premiere-uxp/src/services/linkStorage.test.ts @@ -69,6 +69,16 @@ describe('linkStorage service', () => { expect(result).toEqual(sampleLink) }) + it('saves and retrieves link with endpoint from cache', () => { + const linkWithEndpoint: LinkedSequenceAsset = { + ...sampleLink, + endpoint: 'https://staging.shumai.one', + } + saveSequenceLinkToCache(linkWithEndpoint, 'proj-1') + const result = getSequenceLinkFromCache('seq-guid-1', 'proj-1') + expect(result?.endpoint).toBe('https://staging.shumai.one') + }) + it('returns null when link is not in cache', () => { expect(getSequenceLinkFromCache('unknown-seq', 'proj-1')).toBeNull() }) @@ -452,6 +462,35 @@ describe('linkStorage service', () => { expect(success).toBe(true) expect(txCount).toBeGreaterThanOrEqual(2) }) + + it('skips fallback comment fetch if link endpoint does not match current session endpoint', async () => { + localStorage.setItem('shumai_uxp_endpoint', 'https://staging.shumai.one') + localStorage.setItem('shumai_uxp_api_key', 'test-key') + + const fetchCommentsSpy = vi.spyOn(commentUtils, 'fetchAssetComments') + + const mockSeq = { + guid: 'seq-diff-endpoint', + name: 'Diff Endpoint Seq', + } + const mockProj = { + guid: 'proj-diff', + lockedAccess: (fn: () => void) => fn(), + executeTransaction: () => true, + } + + const linkFromLocal: LinkedSequenceAsset = { + ...sampleLink, + sequenceGuid: 'seq-diff-endpoint', + endpoint: 'http://localhost:3000', + syncedMarkerGuids: [], // Trigger fallback + } + + saveSequenceLinkToCache(linkFromLocal, 'proj-diff') + + await removeSequenceLink(mockProj as unknown as Project, mockSeq as unknown as Sequence) + expect(fetchCommentsSpy).not.toHaveBeenCalled() + }) }) describe('getAllLinkedSequences', () => { diff --git a/apps/premiere-uxp/src/services/linkStorage.ts b/apps/premiere-uxp/src/services/linkStorage.ts index 45fdee5f..2ae9037f 100644 --- a/apps/premiere-uxp/src/services/linkStorage.ts +++ b/apps/premiere-uxp/src/services/linkStorage.ts @@ -3,6 +3,7 @@ import { getPremiereModule } from './premiere' import type { LinkedSequenceAsset } from '../types/link' import { getStoredCredentials } from './storage' import { fetchAssetComments, formatCommentBody } from './commentUtils' +import { isSameEndpoint } from '../utils/url' export const LINK_STORAGE_PROP_KEY = 'shumai_linked_asset' const STORAGE_PREFIX = '@shumai/premiere-uxp:project-links' @@ -372,7 +373,11 @@ export async function removeSequenceLink(project: Project, sequence: Sequence): ) try { const creds = getStoredCredentials() - if (creds?.endpoint && creds?.apiKey) { + const canFetchComments = + creds?.endpoint && + creds?.apiKey && + (!linkData.endpoint || isSameEndpoint(linkData.endpoint, creds.endpoint)) + if (canFetchComments) { const comments = await fetchAssetComments( creds.endpoint, creds.apiKey, diff --git a/apps/premiere-uxp/src/types/link.ts b/apps/premiere-uxp/src/types/link.ts index 3c73399b..97471a54 100644 --- a/apps/premiere-uxp/src/types/link.ts +++ b/apps/premiere-uxp/src/types/link.ts @@ -4,6 +4,7 @@ export interface LinkedSequenceAsset { assetId: string assetName: string assetThumbnailUrl?: string + endpoint?: string projectId?: string syncedCommentIds: string[] syncedMarkerGuids?: string[] diff --git a/apps/premiere-uxp/src/utils/url.test.ts b/apps/premiere-uxp/src/utils/url.test.ts index 08a66219..61ca4005 100644 --- a/apps/premiere-uxp/src/utils/url.test.ts +++ b/apps/premiere-uxp/src/utils/url.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { resolveAssetUrl } from './url' +import { resolveAssetUrl, normalizeEndpoint, isSameEndpoint } from './url' describe('resolveAssetUrl', () => { it('returns undefined for empty or null inputs', () => { @@ -43,3 +43,30 @@ describe('resolveAssetUrl', () => { expect(resolveAssetUrl(r2Url, endpoint)).toBe(r2Url) }) }) + +describe('normalizeEndpoint', () => { + it('handles empty and null values', () => { + expect(normalizeEndpoint('')).toBe('') + expect(normalizeEndpoint(null)).toBe('') + expect(normalizeEndpoint(undefined)).toBe('') + }) + + it('trims whitespace and trailing slashes and converts to lower case', () => { + expect(normalizeEndpoint(' https://STAGING.shumai.one/// ')).toBe('https://staging.shumai.one') + expect(normalizeEndpoint('http://localhost:3000/')).toBe('http://localhost:3000') + }) +}) + +describe('isSameEndpoint', () => { + it('returns true when endpoints match ignoring slashes and casing', () => { + expect(isSameEndpoint('https://staging.shumai.one/', 'https://STAGING.shumai.one')).toBe(true) + expect(isSameEndpoint('http://localhost:3000', 'http://localhost:3000/')).toBe(true) + }) + + it('returns false when endpoints differ', () => { + expect(isSameEndpoint('http://localhost:3000', 'https://staging.shumai.one')).toBe(false) + expect(isSameEndpoint('http://localhost:3000', 'http://127.0.0.1:3000')).toBe(false) + expect(isSameEndpoint('', 'http://localhost:3000')).toBe(false) + expect(isSameEndpoint(null, undefined)).toBe(false) + }) +}) diff --git a/apps/premiere-uxp/src/utils/url.ts b/apps/premiere-uxp/src/utils/url.ts index 7dcf655e..09cec8e1 100644 --- a/apps/premiere-uxp/src/utils/url.ts +++ b/apps/premiere-uxp/src/utils/url.ts @@ -23,3 +23,21 @@ export function resolveAssetUrl(url?: string | null, endpoint?: string): string return url } + +/** + * Normalizes an endpoint URL by trimming whitespace, stripping trailing slashes, + * and converting to lower case for reliable comparison. + */ +export function normalizeEndpoint(endpoint?: string | null): string { + if (!endpoint) return '' + return endpoint.trim().replace(/\/+$/, '').toLowerCase() +} + +/** + * Checks if two endpoints refer to the same server URL. + */ +export function isSameEndpoint(ep1?: string | null, ep2?: string | null): boolean { + const n1 = normalizeEndpoint(ep1) + const n2 = normalizeEndpoint(ep2) + return Boolean(n1 && n2 && n1 === n2) +} diff --git a/apps/premiere-uxp/src/views/FileListView.tsx b/apps/premiere-uxp/src/views/FileListView.tsx index fec60ef1..b2856a73 100644 --- a/apps/premiere-uxp/src/views/FileListView.tsx +++ b/apps/premiere-uxp/src/views/FileListView.tsx @@ -15,6 +15,7 @@ import { getActiveProject, getAllSequences } from '../services/premiere' import type { LinkedSequenceAsset } from '../types/link' import { importAssetIntoPremiere, type ProxyOption } from '../services/import' import { ProjectSummary } from './ProjectsView' +import { isSameEndpoint } from '../utils/url' import { ActionButton } from '@swc-react/action-button' import { Button } from '@swc-react/button' import { Search } from '@swc-react/search' @@ -75,10 +76,12 @@ export const FileListView: React.FC = ({ if (cachedLinks.length > 0) { const map: Record = {} for (const link of cachedLinks) { - map[link.assetId] = link + if (!link.endpoint || isSameEndpoint(link.endpoint, endpoint)) { + map[link.assetId] = link + } } setLinkedAssetsMap((prev) => ({ ...prev, ...map })) - onLinkCountChange?.(cachedLinks.length) + onLinkCountChange?.(Object.keys(map).length) } // 2. Query active project in Premiere Pro for live persistent links @@ -88,15 +91,17 @@ export const FileListView: React.FC = ({ const liveLinks = await getAllLinkedSequences(pr) const liveMap: Record = {} for (const link of liveLinks) { - liveMap[link.assetId] = link + if (!link.endpoint || isSameEndpoint(link.endpoint, endpoint)) { + liveMap[link.assetId] = link + } } setLinkedAssetsMap(liveMap) - onLinkCountChange?.(liveLinks.length) + onLinkCountChange?.(Object.keys(liveMap).length) } } catch (err) { console.warn('[FileListView] Could not get linked sequences from active project:', err) } - }, [onLinkCountChange]) + }, [endpoint, onLinkCountChange]) useEffect(() => { void refreshLinkedAssets() diff --git a/apps/premiere-uxp/src/views/SequencesView.test.tsx b/apps/premiere-uxp/src/views/SequencesView.test.tsx index c64c7b44..d7d901b6 100644 --- a/apps/premiere-uxp/src/views/SequencesView.test.tsx +++ b/apps/premiere-uxp/src/views/SequencesView.test.tsx @@ -6,12 +6,13 @@ import { SequencesView } from './SequencesView' import type { Project, Sequence } from '@adobe/premierepro' import * as premiereService from '../services/premiere' import * as linkStorage from '../services/linkStorage' +import * as markersService from '../services/markers' +import type { CommentInfo } from '@shumai/dtos' // Configure React 19 act environment for happy-dom ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true describe('SequencesView Component', () => { - const mockSwitchToBrowse = vi.fn() const mockOnLinkCountChange = vi.fn() beforeEach(() => { @@ -38,7 +39,6 @@ describe('SequencesView Component', () => { , ) @@ -46,7 +46,7 @@ describe('SequencesView Component', () => { expect(screen.getByText('No Linked Sequences')).toBeDefined() expect(screen.getByText(/Sequence 01/i)).toBeDefined() - expect(screen.queryByText(/Browse Assets to Link/i)).toBeNull() + expect(screen.queryByText('Browse Assets to Link')).toBeNull() }) it('renders linked sequence card and handles unlink', async () => { @@ -75,7 +75,6 @@ describe('SequencesView Component', () => { , ) @@ -93,4 +92,162 @@ describe('SequencesView Component', () => { expect(linkStorage.removeSequenceLink).toHaveBeenCalledWith(mockProject, mockSeq) }) + + it('filters out foreign endpoint links from the view and link count', async () => { + const mockSeq1 = { guid: 'seq-1', name: 'Sequence Foreign' } + const mockSeq2 = { guid: 'seq-2', name: 'Sequence Staging' } + const mockProject = { guid: 'proj-1' } + const foreignLink = { + sequenceGuid: 'seq-1', + sequenceName: 'Sequence Foreign', + assetId: 'asset-dev', + assetName: 'dev_asset.mp4', + endpoint: 'http://localhost:3000', + syncedCommentIds: [], + lastSyncAt: Date.now(), + totalCommentsSynced: 0, + } + const stagingLink = { + sequenceGuid: 'seq-2', + sequenceName: 'Sequence Staging', + assetId: 'asset-staging', + assetName: 'staging_asset.mp4', + endpoint: 'https://staging.shumai.one', + syncedCommentIds: [], + lastSyncAt: Date.now(), + totalCommentsSynced: 0, + } + + vi.spyOn(premiereService, 'getActiveProject').mockResolvedValue( + mockProject as unknown as Project, + ) + vi.spyOn(premiereService, 'getActiveSequence').mockResolvedValue( + mockSeq1 as unknown as Sequence, + ) + vi.spyOn(premiereService, 'getAllSequences').mockResolvedValue([ + mockSeq1 as unknown as Sequence, + mockSeq2 as unknown as Sequence, + ]) + vi.spyOn(linkStorage, 'getAllLinkedSequences').mockResolvedValue([foreignLink, stagingLink]) + + await act(async () => { + render( + , + ) + }) + + // Foreign link should be completely hidden + expect(screen.queryByText('dev_asset.mp4')).toBeNull() + expect(screen.queryByText(/Server:/i)).toBeNull() + + // Matching link should be visible + expect(screen.getAllByText(/staging_asset.mp4/i).length).toBeGreaterThan(0) + + // Active sequence (seq-1) is linked to foreign server, so current sequence card should show unlinked state + expect(screen.getByText('This sequence is not linked to any Shumai asset.')).toBeDefined() + + // Link count reported to parent should only count staging link (1) + expect(mockOnLinkCountChange).toHaveBeenCalledWith(1) + }) + + it('shows error toast when manual sync fails', async () => { + const mockSeq = { guid: 'seq-1', name: 'Sequence 01' } + const mockProject = { guid: 'proj-1' } + const mockLink = { + sequenceGuid: 'seq-1', + sequenceName: 'Sequence 01', + assetId: 'asset-missing', + assetName: 'missing.mp4', + endpoint: 'https://staging.shumai.one', + syncedCommentIds: [], + lastSyncAt: Date.now(), + totalCommentsSynced: 0, + } + + vi.spyOn(premiereService, 'getActiveProject').mockResolvedValue( + mockProject as unknown as Project, + ) + vi.spyOn(premiereService, 'getActiveSequence').mockResolvedValue(mockSeq as unknown as Sequence) + vi.spyOn(premiereService, 'getAllSequences').mockResolvedValue([mockSeq as unknown as Sequence]) + vi.spyOn(linkStorage, 'getAllLinkedSequences').mockResolvedValue([mockLink]) + + vi.spyOn(markersService, 'fetchAssetComments').mockRejectedValue( + new Error('Asset not found on this server (HTTP 404)'), + ) + + await act(async () => { + render( + , + ) + }) + + const syncButtons = screen.getAllByTitle('Sync comments now') + expect(syncButtons[0].hasAttribute('disabled')).toBe(false) + + await act(async () => { + fireEvent.click(syncButtons[0]) + }) + + expect(markersService.fetchAssetComments).toHaveBeenCalledWith( + 'https://staging.shumai.one', + 'staging-key', + 'asset-missing', + ) + expect(screen.getByText('Asset not found on this server (HTTP 404)')).toBeDefined() + }) + + it('shows success toast when manual sync succeeds', async () => { + const mockSeq = { guid: 'seq-1', name: 'Sequence 01' } + const mockProject = { guid: 'proj-1' } + const mockLink = { + sequenceGuid: 'seq-1', + sequenceName: 'Sequence 01', + assetId: 'asset-1', + assetName: 'final.mp4', + endpoint: 'https://staging.shumai.one', + syncedCommentIds: [], + lastSyncAt: Date.now(), + totalCommentsSynced: 0, + } + + vi.spyOn(premiereService, 'getActiveProject').mockResolvedValue( + mockProject as unknown as Project, + ) + vi.spyOn(premiereService, 'getActiveSequence').mockResolvedValue(mockSeq as unknown as Sequence) + vi.spyOn(premiereService, 'getAllSequences').mockResolvedValue([mockSeq as unknown as Sequence]) + vi.spyOn(linkStorage, 'getAllLinkedSequences').mockResolvedValue([mockLink]) + + vi.spyOn(markersService, 'fetchAssetComments').mockResolvedValue([ + { id: 'comm-1', second: 10, message: 'Fix color' } as unknown as CommentInfo, + ]) + vi.spyOn(markersService, 'syncCommentsToSequence').mockResolvedValue({ + updatedLink: { ...mockLink, syncedCommentIds: ['comm-1'], totalCommentsSynced: 1 }, + addedCount: 1, + }) + + await act(async () => { + render( + , + ) + }) + + const syncButtons = screen.getAllByTitle('Sync comments now') + await act(async () => { + fireEvent.click(syncButtons[0]) + }) + + expect(screen.getByText('Synced 1 new comment marker for "Sequence 01".')).toBeDefined() + }) }) diff --git a/apps/premiere-uxp/src/views/SequencesView.tsx b/apps/premiere-uxp/src/views/SequencesView.tsx index 36b4d48a..5836f037 100644 --- a/apps/premiere-uxp/src/views/SequencesView.tsx +++ b/apps/premiere-uxp/src/views/SequencesView.tsx @@ -10,14 +10,13 @@ import { } from '../services/premiere' import { getAllLinkedSequences, normalizeGuid, removeSequenceLink } from '../services/linkStorage' import { fetchAssetComments, syncCommentsToSequence } from '../services/markers' -import { resolveAssetUrl } from '../utils/url' +import { resolveAssetUrl, isSameEndpoint } from '../utils/url' import { formatDateAgo } from '../utils/date' import { ProgressCircle } from '@swc-react/progress-circle' export interface SequencesViewProps { endpoint: string apiKey: string - onSwitchToBrowse?: () => void onLinkCountChange?: (count: number) => void } @@ -33,7 +32,7 @@ export const SequencesView: React.FC = ({ const [loading, setLoading] = useState(true) const [syncingGuid, setSyncingGuid] = useState(null) const [unlinkingGuid, setUnlinkingGuid] = useState(null) - const [toastMessage, setToastMessage] = useState(null) + const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null) const loadData = useCallback(async () => { try { @@ -55,15 +54,19 @@ export const SequencesView: React.FC = ({ setActiveSeq(currentActive) setAllSeqs(seqsList) - const links = await getAllLinkedSequences(pr, seqsList) - setLinkedSequences(links) - onLinkCountChange?.(links.length) + const allLinks = await getAllLinkedSequences(pr, seqsList) + // Hide foreign links entirely: only show sequences linked to the current endpoint + const currentServerLinks = allLinks.filter( + (link) => !link.endpoint || isSameEndpoint(link.endpoint, endpoint), + ) + setLinkedSequences(currentServerLinks) + onLinkCountChange?.(currentServerLinks.length) } catch (err) { console.error('[SequencesView] Failed to load sequences data:', err) } finally { setLoading(false) } - }, [onLinkCountChange]) + }, [endpoint, onLinkCountChange]) useEffect(() => { void loadData() @@ -96,9 +99,25 @@ export const SequencesView: React.FC = ({ } }, [loadData]) + const showToast = (type: 'success' | 'error', message: string, duration = 4000) => { + setToast({ type, message }) + setTimeout(() => { + setToast((prev) => (prev?.message === message ? null : prev)) + }, duration) + } + // Sync Now handler const handleSyncNow = async (link: LinkedSequenceAsset) => { if (!project || syncingGuid) return + if (link.endpoint && !isSameEndpoint(link.endpoint, endpoint)) { + showToast( + 'error', + `Cannot sync comments: sequence was linked to "${link.endpoint}". Connect to that server to sync.`, + 5000, + ) + return + } + const targetSeq = allSeqs.find((s) => normalizeGuid(s.guid) === normalizeGuid(link.sequenceGuid)) || (await getAllSequences(project)).find( @@ -124,14 +143,19 @@ export const SequencesView: React.FC = ({ ), ) - setToastMessage( + showToast( + 'success', addedCount > 0 ? `Synced ${addedCount} new comment ${addedCount === 1 ? 'marker' : 'markers'} for "${link.sequenceName}".` : `All comments are already synced for "${link.sequenceName}".`, ) - setTimeout(() => setToastMessage(null), 4000) } catch (err) { console.error('[SequencesView] Failed to sync comments:', err) + showToast( + 'error', + err instanceof Error ? err.message : 'Failed to sync comments from server.', + 5000, + ) } finally { setSyncingGuid(null) } @@ -157,10 +181,10 @@ export const SequencesView: React.FC = ({ onLinkCountChange?.(next.length) return next }) - setToastMessage(`Unlinked "${link.sequenceName}" from "${link.assetName}".`) - setTimeout(() => setToastMessage(null), 3000) + showToast('success', `Unlinked "${link.sequenceName}" from "${link.assetName}".`, 3000) } catch (err) { console.error('[SequencesView] Failed to unlink sequence:', err) + showToast('error', 'Failed to unlink sequence.', 4000) } finally { setUnlinkingGuid(null) } @@ -180,6 +204,41 @@ export const SequencesView: React.FC = ({ setActiveSeq(targetSeq) } + const renderToast = () => { + if (!toast) return null + const isError = toast.type === 'error' + return ( +
+ {isError ? ( + + ) : ( + + )} + {toast.message} +
+ ) + } + if (loading) { return (
= ({ if (linkedSequences.length === 0) { return (
- {toastMessage && ( -
- - {toastMessage} -
- )} + {renderToast()}
= ({ style={{ fontSize: 11, color: 'var(--text-secondary)', - marginBottom: 16, + marginBottom: 0, maxWidth: 280, lineHeight: 1.4, }} @@ -254,27 +293,7 @@ export const SequencesView: React.FC = ({ return (
{/* Toast Notification */} - {toastMessage && ( -
- - {toastMessage} -
- )} + {renderToast()} {/* SECTION 1: Current Sequence Asset */}
@@ -287,7 +306,10 @@ export const SequencesView: React.FC = ({
{currentSequenceLink.assetThumbnailUrl ? ( {currentSequenceLink.assetName} ) : ( @@ -402,7 +424,7 @@ export const SequencesView: React.FC = ({
{link.assetThumbnailUrl ? ( {link.assetName} ) : (