diff --git a/locales/en.json b/locales/en.json index 96375e25c..2ea667807 100644 --- a/locales/en.json +++ b/locales/en.json @@ -63,6 +63,20 @@ }, "assets": { "kindLabel": "Asset type", + "buildPickerLabel": "Build", + "browseAssetsOf": "Browse the assets of", + "thisComputer": "This computer", + "outputFolder": "Output folder", + "buildStatus": "{where} · {state}", + "buildWhere": { + "local": "Local", + "cloud": "Cloud" + }, + "buildState": { + "running": "Running", + "starting": "Starting", + "stopped": "Stopped" + }, "kind": { "all": "All", "image": "Images", @@ -104,7 +118,6 @@ "deleteFailed": "Couldn't delete asset", "noMatches": "No matching assets", "noMatchesHint": "Try another type or search.", - "filter": "Filter", "signedOutTitle": "Log in to see your assets", "signedOutBody": "Assets that you make in Comfy Cloud show here.", "signIn": "Log in to Comfy Cloud", diff --git a/locales/zh.json b/locales/zh.json index 68f4beb74..228c181d0 100644 --- a/locales/zh.json +++ b/locales/zh.json @@ -63,6 +63,20 @@ }, "assets": { "kindLabel": "资产类型", + "buildPickerLabel": "构建", + "browseAssetsOf": "浏览以下构建的资产", + "thisComputer": "这台电脑", + "outputFolder": "输出文件夹", + "buildStatus": "{where} · {state}", + "buildWhere": { + "local": "本地", + "cloud": "云端" + }, + "buildState": { + "running": "运行中", + "starting": "启动中", + "stopped": "已停止" + }, "kind": { "all": "全部", "image": "图片", @@ -104,7 +118,6 @@ "deleteFailed": "无法删除资产", "noMatches": "没有匹配的资产", "noMatchesHint": "试试其他类型或搜索词。", - "filter": "筛选", "signedOutTitle": "登录以查看你的资产", "signedOutBody": "你在 Comfy Cloud 中生成的资产会显示在这里。", "signIn": "登录 Comfy Cloud", diff --git a/src/main/lib/ipc/installationsForRenderer.test.ts b/src/main/lib/ipc/installationsForRenderer.test.ts new file mode 100644 index 000000000..76e64cfab --- /dev/null +++ b/src/main/lib/ipc/installationsForRenderer.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it, vi } from 'vitest' +import { EventEmitter } from 'events' +import os from 'os' +import type { InstallationRecord } from '../../installations' + +vi.mock('electron', () => ({ + app: { + isPackaged: false, + getPath: () => os.tmpdir(), + getVersion: () => '0.0.0-test', + getLocale: () => 'en' + }, + ipcMain: { handle: vi.fn(), on: vi.fn(), off: vi.fn() }, + dialog: {}, + shell: {}, + session: {}, + WebContentsView: class {}, + BrowserWindow: { getAllWindows: () => [] }, + nativeTheme: { on: vi.fn(), shouldUseDarkColors: false } +})) + +vi.mock('../i18n', () => ({ + t: (key: string) => key, + init: vi.fn(), + getMessages: () => ({}), + getLocale: () => 'en', + getAvailableLocales: () => [] +})) + +vi.mock('../../settings', () => ({ + get: vi.fn(() => undefined), + set: vi.fn(async () => {}), + getAll: vi.fn(() => ({})), + getMirrorConfig: vi.fn(() => ({ pypiMirror: undefined, useChineseMirrors: false })), + defaults: { modelsDirs: ['/unused'], inputDir: '/unused', outputDir: '/unused' } +})) + +vi.mock('../../installations', () => ({ + installationEvents: new EventEmitter(), + CLOUD_SOURCE_ID: 'cloud', + list: vi.fn(async () => []), + get: vi.fn(async () => null), + update: vi.fn(async () => null), + remove: vi.fn(async () => {}) +})) + +import { enrichInstallationsForRenderer } from './registerInstallationHandlers' + +function installation(id: string, sourceId: string): InstallationRecord { + return { + id, + name: id, + sourceId, + installPath: `/installs/${id}`, + status: 'installed', + createdAt: '2026-11-01T00:00:00Z' + } +} + +describe('enrichInstallationsForRenderer', () => { + it('tells the page which builds save to an output folder Desktop can list', () => { + const { enriched } = enrichInstallationsForRenderer([ + installation('standalone', 'standalone'), + installation('from-a-build', 'comfybuilder'), + installation('old-desktop', 'desktop'), + installation('cloud', 'cloud'), + installation('server', 'remote') + ]) + + expect(Object.fromEntries(enriched.map((inst) => [inst.id, inst.hasOutputFolder]))).toEqual({ + standalone: true, + 'from-a-build': true, + 'old-desktop': false, + cloud: false, + server: false + }) + }) +}) diff --git a/src/main/lib/ipc/registerInstallationHandlers.ts b/src/main/lib/ipc/registerInstallationHandlers.ts index 0ebf5642d..95b2ccbe5 100644 --- a/src/main/lib/ipc/registerInstallationHandlers.ts +++ b/src/main/lib/ipc/registerInstallationHandlers.ts @@ -38,6 +38,7 @@ import * as releaseCache from '../release-cache' import { runStartupReleaseChecks } from '../release-cache-startup' import { _broadcastToRenderer } from './shared' import { hasGitDir } from '../git' +import { hasOutputFolder } from '../outputFolders' import { parseUrl } from '../util' import { restoreSnapshotIntoInstallation } from '../standaloneMigration' import * as mainTelemetry from '../telemetry' @@ -129,6 +130,7 @@ export function enrichInstallationsForRenderer(allInstalls: InstallationRecord[] sourceLabel: source.label, sourceCategory: source.category, hasConsole: source.hasConsole !== false, + hasOutputFolder: hasOutputFolder(inst), ...(buildVersion ? { distributionVersion: buildVersion } : {}), ...(listPreview != null ? { listPreview } : {}), ...(statusTag ? { statusTag } : {}) diff --git a/src/main/lib/outputFolders.test.ts b/src/main/lib/outputFolders.test.ts index e3ebd3c70..60341690f 100644 --- a/src/main/lib/outputFolders.test.ts +++ b/src/main/lib/outputFolders.test.ts @@ -65,11 +65,8 @@ vi.mock('../settings', () => ({ })) vi.mock('./ipc/shared', () => ({ sourceMap: { - standalone: { category: 'local', getLaunchCommand: () => ({ cmd: 'python' }) }, - desktop: { - category: 'local', - getLaunchCommand: () => ({ cmd: 'open', skipSharedPaths: true }) - }, + standalone: { category: 'local' }, + desktop: { category: 'local', managesOwnPaths: true }, cloud: { category: 'cloud' } } })) @@ -89,6 +86,7 @@ import { MAX_LOCAL_ASSETS, THUMBNAIL_WAIT_MS, copyOutputImage, + hasOutputFolder, revealOutputFile, trashOutputFile, listLocalAssets, @@ -164,6 +162,22 @@ describe('outputDirOverride', () => { }) }) +describe('hasOutputFolder', () => { + it('is true only for a local build that leaves its paths to Desktop', () => { + expect(hasOutputFolder(install('a')), 'a build on the shared folder').toBe(true) + expect( + hasOutputFolder(install('a', { useSharedOutput: false })), + 'a build that saves inside its install' + ).toBe(true) + expect(hasOutputFolder(install('a', { sourceId: 'cloud' })), 'Cloud').toBe(false) + expect( + hasOutputFolder(install('a', { sourceId: 'desktop' })), + 'a build that manages its own paths' + ).toBe(false) + expect(hasOutputFolder(install('a', { sourceId: 'gone' })), 'an unknown source').toBe(false) + }) +}) + describe('listOutputFolders', () => { it('lists each real output folder once, leaving out Cloud and builds that manage their own paths', async () => { expect(await listOutputFolders()).toEqual([ @@ -182,22 +196,18 @@ describe('listOutputFolders', () => { }) describe('listLocalAssets', () => { - it('lists media from every output folder and its subfolders, newest first', async () => { + it("lists the media in the picked build's output folder and its subfolders, newest first", async () => { write(path.join(sharedDir, 'old.png'), 'x', new Date('2026-10-01T00:00:00Z')) write(path.join(sharedDir, 'video', 'new.mp4'), 'xx', new Date('2026-11-05T00:00:00Z')) + write(path.join(sharedDir, 'mesh.glb'), 'x', new Date('2026-11-02T00:00:00Z')) write(path.join(ownDir, 'voice.wav'), 'xxx', new Date('2026-11-03T00:00:00Z')) - write( - path.join(installDir, 'ComfyUI', 'output', 'mesh.glb'), - 'x', - new Date('2026-11-02T00:00:00Z') - ) write(path.join(sharedDir, 'notes.txt')) write(path.join(sharedDir, '.hidden.png')) write(path.join(sharedDir, '.cache', 'inside-hidden.png')) - const assets = await listLocalAssets() + const assets = await listLocalAssets('Test Instance') - expect(assets.map((a) => a.name)).toEqual(['new.mp4', 'voice.wav', 'mesh.glb', 'old.png']) + expect(assets.map((a) => a.name)).toEqual(['new.mp4', 'mesh.glb', 'old.png']) const newVideo = path.join(sharedDir, 'video', 'new.mp4') expect(assets[0]).toEqual({ id: newVideo, @@ -214,10 +224,10 @@ describe('listLocalAssets', () => { durationSeconds: null }) const oldPicture = path.join(sharedDir, 'old.png') - expect(assets[3]!.thumbnailUrl, 'an image thumbnail link changes when the file does').toBe( + expect(assets[2]!.thumbnailUrl, 'an image thumbnail link changes when the file does').toBe( outputFileUrl(oldPicture, fs.statSync(oldPicture).mtimeMs) ) - expect(assets[2]!.previewUrl, '3D files have no preview').toBeNull() + expect(assets[1]!.previewUrl, '3D files have no preview').toBeNull() }) it('reports the size of each picture and video, and how long a video runs, before they load', async () => { @@ -226,7 +236,7 @@ describe('listLocalAssets', () => { write(path.join(sharedDir, 'broken.png'), 'not a picture') const facts = Object.fromEntries( - (await listLocalAssets()).map((a) => [ + (await listLocalAssets('Test Instance')).map((a) => [ a.name, [a.width, a.height, a.durationSeconds && Math.round(a.durationSeconds)] ]) @@ -239,17 +249,48 @@ describe('listLocalAssets', () => { }) }) - it('finds a file once when two builds save to the same folder', async () => { + it('shows each build the files in its own output folder', async () => { write(path.join(sharedDir, 'shared.png')) + write(path.join(ownDir, 'own.png')) + write(path.join(installDir, 'ComfyUI', 'output', 'install.png')) + const namesFor = async (id: string) => (await listLocalAssets(id)).map((a) => a.name) - expect((await listLocalAssets()).map((a) => a.name)).toEqual(['shared.png']) + expect(await namesFor('Test Instance'), 'a build on the shared folder').toEqual(['shared.png']) + expect(await namesFor('My Local 1'), 'another build on the shared folder').toEqual([ + 'shared.png' + ]) + expect(await namesFor('Apps'), 'a build with its own folder').toEqual(['own.png']) + expect(await namesFor('Bare'), 'a build that saves inside its install').toEqual(['install.png']) + expect(await namesFor('Cloud'), 'Cloud has no folder on this computer').toEqual([]) + expect(await namesFor('Old Desktop'), 'a build that manages its own paths').toEqual([]) + expect(await namesFor('deleted'), 'a build that is gone').toEqual([]) + expect( + (await listLocalAssets()).map((a) => a.name), + 'no build: the shared output folder' + ).toEqual(['shared.png']) + }) + + it('opens a file it listed for a build added a moment ago', async () => { + await listOutputFolders() + const newDir = path.join(root, 'new-output') + const file = path.join(newDir, 'first.png') + write(file) + installs.mockResolvedValue([install('New', { useSharedOutput: false, outputDir: newDir })]) + try { + const [listed] = await listLocalAssets('New') + + expect(listed!.id).toBe(file) + expect(await outputFilePath(listed!.id)).toBe(file) + } finally { + fs.rmSync(newDir, { recursive: true, force: true }) + } }) it('keeps only the newest files when the folders are very large', async () => { for (let i = 0; i <= MAX_LOCAL_ASSETS; i++) write(path.join(sharedDir, `f${i}.png`), '', new Date(Date.UTC(2026, 0, 1, 0, 0, i))) - const assets = await listLocalAssets() + const assets = await listLocalAssets('Test Instance') expect(assets).toHaveLength(MAX_LOCAL_ASSETS) expect(assets.map((a) => a.name)).not.toContain('f0.png') @@ -264,7 +305,7 @@ describe('listLocalAssets', () => { ) write(path.join(deep, 'too-deep.png')) - expect(await listLocalAssets()).toEqual([]) + expect(await listLocalAssets('Test Instance')).toEqual([]) }) }) diff --git a/src/main/lib/outputFolders.ts b/src/main/lib/outputFolders.ts index 51dcecad1..1b0ead901 100644 --- a/src/main/lib/outputFolders.ts +++ b/src/main/lib/outputFolders.ts @@ -44,9 +44,13 @@ export function outputDirOverride(inst: InstallationRecord, sharedDir: string): return (inst.outputDir as string | undefined) || null } -function outputDirFor(inst: InstallationRecord, sharedDir: string): string | null { +export function hasOutputFolder(inst: InstallationRecord): boolean { const source = sourceMap[inst.sourceId] - if (source?.category !== 'local' || source.getLaunchCommand(inst)?.skipSharedPaths) return null + return source?.category === 'local' && !source.managesOwnPaths +} + +function outputDirFor(inst: InstallationRecord, sharedDir: string): string | null { + if (!hasOutputFolder(inst)) return null return outputDirOverride(inst, sharedDir) ?? installOutputDir(inst.installPath) } @@ -57,19 +61,29 @@ async function realDir(dir: string): Promise { return stat?.isDirectory() ? real : null } -export async function listOutputFolders(): Promise { - const shared = sharedOutputDir() - const folders = new Set() - const sharedReal = await realDir(shared) - if (sharedReal) folders.add(sharedReal) +interface OutputFolders { + all: string[] + shared: string | null + ofBuild: Map +} + +async function findOutputFolders(): Promise { + const sharedDir = sharedOutputDir() + const shared = await realDir(sharedDir) + const ofBuild = new Map() for (const inst of await installations.list()) { - const dir = outputDirFor(inst, shared) + const dir = outputDirFor(inst, sharedDir) const real = dir ? await realDir(dir) : null - if (real) folders.add(real) + if (real) ofBuild.set(inst.id, real) } - allowedRoots = [...folders] + const all = [...new Set([...(shared ? [shared] : []), ...ofBuild.values()])] + allowedRoots = all allowedRootsAt = Date.now() - return allowedRoots + return { all, shared, ofBuild } +} + +export async function listOutputFolders(): Promise { + return (await findOutputFolders()).all } function isInsideRoot(target: string, root: string): boolean { @@ -79,7 +93,7 @@ function isInsideRoot(target: string, root: string): boolean { async function allowedPath(target: string): Promise { if (!path.isAbsolute(target)) return null - if (Date.now() - allowedRootsAt > ROOTS_FRESH_MS) await listOutputFolders() + if (Date.now() - allowedRootsAt > ROOTS_FRESH_MS) await findOutputFolders() const real = await fsp.realpath(target).catch(() => null) if (!real) return null return allowedRoots.some((root) => isInsideRoot(real, root)) ? real : null @@ -161,9 +175,10 @@ async function addMediaFacts(asset: AssetSummary): Promise { Object.assign(asset, await mediaFactsFromFile(asset.id, asset.kind)) } -export async function listLocalAssets(): Promise { - const folders = await listOutputFolders() - const files = [...new Set((await Promise.all(folders.map(collectMediaFiles))).flat())] +export async function listLocalAssets(installationId?: string): Promise { + const folders = await findOutputFolders() + const folder = installationId === undefined ? folders.shared : folders.ofBuild.get(installationId) + const files = folder ? await collectMediaFiles(folder) : [] const found: AssetSummary[] = [] await runPool(files, STATS_AT_ONCE, async (file) => { const stat = await fsp.stat(file).catch(() => null) @@ -304,5 +319,7 @@ export function registerOutputFilesScheme(): void { export function registerOutputFolderHandlers(): void { protocol.handle(OUTPUT_FILES_SCHEME, serveOutputFile) - ipcMain.handle(LIST_LOCAL_CHANNEL, () => listLocalAssets()) + ipcMain.handle(LIST_LOCAL_CHANNEL, (_event, installationId: unknown) => + listLocalAssets(typeof installationId === 'string' ? installationId : undefined) + ) } diff --git a/src/main/sources/desktop.ts b/src/main/sources/desktop.ts index d8af6c6a4..13496aba5 100644 --- a/src/main/sources/desktop.ts +++ b/src/main/sources/desktop.ts @@ -25,6 +25,7 @@ export const desktop: SourcePlugin = { category: 'local', hasConsole: true, skipInstall: true, + managesOwnPaths: true, platforms: ['win32', 'darwin'], hidden: true, diff --git a/src/main/types/sources.ts b/src/main/types/sources.ts index cc0d0d3cb..10db6a6b4 100644 --- a/src/main/types/sources.ts +++ b/src/main/types/sources.ts @@ -107,6 +107,7 @@ export interface SourcePlugin { category: string hasConsole?: boolean skipInstall?: boolean + managesOwnPaths?: boolean platforms?: readonly string[] hidden?: boolean fields: readonly SourceField[] diff --git a/src/preload/api.ts b/src/preload/api.ts index 0822465fe..8c2e2541a 100644 --- a/src/preload/api.ts +++ b/src/preload/api.ts @@ -97,7 +97,8 @@ export function buildElectronApi(): ElectronApi { signalOverlayReady: () => ipcRenderer.send('comfy-window:overlay-ready'), navigatePanel: (page) => ipcRenderer.send('comfy-window:navigate-panel', page), listAssets: (installationId) => ipcRenderer.invoke('assets:list', installationId), - listLocalAssets: () => ipcRenderer.invoke('assets:list-local'), + listLocalAssets: (installationId?: string) => + ipcRenderer.invoke('assets:list-local', installationId), downloadAsset: (source, assetId, fileName) => ipcRenderer.invoke('assets:download', source, assetId, fileName), revealAsset: (source, assetId) => ipcRenderer.invoke('assets:reveal', source, assetId), diff --git a/src/renderer/src/panel/AssetsView.test.ts b/src/renderer/src/panel/AssetsView.test.ts index 98f7625a6..f29cbd080 100644 --- a/src/renderer/src/panel/AssetsView.test.ts +++ b/src/renderer/src/panel/AssetsView.test.ts @@ -6,8 +6,10 @@ import '../assets/main.css' import AssetsView from './AssetsView.vue' import Tooltip from '../components/ui/Tooltip.vue' import { useAuthStore } from '../stores/authStore' +import { useDashboardScopeStore } from '../stores/dashboardScopeStore' import { useInstallationStore } from '../stores/installationStore' -import type { AssetSummary, Installation } from '../types/ipc' +import { useSessionStore } from '../stores/sessionStore' +import type { AssetSummary, Installation, RunningInstance } from '../types/ipc' const listAssets = vi.fn() const listLocalAssets = vi.fn() @@ -18,6 +20,10 @@ const trashAsset = vi.fn() const alert = vi.fn() const confirm = vi.fn() const signIn = vi.fn().mockResolvedValue({ signedIn: false }) +const switchWorkspace = vi.fn() +const listWorkspaces = vi.fn() +const getAuthStatus = vi.fn() +const getSetting = vi.fn() const MASONRY_GAP = 14 const FOUR_COLUMN_PAGE_WIDTH = 1100 const TALL_PAGE_HEIGHT = 3000 @@ -63,17 +69,70 @@ function asset( } } -function cloudBuild(id: string): Installation { - return { id, name: id, sourceLabel: 'Comfy Cloud', sourceCategory: 'cloud' } +function cloudBuild(id: string, name = id): Installation { + return { id, name, sourceLabel: 'Comfy Cloud', sourceCategory: 'cloud' } } -async function mountAssets(local: AssetSummary[] | Promise = []) { +function localBuild(id: string, name = id, extra: Partial = {}): Installation { + return { + id, + name, + sourceLabel: 'Standalone', + sourceCategory: 'local', + hasOutputFolder: true, + ...extra + } +} + +function oldDesktopBuild(id: string, name = id): Installation { + return localBuild(id, name, { sourceLabel: 'Desktop', hasOutputFolder: false }) +} + +function teamBuild(build: Installation): Installation { + return { ...build, workspaceId: 'team-b' } +} + +function signedInToPersonalWithTeamDashboard(): void { + getAuthStatus.mockResolvedValue({ signedIn: true, workspaceId: 'me', workspaceType: 'personal' }) + getSetting.mockImplementation(async (key: string) => + key === 'dashboardWorkspaceId' ? 'team-b' : undefined + ) +} + +async function mountAssets( + local: AssetSummary[] | Promise = [], + { + builds = [localBuild('lab')], + installationId + }: { builds?: Installation[]; installationId?: string } = {} +) { + const installationStore = useInstallationStore() + installationStore.installations = builds + installationStore.loading = false listLocalAssets.mockReturnValue(Promise.resolve(local)) - const wrapper = mount(AssetsView, { attachTo: page }) + const wrapper = mount(AssetsView, { attachTo: page, props: { installationId } }) await flushPromises() return wrapper } +async function openBuildPicker(wrapper: Awaited>): Promise { + await wrapper.get('[data-testid="assets-build-picker"]').trigger('keydown', { key: 'Enter' }) + await flushPromises() +} + +function buildRows(): string[] { + return [ + ...document.querySelectorAll( + '[data-testid^="assets-build-"]:not([data-testid="assets-build-picker"])' + ) + ].map((row) => row.textContent?.replace(/\s+/g, ' ').trim() ?? '') +} + +async function pickBuild(id: string): Promise { + document.querySelector(`[data-testid="assets-build-${id}"]`)!.click() + await flushPromises() +} + async function signInWith(cloud: AssetSummary[]): Promise { useInstallationStore().installations = [cloudBuild('cloud')] listAssets.mockResolvedValue(cloud) @@ -133,6 +192,16 @@ beforeEach(() => { vi.clearAllMocks() window.localStorage.clear() listLocalAssets.mockResolvedValue([]) + listWorkspaces.mockResolvedValue([ + { id: 'me', name: 'Personal Workspace', type: 'personal' }, + { id: 'team-b', name: 'Team B', type: 'team' } + ]) + switchWorkspace.mockImplementation(async (workspaceId: string) => ({ + signedIn: true, + workspaceId + })) + getAuthStatus.mockResolvedValue({ signedIn: false }) + getSetting.mockResolvedValue(undefined) ;(window as unknown as { api: unknown }).api = { listAssets, listLocalAssets, @@ -141,11 +210,16 @@ beforeEach(() => { copyAsset, trashAsset, platform: 'darwin', + getSetting, + setSetting: vi.fn().mockResolvedValue(undefined), + onSettingsChanged: vi.fn(() => () => {}), onInstallationsChanged: vi.fn(() => () => {}), onInstallationsVersionsUpdated: vi.fn(() => () => {}), comfybuilder: { - getAuthStatus: vi.fn().mockResolvedValue({ signedIn: false }), + getAuthStatus, signIn, + switchWorkspace, + listWorkspaces, onAuthChanged: vi.fn(() => () => {}) } } @@ -264,13 +338,13 @@ describe('AssetsView', () => { expect(wrapper.get('[data-testid="asset-a"]').text()).not.toContain('a.svg') }) - it('shows the files on this computer without any build running or a Cloud login', async () => { + it('shows the files of a local build without it running or a Cloud login', async () => { const wrapper = await mountAssets([ asset('/out/surfer.mp4', 'surfer.mp4', 'video'), asset('/out/forest.png', 'forest.png', 'image') ]) - expect(listLocalAssets).toHaveBeenCalledOnce() + expect(listLocalAssets).toHaveBeenCalledExactlyOnceWith('lab') expect(listAssets).not.toHaveBeenCalled() expect(assetNames(wrapper)).toEqual(['surfer.mp4', 'forest.png']) }) @@ -286,25 +360,112 @@ describe('AssetsView', () => { expect(wrapper.get('img').attributes('src')).toBe('comfy-output://file/full?thumbnail=1') }) - it('mixes this computer and the signed-in Cloud workspace, newest first', async () => { - const wrapper = await mountAssets([ - asset('/out/old.png', 'old.png', 'image', { createdAt: '2026-11-01T00:00:00Z' }) + it("opens on the window's build, lists every build with where it runs, and switches to the one picked", async () => { + useSessionStore().runningInstances.set('lab', { installationId: 'lab' } as RunningInstance) + listAssets.mockResolvedValue([asset('c1', 'cloud.png', 'image')]) + const wrapper = await mountAssets([asset('/out/mine.png', 'mine.png', 'image')], { + builds: [ + localBuild('mine', 'My Local 1'), + localBuild('lab', 'Video Lab'), + { + ...cloudBuild('cloud', 'Comfy Cloud'), + statusTag: { style: 'update', label: 'Update available' } + } + ], + installationId: 'mine' + }) + + useAuthStore().status = { signedIn: true } + await flushPromises() + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('My Local 1') + expect( + listLocalAssets.mock.calls.flat(), + 'only the window build is read, and logging in does not read it again' + ).toEqual(['mine']) + expect(listAssets).not.toHaveBeenCalled() + expect(assetNames(wrapper)).toEqual(['mine.png']) + + await openBuildPicker(wrapper) + expect(document.body.textContent).toContain('Browse the assets of') + expect(buildRows()).toEqual([ + 'My Local 1 Local · Stopped', + 'Video Lab Local · Running', + 'Comfy Cloud Cloud · Running' ]) - await signInWith([asset('c1', 'cloud.png', 'image', { createdAt: '2026-11-05T00:00:00Z' })]) - expect(listAssets.mock.calls.map(([id]) => id)).toEqual(['cloud']) - expect(assetNames(wrapper)).toEqual(['cloud.png', 'old.png']) + await pickBuild('cloud') + + expect(listAssets).toHaveBeenCalledExactlyOnceWith('cloud') + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Comfy Cloud') + expect(assetNames(wrapper), "only the picked build's files show").toEqual(['cloud.png']) }) - it('loads the Cloud assets once when the account has several Cloud builds', async () => { - useInstallationStore().installations = [cloudBuild('cloud-a'), cloudBuild('cloud-b')] - listAssets.mockResolvedValue([asset('a', 'forest.png', 'image')]) + it('reopens on the last picked build in a window with no build of its own', async () => { + const builds = [localBuild('mine', 'My Local 1'), localBuild('lab', 'Video Lab')] + const first = await mountAssets([], { builds }) + await openBuildPicker(first) + await pickBuild('lab') + first.unmount() + listLocalAssets.mockClear() + + const again = await mountAssets([], { builds }) + + expect(again.get('[data-testid="assets-build-picker"]').text()).toBe('Video Lab') + expect(listLocalAssets).toHaveBeenCalledExactlyOnceWith('lab') + }) + + it('leaves out builds from other workspaces, and servers and builds whose files Desktop cannot list', async () => { + const wrapper = await mountAssets([], { + builds: [ + localBuild('mine', 'My Local 1'), + teamBuild(localBuild('team', 'Team build')), + { id: 'remote', name: 'Office server', sourceLabel: 'Remote', sourceCategory: 'remote' }, + oldDesktopBuild('old', 'Old Desktop') + ] + }) + + await openBuildPicker(wrapper) + + expect(buildRows()).toEqual(['My Local 1 Local · Stopped']) + }) + + it('opens on a build it can list, not on a running build that keeps its files to itself', async () => { + useSessionStore().runningInstances.set('old', { installationId: 'old' } as RunningInstance) + const wrapper = await mountAssets([asset('/out/forest.png', 'forest.png', 'image')], { + builds: [oldDesktopBuild('old', 'Old Desktop'), localBuild('lab', 'Video Lab')] + }) + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Video Lab') + expect(listLocalAssets).toHaveBeenCalledExactlyOnceWith('lab') + expect(assetNames(wrapper)).toEqual(['forest.png']) + }) + + it('waits for the builds before it reads any folder', async () => { + const installationStore = useInstallationStore() + const wrapper = mount(AssetsView, { attachTo: page, props: { installationId: 'mine' } }) + await flushPromises() + + expect(listLocalAssets, 'no folder is read before the builds are known').not.toHaveBeenCalled() + expect(wrapper.find('[data-testid="assets-build-picker"]').exists()).toBe(false) + expect(wrapper.findAll('[data-testid="assets-skeleton"] > li')).toHaveLength(8) + + installationStore.installations = [localBuild('lab'), localBuild('mine', 'My Local 1')] + installationStore.loading = false + await flushPromises() + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('My Local 1') + expect(listLocalAssets).toHaveBeenCalledExactlyOnceWith('mine') + }) + + it('keeps an empty page in place while the builds refresh', async () => { const wrapper = await mountAssets() - useAuthStore().status = { signedIn: true } + + useInstallationStore().loading = true await flushPromises() - expect(listAssets.mock.calls.map(([id]) => id)).toEqual(['cloud-a']) - expect(assetNames(wrapper)).toEqual(['forest.png']) + expect(wrapper.get('[data-testid="assets-empty"] h2').text()).toBe('No assets yet') + expect(wrapper.find('[data-testid="assets-skeleton"]').exists()).toBe(false) }) it('filters by asset type and by name', async () => { @@ -314,19 +475,64 @@ describe('AssetsView', () => { asset('c', 'terraces.png', 'image') ]) - await wrapper.get('[data-testid="assets-filter"]').trigger('keydown', { key: 'Enter' }) - await flushPromises() - document.querySelector('[data-testid="assets-filter-image"]')!.click() - await flushPromises() + const tabs = () => wrapper.findAll('[data-testid^="assets-kind-"]').map((tab) => tab.text()) + expect(tabs(), 'each type tab counts its files').toEqual([ + 'All3', + 'Images2', + 'Videos1', + '3D0', + 'Audio0' + ]) + + await wrapper.get('[data-testid="assets-kind-image"]').trigger('click') expect(assetNames(wrapper)).toEqual(['forest.png', 'terraces.png']) await wrapper.get('input').setValue('terr') expect(assetNames(wrapper)).toEqual(['terraces.png']) + expect(tabs(), 'the counts follow the search').toEqual([ + 'All1', + 'Images1', + 'Videos0', + '3D0', + 'Audio0' + ]) }) - it('asks a signed-out user with no files to log in to Comfy Cloud', async () => { - useInstallationStore().installations = [cloudBuild('cloud')] - const wrapper = await mountAssets() + it('shows the output folder as This computer when there is no local build', async () => { + const wrapper = await mountAssets([asset('/out/forest.png', 'forest.png', 'image')], { + builds: [cloudBuild('cloud', 'Comfy Cloud')] + }) + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('This computer') + expect( + listLocalAssets, + 'the shared output folder, not a build' + ).toHaveBeenCalledExactlyOnceWith() + expect(assetNames(wrapper)).toEqual(['forest.png']) + await openBuildPicker(wrapper) + expect(buildRows()).toEqual(['Comfy Cloud Cloud · Running', 'This computer Output folder']) + }) + + it('reopens on This computer, not the saved Comfy Cloud pick, after signing out', async () => { + const builds = [cloudBuild('cloud', 'Comfy Cloud')] + const first = await mountAssets([], { builds }) + useAuthStore().status = { signedIn: true } + await flushPromises() + await openBuildPicker(first) + await pickBuild('cloud') + first.unmount() + + useAuthStore().status = { signedIn: false } + const again = await mountAssets([asset('/out/forest.png', 'forest.png', 'image')], { builds }) + + expect(again.get('[data-testid="assets-build-picker"]').text()).toBe('This computer') + expect(assetNames(again)).toEqual(['forest.png']) + }) + + it('asks a signed-out user who picked Comfy Cloud to log in', async () => { + const wrapper = await mountAssets([], { builds: [cloudBuild('cloud')] }) + await openBuildPicker(wrapper) + await pickBuild('cloud') expect(listAssets).not.toHaveBeenCalled() expect(wrapper.get('[data-testid="assets-empty"] h2').text()).toBe('Log in to see your assets') @@ -341,7 +547,9 @@ describe('AssetsView', () => { it('ignores a cancelled log-in', async () => { signIn.mockRejectedValueOnce(new Error('cancelled')) - const wrapper = await mountAssets() + const wrapper = await mountAssets([], { builds: [cloudBuild('cloud')] }) + await openBuildPicker(wrapper) + await pickBuild('cloud') await wrapper.get('[data-testid="assets-empty-action"]').trigger('click') await flushPromises() @@ -415,12 +623,11 @@ describe('AssetsView', () => { }) }) - it('does not reload when a build changes but the account stays the same', async () => { + it('does not reload when another build changes but the picked build stays the same', async () => { await mountAssets([asset('a', 'forest.png', 'image')]) - useInstallationStore().installations = [ - { id: 'lab', name: 'Video Lab', sourceLabel: 'Standalone', sourceCategory: 'local' } - ] + useInstallationStore().installations = [localBuild('lab'), localBuild('other', 'Video Lab')] + useSessionStore().runningInstances.set('lab', { installationId: 'lab' } as RunningInstance) await flushPromises() expect(listLocalAssets).toHaveBeenCalledOnce() @@ -447,29 +654,148 @@ describe('AssetsView', () => { } }) - it('keeps the files on this computer when Cloud fails', async () => { - const wrapper = await mountAssets([asset('/out/forest.png', 'forest.png', 'image')]) - useInstallationStore().installations = [cloudBuild('cloud')] - listAssets.mockRejectedValue(new Error('offline')) - useAuthStore().status = { signedIn: true } + it('stays on the build it opened on when another build starts', async () => { + const wrapper = await mountAssets([asset('a', 'forest.png', 'image')], { + builds: [ + localBuild('mine', 'My Local 1', { lastLaunchedAt: 1 }), + localBuild('lab', 'Video Lab', { lastLaunchedAt: 2 }) + ] + }) + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Video Lab') + + useSessionStore().runningInstances.set('mine', { installationId: 'mine' } as RunningInstance) + useInstallationStore().installations = [ + localBuild('mine', 'My Local 1', { lastLaunchedAt: 3 }), + localBuild('lab', 'Video Lab', { lastLaunchedAt: 2 }) + ] await flushPromises() - expect(assetNames(wrapper)).toEqual(['forest.png']) - expect(wrapper.find('[data-testid="assets-empty"]').exists()).toBe(false) + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Video Lab') + expect(listLocalAssets).toHaveBeenCalledExactlyOnceWith('lab') }) - it('reloads when the signed-in workspace changes', async () => { - await mountAssets([asset('a', 'forest.png', 'image')]) + it('switches to the builds of the workspace the user moves to', async () => { + listAssets.mockResolvedValue([asset('t1', 'team.png', 'image')]) + const wrapper = await mountAssets([asset('a', 'forest.png', 'image')], { + builds: [localBuild('lab', 'Video Lab'), teamBuild(cloudBuild('team-cloud', 'Team Cloud'))] + }) useAuthStore().status = { signedIn: true, workspaceId: 'team-b' } await flushPromises() - expect(listLocalAssets).toHaveBeenCalledTimes(2) + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Team Cloud') + expect(listAssets).toHaveBeenCalledExactlyOnceWith('team-cloud') + expect(assetNames(wrapper)).toEqual(['team.png']) + }) + + it("moves the Cloud session to the picked Cloud build's workspace before listing its assets", async () => { + const wrapper = await mountAssets([], { + builds: [teamBuild(cloudBuild('team-cloud', 'Team Cloud'))] + }) + useAuthStore().status = { signedIn: true, workspaceId: 'me', workspaceType: 'personal' } + await flushPromises() + listAssets.mockImplementation(async () => + useAuthStore().status.workspaceId === 'team-b' ? [asset('t1', 'team.png', 'image')] : [] + ) + + useDashboardScopeStore().selectWorkspace('team-b') + await flushPromises() + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Team Cloud') + expect(switchWorkspace).toHaveBeenCalledExactlyOnceWith('team-b', 'chosen') + expect(assetNames(wrapper), "the team's files, not the personal workspace's").toEqual([ + 'team.png' + ]) + }) + + it("says the load failed instead of showing another workspace's files when the personal workspace is unknown", async () => { + listAssets.mockResolvedValue([asset('t1', 'team.png', 'image')]) + listWorkspaces.mockResolvedValue([{ id: 'team-b', name: 'Team B', type: 'team' }]) + const wrapper = await mountAssets([], { builds: [cloudBuild('cloud', 'Comfy Cloud')] }) + useAuthStore().status = { signedIn: true, workspaceId: 'team-b', workspaceType: 'team' } + await flushPromises() + useDashboardScopeStore().selectWorkspace('personal') + await flushPromises() + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Comfy Cloud') + expect(listAssets).not.toHaveBeenCalled() + expect(wrapper.get('[data-testid="assets-empty"]').text()).toContain("Couldn't load assets") + }) + + it('does not list Cloud files with a session tied to no known workspace', async () => { + listAssets.mockResolvedValue([asset('x1', 'unknown.png', 'image')]) + listWorkspaces.mockResolvedValue([{ id: 'team-b', name: 'Team B', type: 'team' }]) + const wrapper = await mountAssets([], { builds: [cloudBuild('cloud', 'Comfy Cloud')] }) + useAuthStore().status = { signedIn: true } + await flushPromises() + + expect(listAssets).not.toHaveBeenCalled() + expect(wrapper.get('[data-testid="assets-empty"]').text()).toContain("Couldn't load assets") + }) + + it("reopens on a saved workspace's Cloud build without treating the move there as the user's choice", async () => { + signedInToPersonalWithTeamDashboard() + listAssets.mockResolvedValue([asset('t1', 'team.png', 'image')]) + + const wrapper = await mountAssets([], { + builds: [teamBuild(cloudBuild('team-cloud', 'Team Cloud'))] + }) + + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Team Cloud') + expect(switchWorkspace).toHaveBeenCalledExactlyOnceWith('team-b', 'restored') + expect(assetNames(wrapper)).toEqual(['team.png']) + }) + + it("says the load failed when the session could not move to the build's workspace, and Refresh moves it as the user's choice", async () => { + signedInToPersonalWithTeamDashboard() + listAssets.mockResolvedValue([asset('t1', 'team.png', 'image')]) + switchWorkspace.mockResolvedValueOnce({ + signedIn: true, + workspaceId: 'me', + workspaceType: 'personal', + workspaceSwitchFailure: 'retryable' + }) + const wrapper = await mountAssets([], { + builds: [teamBuild(cloudBuild('team-cloud', 'Team Cloud'))] + }) + + expect(listAssets, "the personal workspace's files are not listed").not.toHaveBeenCalled() + expect(wrapper.get('[data-testid="assets-empty"]').text()).toContain("Couldn't load assets") + + await wrapper.get('[data-testid="assets-refresh"]').trigger('click') + await flushPromises() + + expect(switchWorkspace.mock.calls).toEqual([ + ['team-b', 'restored'], + ['team-b', 'chosen'] + ]) + expect(assetNames(wrapper)).toEqual(['team.png']) + }) + + it("moves the session to a Cloud build's workspace as the user's choice when they pick the build", async () => { + signedInToPersonalWithTeamDashboard() + listAssets.mockResolvedValue([asset('t1', 'team.png', 'image')]) + const wrapper = await mountAssets([], { + builds: [ + teamBuild(localBuild('team-lab', 'Team Lab', { lastLaunchedAt: 5 })), + teamBuild(cloudBuild('team-cloud', 'Team Cloud')) + ] + }) + expect(wrapper.get('[data-testid="assets-build-picker"]').text()).toBe('Team Lab') + expect(switchWorkspace, 'a local build needs no workspace').not.toHaveBeenCalled() + + await openBuildPicker(wrapper) + await pickBuild('team-cloud') + + expect(switchWorkspace).toHaveBeenCalledExactlyOnceWith('team-b', 'chosen') + expect(assetNames(wrapper)).toEqual(['team.png']) }) it('clears the previous workspace assets while the new workspace loads', async () => { - const wrapper = await mountAssets([asset('a', 'forest.png', 'image')]) - listLocalAssets.mockReturnValueOnce(new Promise(() => {})) + listAssets.mockReturnValue(new Promise(() => {})) + const wrapper = await mountAssets([asset('a', 'forest.png', 'image')], { + builds: [localBuild('lab'), teamBuild(cloudBuild('team-cloud'))] + }) useAuthStore().status = { signedIn: true, workspaceId: 'team-b' } await flushPromises() diff --git a/src/renderer/src/panel/AssetsView.vue b/src/renderer/src/panel/AssetsView.vue index 2be6e22b9..aa0f38239 100644 --- a/src/renderer/src/panel/AssetsView.vue +++ b/src/renderer/src/panel/AssetsView.vue @@ -7,14 +7,16 @@ import { AudioLines, Box, Check, + ChevronDown, + Cloud, Copy, Download, Ellipsis, File, FolderOpen, + Laptop, LayoutGrid, LayoutDashboard, - ListFilter, RefreshCw, Search, Trash2, @@ -28,12 +30,17 @@ import MenuRadioItem from '@comfyorg/design-system/menu/MenuRadioItem' import MenuSeparator from '@comfyorg/design-system/menu/MenuSeparator' import BaseInput from '../components/ui/BaseInput.vue' import ContextMenu from '../components/ContextMenu.vue' +import SegmentedControl from '../components/ui/SegmentedControl.vue' import Tooltip from '../components/ui/Tooltip.vue' import OutputDetailDialog from './OutputDetailDialog.vue' import type { OutputDetailItem } from './OutputDetailDialog.vue' import { useModal } from '../composables/useModal' import { useAuthStore } from '../stores/authStore' +import { useDashboardScopeStore } from '../stores/dashboardScopeStore' import { useInstallationStore } from '../stores/installationStore' +import { useSessionStore } from '../stores/sessionStore' +import { isCloudBuild } from './home/homeBuild' +import { installationWorkspaceId, isInstallationInWorkspace } from '../../../shared/workspaces' import { useVirtualMasonry } from '../composables/useVirtualMasonry' import { formatBytes } from '../lib/downloadFormatters' import { formatPlaybackTime, formatRelativeFromMs } from '../lib/datetime' @@ -55,6 +62,14 @@ interface AssetMenu { type KindFilter = 'all' | AssetKind type Layout = 'masonry' | 'grid' type SortOrder = 'newest' | 'oldest' +type BuildState = 'running' | 'starting' | 'stopped' + +interface AssetBuild { + build: Installation + cloud: boolean + computer: boolean + state: BuildState +} interface Shape { width: number @@ -81,10 +96,15 @@ const PLACEHOLDER_TINT = { file: 'bg-[linear-gradient(168deg,rgb(200_211_222/0.09),rgb(255_255_255/0.02))] text-[rgb(160_166_175)]' } as const +const { installationId = '' } = defineProps<{ installationId?: string }>() + const { t } = useI18n() const modal = useModal() const authStore = useAuthStore() const installationStore = useInstallationStore() +const sessionStore = useSessionStore() +const dashboardScope = useDashboardScopeStore() +void dashboardScope.initialize() const kindFilter = ref('all') const searchQuery = ref('') @@ -94,6 +114,9 @@ const layout = useLocalStorage('comfy.desktop.assets.layout', 'masonry') const sortOrder = useLocalStorage('comfy.desktop.assets.sort', 'newest') const showName = useLocalStorage('comfy.desktop.assets.showName', true) const showDetails = useLocalStorage('comfy.desktop.assets.showDetails', true) +const savedBuildId = useLocalStorage('comfy.desktop.assets.build', '') +const pickedBuildId = ref('') +const shownBuild = ref({ id: '', context: '' }) const assets = ref([]) const scroller = useTemplateRef('scroller') @@ -103,26 +126,92 @@ let warmTimer: ReturnType | undefined const loading = ref(false) const failed = ref(false) -function isCloudBuild(inst: Installation): boolean { - return inst.sourceCategory === 'cloud' +const buildsKnown = computed( + () => + dashboardScope.initialized && + !(installationStore.loading && installationStore.installations.length === 0) +) + +function buildState(build: Installation): BuildState { + if (sessionStore.isLaunching(build.id)) return 'starting' + return sessionStore.isRunning(build.id) || isCloudBuild(build) ? 'running' : 'stopped' } -const cloudBuildId = computed(() => - authStore.isSignedIn ? (installationStore.installations.find(isCloudBuild)?.id ?? null) : null -) +function hasAssets(build: Installation): boolean { + return ( + (build.hasOutputFolder === true || isCloudBuild(build)) && + isInstallationInWorkspace(build, dashboardScope.selectedWorkspaceId) + ) +} -const kindOptions = computed(() => [ - { value: 'all' as const, label: t('assets.kind.all') }, - { value: 'image' as const, label: t('assets.kind.image') }, - { value: 'video' as const, label: t('assets.kind.video') }, - { value: '3d' as const, label: t('assets.kind.3d') }, - { value: 'audio' as const, label: t('assets.kind.audio') } -]) -const filterLabel = computed(() => - kindFilter.value === 'all' - ? t('assets.filter') - : (kindOptions.value.find((option) => option.value === kindFilter.value)?.label ?? '') +const thisComputer = computed(() => ({ + build: { + id: LOCAL_ASSETS_SOURCE, + name: t('assets.thisComputer'), + sourceLabel: '', + sourceCategory: 'local' + }, + cloud: false, + computer: true, + state: 'stopped' +})) + +const assetBuilds = computed(() => { + const builds = installationStore.installations.filter(hasAssets).map((build) => ({ + build, + cloud: isCloudBuild(build), + computer: false, + state: buildState(build) + })) + return builds.some((option) => !option.cloud) ? builds : [...builds, thisComputer.value] +}) + +function lastLaunched({ build }: AssetBuild): number { + return typeof build.lastLaunchedAt === 'number' ? build.lastLaunchedAt : -Infinity +} + +const selectionContext = computed( + () => `${authStore.isSignedIn}\n${dashboardScope.selectedWorkspaceId}` ) + +const selectedBuild = computed(() => { + if (!buildsKnown.value) return null + const builds = assetBuilds.value + const openable = builds.filter((option) => authStore.isSignedIn || !option.cloud) + const withId = (options: AssetBuild[], id: string) => + id ? options.find(({ build }) => build.id === id) : undefined + return ( + withId(builds, pickedBuildId.value) ?? + withId(builds, installationId) ?? + withId(openable, savedBuildId.value) ?? + withId( + openable, + shownBuild.value.context === selectionContext.value ? shownBuild.value.id : '' + ) ?? + openable.find((option) => !option.cloud && option.state === 'running') ?? + openable.toSorted((a, b) => lastLaunched(b) - lastLaunched(a))[0] ?? + null + ) +}) + +watch([selectedBuild, selectionContext], ([selected, context]) => { + shownBuild.value = { id: selected?.build.id ?? '', context } +}) + +function pickBuild(id: string): void { + pickedBuildId.value = id + savedBuildId.value = id +} + +function buildStatusLabel({ cloud, computer, state }: AssetBuild): string { + if (computer) return t('assets.outputFolder') + return t('assets.buildStatus', { + where: t(cloud ? 'assets.buildWhere.cloud' : 'assets.buildWhere.local'), + state: t(`assets.buildState.${state}`) + }) +} + +const kinds: KindFilter[] = ['all', 'image', 'video', '3d', 'audio'] const layoutOptions = computed(() => [ { value: 'masonry' as const, label: t('assets.layout.masonry'), icon: LayoutDashboard }, { value: 'grid' as const, label: t('assets.layout.grid'), icon: LayoutGrid } @@ -140,18 +229,36 @@ function cardKey(asset: GalleryAsset): string { return `${asset.source}:${asset.id}` } -const visibleAssets = computed(() => { +const searchedAssets = computed(() => { const query = searchQuery.value.trim().toLowerCase() - const filtered = assets.value.filter( - (asset) => - (kindFilter.value === 'all' || asset.kind === kindFilter.value) && - (!query || asset.name.toLowerCase().includes(query)) + return query + ? assets.value.filter((asset) => asset.name.toLowerCase().includes(query)) + : assets.value +}) + +const kindOptions = computed(() => + kinds.map((kind) => ({ + value: kind, + label: t(`assets.kind.${kind}`), + count: + kind === 'all' + ? searchedAssets.value.length + : searchedAssets.value.filter((asset) => asset.kind === kind).length, + testId: `assets-kind-${kind}` + })) +) + +const visibleAssets = computed(() => { + const filtered = searchedAssets.value.filter( + (asset) => kindFilter.value === 'all' || asset.kind === kindFilter.value ) const direction = sortOrder.value === 'newest' ? -1 : 1 return filtered.toSorted((a, b) => direction * (createdMs(a) - createdMs(b))) }) -const showSkeleton = computed(() => loading.value && assets.value.length === 0) +const showSkeleton = computed( + () => !selectedBuild.value || (loading.value && assets.value.length === 0) +) function assetShape(asset: AssetSummary): Shape { if (layout.value === 'grid' || asset.kind === 'audio') return WIDE @@ -223,7 +330,7 @@ const emptyState = computed(() => { if (assets.value.length > 0) { return { title: t('assets.noMatches'), body: t('assets.noMatchesHint') } } - if (!authStore.isSignedIn) { + if (!authStore.isSignedIn && selectedBuild.value?.cloud) { return { title: t('assets.signedOutTitle'), body: t('assets.signedOutBody'), @@ -237,24 +344,46 @@ const emptyState = computed(() => { }) let requestId = 0 -async function loadAssets(): Promise { +function listBuildAssets({ build, cloud, computer }: AssetBuild): Promise { + if (computer) return window.api.listLocalAssets() + return cloud ? window.api.listAssets(build.id) : window.api.listLocalAssets(build.id) +} + +async function moveSessionToWorkspaceOf(build: Installation, userAsked: boolean): Promise { + const dashboardWorkspaceId = installationWorkspaceId(build) + if (!authStore.sessionWorkspaceFor(dashboardWorkspaceId)) await authStore.fetchWorkspaces() + const workspaceId = authStore.sessionWorkspaceFor(dashboardWorkspaceId) + if (!workspaceId) throw new Error("the build's workspace is unknown") + if (authStore.status.workspaceId === workspaceId) return + const intent = userAsked || dashboardScope.takeChosenSelection() ? 'chosen' : 'restored' + await authStore.switchWorkspace(workspaceId, intent) + if (authStore.status.workspaceId !== workspaceId) throw new Error('workspace switch failed') +} + +async function loadAssets(userAsked = false): Promise { const current = ++requestId - loading.value = true + const selected = selectedBuild.value failed.value = false + if (!selected || (selected.cloud && !authStore.isSignedIn)) { + assets.value = [] + loading.value = false + return + } + loading.value = true + const source = selected.cloud ? selected.build.id : LOCAL_ASSETS_SOURCE try { - const cloudId = cloudBuildId.value - const sources = [ - { source: LOCAL_ASSETS_SOURCE, load: () => window.api.listLocalAssets() }, - ...(cloudId ? [{ source: cloudId, load: () => window.api.listAssets(cloudId) }] : []) - ] - const results = await Promise.allSettled(sources.map(({ load }) => load())) + if (selected.cloud) { + const pickedHere = selected.build.id === pickedBuildId.value + await moveSessionToWorkspaceOf(selected.build, userAsked || pickedHere) + if (current !== requestId) return + } + const listed = await listBuildAssets(selected) + if (current !== requestId) return + assets.value = listed.map((asset) => ({ ...asset, source })) + } catch { if (current !== requestId) return - assets.value = results.flatMap((result, i) => - result.status === 'fulfilled' - ? result.value.map((asset) => ({ ...asset, source: sources[i]!.source })) - : [] - ) - failed.value = assets.value.length === 0 && results.some((r) => r.status === 'rejected') + assets.value = [] + failed.value = true } finally { if (current === requestId) loading.value = false } @@ -264,14 +393,25 @@ const accountContext = computed( () => `${authStore.isSignedIn}:${authStore.status.workspaceId ?? ''}` ) -watch(accountContext, () => (assets.value = [])) +const loadKey = computed(() => { + const selected = selectedBuild.value + if (!selected) return '' + return selected.cloud ? `${selected.build.id}\n${accountContext.value}` : selected.build.id +}) watch( - () => `${cloudBuildId.value ?? ''}\n${accountContext.value}`, - () => void loadAssets(), + loadKey, + () => { + assets.value = [] + void loadAssets() + }, { immediate: true } ) +function refresh(): void { + void loadAssets(true) +} + const detailKey = ref(null) const detailIndex = computed({ @@ -466,6 +606,87 @@ function extensionOf(name: string): string { data-testid="assets-toolbar" >
+ + +
+ {{ t('assets.browseAssetsOf') }} +
+ + + + + + {{ option.build.name }} + + + + + +
+ +
- - - - - {{ option.label }} - - -
{ :revisit="appsVisits" @app-open-change="appIsOpen = $event" /> - + { const isSignedIn = computed(() => status.value.signedIn) const personalWorkspace = computed(() => workspaces.value.find(isPersonalWorkspace) ?? null) + function sessionWorkspaceFor(dashboardWorkspaceId: string): string | null { + if (!isSignedIn.value) return null + if (dashboardWorkspaceId !== PERSONAL_WORKSPACE_ID) return dashboardWorkspaceId + if (status.value.workspaceType === 'personal') return status.value.workspaceId ?? null + return personalWorkspace.value?.id ?? null + } + async function fetchBuilds(): Promise { if (!isSignedIn.value) { builds.value = [] @@ -200,6 +207,7 @@ export const useAuthStore = defineStore('auth', () => { workspaceSwitchFailure, isSignedIn, personalWorkspace, + sessionWorkspaceFor, initializeWorkspaceContext, resetWorkspaceContext, fetchStatus, diff --git a/src/renderer/src/views/ChooserView.vue b/src/renderer/src/views/ChooserView.vue index 26867ae62..658681d2a 100644 --- a/src/renderer/src/views/ChooserView.vue +++ b/src/renderer/src/views/ChooserView.vue @@ -27,7 +27,7 @@ import { openInstallManager } from '../lib/openInstallManager' import { PAGE_SPOTLIGHT_CLASS } from '../lib/pageSpotlight' import type { FilterKey } from '../composables/useInstallList' import type { CloudUserTier, Installation, ShowProgressOpts } from '../types/ipc' -import { PERSONAL_WORKSPACE_ID, isInstallationInWorkspace } from '../../../shared/workspaces' +import { isInstallationInWorkspace } from '../../../shared/workspaces' const props = withDefaults( defineProps<{ @@ -76,14 +76,9 @@ const { searchQuery, activeFilter, effectiveInstalls, visibleInstalls } = useIns defineExpose({ activeFilter }) -const selectedManagedWorkspaceId = computed(() => { - if (!authStore.isSignedIn) return null - if (dashboardScope.selectedWorkspaceId !== PERSONAL_WORKSPACE_ID) { - return dashboardScope.selectedWorkspaceId - } - if (authStore.status.workspaceType === 'personal') return authStore.status.workspaceId ?? null - return authStore.personalWorkspace?.id ?? null -}) +const selectedManagedWorkspaceId = computed(() => + authStore.sessionWorkspaceFor(dashboardScope.selectedWorkspaceId) +) let buildPrefetchGeneration = 0 watch( diff --git a/src/types/ipc.ts b/src/types/ipc.ts index 0684c9a37..0bf443e7f 100644 --- a/src/types/ipc.ts +++ b/src/types/ipc.ts @@ -121,6 +121,7 @@ export interface Installation { launchMode?: string launchArgs?: string hasConsole?: boolean + hasOutputFolder?: boolean installPath?: string status?: string lastLaunchedAt?: number @@ -1161,7 +1162,7 @@ export interface ElectronApi { signalOverlayReady(): void navigatePanel(page: DashboardPage): void listAssets(installationId: string): Promise - listLocalAssets(): Promise + listLocalAssets(installationId?: string): Promise downloadAsset(source: string, assetId: string, fileName: string): Promise revealAsset(source: string, assetId: string): Promise copyAsset(source: string, assetId: string): Promise