Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): route plugin previewable-file handoff through resolveGfsPreview (R1-H3)

Diego Zacariasec7ad71b6e52
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 5e6d5dc29..fe221a426 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -37,7 +37,7 @@ import {
import { useWindowFocusBridge } from '@hooks/useWindowFocusBridge'
import type { ChatLocalMatch } from '@lib/chatLocalSearch'
import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
-import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
+import { resolveGfsPreview } from '@lib/gfsPreview'
import {
canProcessSandboxUiDeepLinks,
resolveSandboxUiDeepLinkApp,
@@ -828,7 +828,8 @@ export function App() {
* A plugin asked to show a shared file — either through `clerum.gfs.open()` or
* by the user activating a `gfs://` link it rendered. Main has already
* resolved it with the user's session, so this only decides where it goes:
- * images get a preview over the plugin, everything else hands off to Files.
+ * an image gets an overlay OVER the plugin (kept in the plugin's context on
+ * purpose); other previewable kinds and folders route to workspace tabs.
*/
const [pluginGfsPreview, setPluginGfsPreview] = React.useState<{
gfsUri: string
@@ -839,19 +840,39 @@ export function App() {
React.useEffect(() => {
const off = window.clerum.pluginSdk?.onOpenGfsResource?.(resource => {
- const mimeType = resource.kind === 'file' ? gfsImagePreviewMimeType(resource.name) : null
- if (mimeType) {
- // The embed's WebContentsView paints above renderer DOM, so it has to be
- // hidden for the overlay to be visible at all.
+ // One detection rule for "previewable, and as what" (spec 18 §3.B.2), the
+ // same one Files uses. Only a file can be previewable; a folder always
+ // opens in the browser.
+ const preview =
+ resource.kind === 'file'
+ ? resolveGfsPreview({
+ gfsUri: resource.gfsUri,
+ name: resource.name,
+ bytes: resource.bytes ?? 0,
+ })
+ : null
+ if (preview?.kind === 'image') {
+ // An image opens as an overlay OVER the plugin, keeping the user in the
+ // plugin's context (the intended modal). The embed's WebContentsView
+ // paints above renderer DOM, so it has to be hidden for the overlay to
+ // be visible at all.
void window.clerum.sandboxUi.setVisible(false).catch(() => undefined)
setPluginGfsPreview({
- gfsUri: resource.gfsUri,
- name: resource.name,
- bytes: resource.bytes ?? 0,
- mimeType,
+ gfsUri: preview.gfsUri,
+ name: preview.name,
+ bytes: preview.bytes,
+ mimeType: preview.mimeType,
})
return
}
+ if (preview) {
+ // Other previewable kinds (markdown, video, …) open directly as a
+ // workspace preview tab. Routing them through openFilesSection would seed
+ // a files tab that immediately re-previews and unmounts, leaving a tab
+ // that jumps back to the preview whenever it is selected (R1-H3).
+ vm.openPreviewSection(preview)
+ return
+ }
// Folders and non-previewable files belong in the full browser, where the
// user gets breadcrumbs, download, and sharing. Open (or focus) a files tab
// AT this gfsUri — dedupe by path focuses the tab already showing it, or
@@ -859,7 +880,7 @@ export function App() {
vm.openFilesSection(resource.gfsUri)
})
return () => off?.()
- }, [vm.openFilesSection])
+ }, [vm.openFilesSection, vm.openPreviewSection])
// Files tab render seam (mini-spec 06 §3). Only the ACTIVE files tab mounts a
// FilesPage; it is keyed by that tab's id so switching files tabs remounts and
diff --git a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
index e7095b251..23dc0468a 100644
--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
@@ -5,16 +5,19 @@ import { useNotificationsContext } from '@contexts/NotificationsContext'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { DESKTOP_ROUTES } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
+import type { GfsPreviewResource } from '@lib/gfsPreview'
import {
activeWorkspaceTab,
createWorkspaceTabsState,
newChatTab,
openChatTab,
openFilesTab,
+ openPreviewTab,
openSettingsTab,
} from '@lib/workspaceTabs'
import { mapKindToRoute, settingsSectionForRoute } from '@lib/workspaceTabsRoute'
import { App } from '@/App'
+import { openGfsResourcePayload, resolvedFile } from '@/gfs/__fixtures__/gfsProducerFixtures'
import type { AppNotification } from '@/uiTypes'
// The universal tab store now lives inside the controller (single writer;
@@ -138,6 +141,7 @@ vi.mock('@pages/ChatPage', async () => {
vi.mock('@pages/ContextDetailsPage', () => ({ ContextDetailsPage: () => null }))
vi.mock('@pages/ContextsPage', () => ({ ContextsPage: () => null }))
vi.mock('@pages/FilesPage', () => ({ FilesPage: () => null }))
+vi.mock('@pages/FilePreviewPage', () => ({ FilePreviewPage: () => null }))
vi.mock('@pages/McpServersPage', () => ({ McpServersPage: () => null }))
vi.mock('@pages/SandboxUiPage', () => ({
SandboxUiPage: (props: NonNullable<typeof sandboxUiPageHarness.props>) => {
@@ -185,6 +189,22 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
)
forceControllerRender()
})
+ // Faithful to the real controller's openPreviewSection: open/focus a preview
+ // tab for a previewable file through the real store producer (dedupe by gfsUri).
+ const openPreviewSection = vi.fn((preview: GfsPreviewResource) => {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openPreviewTab(state, {
+ id: nextWorkspaceTabId(),
+ title: preview.name,
+ gfsUri: preview.gfsUri,
+ fileKind: preview.kind,
+ byteLength: preview.bytes,
+ ...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
+ })
+ )
+ forceControllerRender()
+ })
const showAppsPicker = vi.fn(() => {
// The picker residual is redundant when an app tab is already active.
if (controller.appsPickerActive) return
@@ -293,6 +313,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
clearAppsPicker,
activateWorkspaceChatTab: noop,
openFilesSection,
+ openPreviewSection,
lastActiveChatTabId: null,
activeChatId: null,
chatList: [],
@@ -1135,6 +1156,109 @@ describe('App files multi-instance — deep-link opens by path (mini-spec 06 §3
})
})
+// R1-H3 — a plugin handing off a PREVIEWABLE non-image file (markdown, video, …)
+// must open a PREVIEW tab directly, not a files tab seeded with that URI. The old
+// image-mime-only branch sent everything else to openFilesSection, which seeded a
+// files tab that immediately re-previewed and unmounted, leaving a tab that
+// jumped back to preview whenever selected (a loop). The handoff now runs through
+// the shared resolveGfsPreview, the same rule Files/sidebar use. Payloads are
+// derived from the real producer (`openGfsResourcePayload`); tabs are asserted on
+// the observable store (T4).
+describe('App plugin previewable handoff — routes through resolveGfsPreview (R1-H3)', () => {
+ let currentController: AppController
+ let openGfsResourceCb:
+ | ((resource: Awaited<ReturnType<typeof openGfsResourcePayload>>) => void)
+ | null
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ sidebarHarness.props = null
+ sandboxUiPageHarness.props = null
+ appHeaderHarness.props = null
+ appHeaderHarness.openNotification = null
+ openGfsResourceCb = null
+ currentController = makeController()
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ shortcuts: { onCommand: vi.fn(() => vi.fn()) },
+ app: { rendererReady: vi.fn().mockResolvedValue(undefined) },
+ sandboxUi: {
+ listApps: vi.fn().mockResolvedValue({ apps: [] }),
+ listPendingDeepLinks: vi.fn().mockResolvedValue({ links: [] }),
+ clearPendingDeepLinks: vi.fn().mockResolvedValue(undefined),
+ onDeepLink: vi.fn(() => vi.fn()),
+ setVisible: vi.fn().mockResolvedValue(undefined),
+ setBounds: vi.fn().mockResolvedValue(undefined),
+ focusActive: vi.fn().mockResolvedValue(true),
+ close: vi.fn().mockResolvedValue(undefined),
+ },
+ pluginSdk: {
+ onOpenGfsResource: vi.fn(
+ (cb: (resource: Awaited<ReturnType<typeof openGfsResourcePayload>>) => void) => {
+ openGfsResourceCb = cb
+ return vi.fn()
+ }
+ ),
+ },
+ } as unknown as Window['clerum'],
+ })
+ })
+
+ afterEach(() => {
+ cleanup()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('opens a preview tab (never a files tab) for a plugin markdown and a plugin video resource', async () => {
+ const mdPayload = await openGfsResourcePayload(
+ resolvedFile('md1', 'README.md', { gfsUri: 'gfs://main/md1' })
+ )
+ const videoPayload = await openGfsResourcePayload(
+ resolvedFile('vid1', 'demo.mp4', { gfsUri: 'gfs://main/vid1' })
+ )
+ render(<App />)
+ const previewTabs = () => currentController.workspaceTabs.tabs.filter(t => t.kind === 'preview')
+ const filesTabs = () => currentController.workspaceTabs.tabs.filter(t => t.kind === 'files')
+
+ act(() => openGfsResourceCb?.(mdPayload))
+ act(() => openGfsResourceCb?.(videoPayload))
+
+ // Observable output: one preview tab per file, tagged with its detected kind.
+ expect(previewTabs().map(t => ({ uri: t.preview?.gfsUri, kind: t.preview?.fileKind }))).toEqual(
+ [
+ { uri: 'gfs://main/md1', kind: 'markdown' },
+ { uri: 'gfs://main/vid1', kind: 'video' },
+ ]
+ )
+ // No leftover files tab seeded with a previewable URI — the R1-H3 loop.
+ expect(filesTabs()).toHaveLength(0)
+ expect(currentController.openFilesSection).not.toHaveBeenCalled()
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.preview)
+ })
+
+ it('opens a files tab (never a preview tab) for a plugin folder and a non-previewable file', async () => {
+ const folderPayload = await openGfsResourcePayload(
+ resolvedFile('dir1', 'Docs', { gfsUri: 'gfs://main/dir1', kind: 'directory' })
+ )
+ const pdfPayload = await openGfsResourcePayload(
+ resolvedFile('doc1', 'report.pdf', { gfsUri: 'gfs://main/doc1' })
+ )
+ render(<App />)
+ const previewTabs = () => currentController.workspaceTabs.tabs.filter(t => t.kind === 'preview')
+ const filesTabs = () => currentController.workspaceTabs.tabs.filter(t => t.kind === 'files')
+
+ act(() => openGfsResourceCb?.(folderPayload))
+ act(() => openGfsResourceCb?.(pdfPayload))
+
+ expect(filesTabs().map(t => t.files?.path)).toEqual(['gfs://main/dir1', 'gfs://main/doc1'])
+ expect(previewTabs()).toHaveLength(0)
+ expect(currentController.openPreviewSection).not.toHaveBeenCalled()
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.files)
+ })
+})
+
// Mini-spec 05: below the minimum panel width the drawer is SUPPRESSED (hidden,
// app takes full width) without clearing the user's open intent, so it reappears
// when the window re-widens; a MANUAL close clears the intent, so it stays gone.
diff --git a/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts b/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts
index e3cf867c0..28c4ba74f 100644
--- a/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts
+++ b/desktop-app/ui/src/gfs/__fixtures__/gfsProducerFixtures.ts
@@ -147,6 +147,37 @@ export async function downloadResult(
return structuredClone(out)
}
+// The `onOpenGfsResource` payload the plugin SDK pushes across the preload
+// boundary — bound to the renderer `.d.ts` callback arg, so a drift between what
+// the runtime emits and what the renderer expects fails this module's typecheck.
+type OpenGfsResourcePayload = Parameters<
+ Parameters<typeof window.clerum.pluginSdk.onOpenGfsResource>[0]
+>[0]
+
+/**
+ * The `onOpenGfsResource` wire payload as `pluginSdkRuntime.openGfsResource`
+ * emits it: it resolves the URI with the user's session (the real
+ * `GfsClient.resolveUri` below — envelope unwrap, the same seam `download` uses)
+ * and then projects four fields onto the wire. That runtime imports `electron`
+ * at module load, so it cannot be driven from a jsdom renderer test (the awkward
+ * case T1 anticipates); the resolve half runs through this repo's REAL producer
+ * and the runtime's four-field projection is mirrored here in ONE place —
+ * `bytes` is coerced to `null` when the resolved resource omits it, exactly as
+ * the runtime does — then structured-cloned to model the IPC boundary.
+ */
+export async function openGfsResourcePayload(
+ resource: ResolvedGfsResource
+): Promise<OpenGfsResourcePayload> {
+ const client = new GfsClient(stubTransport({ ok: true, data: resource }))
+ const resolved = await client.resolveUri(resource.gfsUri, SESSION_TOKEN)
+ return structuredClone({
+ gfsUri: resolved.gfsUri ?? resource.gfsUri,
+ name: resolved.name,
+ kind: resolved.kind,
+ bytes: typeof resolved.bytes === 'number' ? resolved.bytes : null,
+ })
+}
+
/** A `ResolvedGfsResource` for a downloadable file, for `downloadResult`. */
export function resolvedFile(
resourceId: string,