Skip to content

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

TypeScript

fix(desktop): r1-m2 bind hover leases to the shared drag gesture

M24220eeffbbc
diff --git a/desktop-app/ui/src/constants/gfsBrowser.ts b/desktop-app/ui/src/constants/gfsBrowser.ts
index 3f86d378a..17b139502 100644
--- a/desktop-app/ui/src/constants/gfsBrowser.ts
+++ b/desktop-app/ui/src/constants/gfsBrowser.ts
@@ -20,3 +20,6 @@ export const DRAG_COLD_CHECK_DEBOUNCE_MS = 150
/** At most this many NEW cold destination checks per drag; beyond it targets
* stay "checking" and receive a priority check on drop (rev-2 §4.1). */
export const DRAG_COLD_CHECK_BUDGET = 8
+
+/** Concurrent cold-hover probe chains per gesture, shared across both surfaces. */
+export const DRAG_COLD_CHECK_MAX_CONCURRENCY = 2
diff --git a/desktop-app/ui/src/gfs/__tests__/hoverBudget.test.tsx b/desktop-app/ui/src/gfs/__tests__/hoverBudget.test.tsx
new file mode 100644
index 000000000..d9ee55044
--- /dev/null
+++ b/desktop-app/ui/src/gfs/__tests__/hoverBudget.test.tsx
@@ -0,0 +1,303 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import fc from 'fast-check'
+import { DRAG_COLD_CHECK_BUDGET, DRAG_COLD_CHECK_DEBOUNCE_MS } from '@constants/gfsBrowser'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
+import { affordancesResult, heldAffordances } from '../__fixtures__/gfsProducerFixtures'
+import { useGfsDragAdjudication } from '../dragAdjudication'
+import { GfsDragSessionProvider, GfsDragSessionStore, useGfsDragSession } from '../dragSession'
+import type { GfsDropTargetFact, GfsHoverCheckLease } from '../dragSession.types'
+
+const scope = 'test:user-1:team-1'
+vi.mock('@contexts/AuthContext', () => ({
+ useAuthContext: () => ({
+ isAuthenticated: true,
+ me: { id: 'user-1', teamId: 'team-1' },
+ runtimeConfigState: { envKey: 'test' },
+ }),
+}))
+function source(id = 'source') {
+ return {
+ resourceId: id,
+ gfsUri: `gfs://main/${id}`,
+ drive: 'main',
+ kind: 'file' as const,
+ name: id,
+ parentKnown: true,
+ parentResourceId: 'parent',
+ knownAncestorIds: ['parent'],
+ origin: 'sidebar' as const,
+ scope,
+ }
+}
+function target(id: string): GfsDropTargetFact {
+ return { resourceId: id, name: id, kind: 'directory', ancestorIds: ['parent', null] }
+}
+afterEach(() => {
+ cleanup()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+async function setup(provider = true) {
+ const bits = await affordancesResult(heldAffordances(['read', 'write', 'delete']))
+ const gates = new Map<string, Promise<void>>()
+ const release = new Map<string, () => void>()
+ const affordances = vi.fn(async (id: string) => {
+ await gates.get(id)
+ return bits
+ })
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { gfs: { affordances } } })
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },
+ })
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ {provider ? <GfsDragSessionProvider>{children}</GfsDragSessionProvider> : children}
+ </QueryClientProvider>
+ )
+ const hook = renderHook(
+ () => {
+ const session = useGfsDragSession()
+ const first = useGfsDragAdjudication({ scope, drive: 'main', resolve: vi.fn() })
+ const second = useGfsDragAdjudication({ scope, drive: 'main', resolve: vi.fn() })
+ return { session, first, second }
+ },
+ { wrapper }
+ )
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+ const begin = (id = 'source', instance: 'first' | 'second' = 'first') => {
+ hook.result.current.session?.beginDrag(source(id))
+ hook.result.current[instance].beginDragSession()
+ }
+ begin()
+ const dwell = async () => {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(DRAG_COLD_CHECK_DEBOUNCE_MS)
+ })
+ }
+ const block = (id: string) => {
+ gates.set(
+ id,
+ new Promise<void>(resolve => {
+ release.set(id, resolve)
+ })
+ )
+ }
+ const complete = async (id: string) => {
+ await act(async () => {
+ release.get(id)?.()
+ })
+ }
+ return { ...hook, begin, dwell, affordances, queryClient, bits, block, complete }
+}
+
+describe('gesture-owned hover budget (R1-M2)', () => {
+ it.each([true, false])(
+ 'canceled dwells are free and the last hovered target is checked (provider=%s)',
+ async provider => {
+ const h = await setup(provider)
+ const done = vi.fn()
+ for (let i = 0; i < 20; i++)
+ h.result.current.first.scheduleColdCheck(target(`canceled-${i}`), null, done)
+ await h.dwell()
+ expect(h.affordances.mock.calls.map(call => call[0])).toEqual(['canceled-19'])
+ for (let i = 1; i < DRAG_COLD_CHECK_BUDGET; i++) {
+ h.result.current.first.scheduleColdCheck(target(`next-${i}`), null, done)
+ await h.dwell()
+ }
+ h.result.current.first.scheduleColdCheck(target('over-budget'), null, done)
+ await h.dwell()
+ expect(h.affordances).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET)
+ expect(done).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET)
+ }
+ )
+
+ it('shares eight dispatched checks across the two hook instances', async () => {
+ const h = await setup()
+ const done = vi.fn()
+ for (let i = 0; i <= DRAG_COLD_CHECK_BUDGET; i++) {
+ h.result.current[i % 2 ? 'second' : 'first'].scheduleColdCheck(
+ target(`target-${i}`),
+ null,
+ done
+ )
+ await h.dwell()
+ }
+ expect(h.affordances).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET)
+ expect(done).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET)
+ // Cached verdicts consume no budget even after all cold leases are spent.
+ h.result.current.second.scheduleColdCheck(target('target-0'), null, done)
+ await h.dwell()
+ expect(done).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET + 1)
+ expect(h.affordances).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET)
+ const decision = await h.result.current.second.adjudicateDrop(
+ { ...source(), generation: 1 },
+ target('priority-drop')
+ )
+ expect(decision.allowed).toBe(true)
+ })
+
+ it('bounds concurrent probe chains across surfaces and reuses a completed slot', async () => {
+ const h = await setup()
+ h.block('a')
+ h.block('b')
+ h.result.current.first.scheduleColdCheck(target('a'), null, vi.fn())
+ await h.dwell()
+ h.result.current.second.scheduleColdCheck(target('b'), null, vi.fn())
+ await h.dwell()
+ h.result.current.first.scheduleColdCheck(target('c'), null, vi.fn())
+ await h.dwell()
+ expect(h.affordances.mock.calls.map(call => call[0])).toEqual(['a', 'b'])
+ await h.complete('a')
+ h.result.current.first.scheduleColdCheck(target('c'), null, vi.fn())
+ await h.dwell()
+ expect(h.affordances.mock.calls.map(call => call[0])).toEqual(['a', 'b', 'c'])
+ await h.complete('b')
+ })
+
+ it.each([true, false])(
+ 'refuses an old timer without charging or painting the new gesture (warm=%s)',
+ async warm => {
+ const h = await setup()
+ const stale = vi.fn()
+ if (warm)
+ h.queryClient.setQueryData(desktopQueryKeys.gfsAffordances(scope, 'old', 'main'), h.bits)
+ h.result.current.first.scheduleColdCheck(target('old'), null, stale)
+ h.begin('new', 'second')
+ await h.dwell()
+ expect(h.affordances).not.toHaveBeenCalled()
+ expect(stale).not.toHaveBeenCalled()
+ for (let i = 0; i < DRAG_COLD_CHECK_BUDGET; i++) {
+ h.result.current.second.scheduleColdCheck(target(`new-${i}`), null, vi.fn())
+ await h.dwell()
+ }
+ expect(h.affordances).toHaveBeenCalledTimes(DRAG_COLD_CHECK_BUDGET)
+ }
+ )
+
+ it.each([true, false])('never paints or fetches after native end (warm=%s)', async warm => {
+ const h = await setup()
+ if (warm)
+ h.queryClient.setQueryData(desktopQueryKeys.gfsAffordances(scope, 'ended', 'main'), h.bits)
+ const done = vi.fn()
+ h.result.current.second.scheduleColdCheck(target('ended'), null, done)
+ h.result.current.session!.endDrag()
+ await h.dwell()
+ expect(h.affordances).not.toHaveBeenCalled()
+ expect(done).not.toHaveBeenCalled()
+ })
+
+ it('rejects stale completion before a sequential parent probe or hover paint', async () => {
+ const h = await setup()
+ h.block('a')
+ const done = vi.fn()
+ h.result.current.first.scheduleColdCheck(target('a'), 'parent', done)
+ await h.dwell()
+ expect(h.affordances).toHaveBeenCalledTimes(1)
+ h.begin('b', 'second')
+ await h.complete('a')
+ expect(h.affordances.mock.calls.map(call => call[0])).toEqual(['a'])
+ expect(done).not.toHaveBeenCalled()
+ // Late A completion cannot reduce/inflate B's in-flight ledger.
+ h.block('b1')
+ h.block('b2')
+ h.result.current.first.scheduleColdCheck(target('b1'), null, vi.fn())
+ await h.dwell()
+ h.result.current.second.scheduleColdCheck(target('b2'), null, vi.fn())
+ await h.dwell()
+ h.result.current.first.scheduleColdCheck(target('b3'), null, vi.fn())
+ await h.dwell()
+ expect(h.affordances.mock.calls.map(call => call[0])).toEqual(['a', 'b1', 'b2'])
+ await h.complete('b1')
+ await h.complete('b2')
+ })
+
+ it('does not paint a dispatched hover after native end, while drop admission stays usable', async () => {
+ const h = await setup()
+ h.block('a')
+ const done = vi.fn()
+ h.result.current.second.scheduleColdCheck(target('a'), 'parent', done)
+ await h.dwell()
+ h.result.current.session!.endDrag()
+ await h.complete('a')
+ expect(h.affordances.mock.calls.map(call => call[0])).toEqual(['a'])
+ expect(done).not.toHaveBeenCalled()
+ const decision = await h.result.current.second.adjudicateDrop(
+ { ...source(), generation: 1 },
+ target('dest')
+ )
+ expect(decision.allowed).toBe(true)
+ })
+
+ it('cancels a pending dwell when its hook unmounts', async () => {
+ const h = await setup()
+ const done = vi.fn()
+ h.result.current.first.scheduleColdCheck(target('unmounted'), null, done)
+ h.unmount()
+ await h.dwell()
+ expect(h.affordances).not.toHaveBeenCalled()
+ expect(done).not.toHaveBeenCalled()
+ })
+})
+
+describe('hover lease state invariants', () => {
+ it('enforces shared caps, lazy generation reset and idempotent late completion across arbitrary traces', () => {
+ fc.assert(
+ fc.property(
+ fc.array(
+ fc.record({
+ kind: fc.constantFrom('begin', 'end', 'invalidate', 'acquire', 'complete'),
+ value: fc.integer({ min: -1, max: 12 }),
+ }),
+ { minLength: 40, maxLength: 150 }
+ ),
+ actions => {
+ const store = new GfsDragSessionStore()
+ let generation = 0
+ let active = false
+ let dispatched = 0
+ let inFlight = 0
+ const leases: Array<{
+ generation: number
+ completed: boolean
+ lease: GfsHoverCheckLease
+ }> = []
+ for (const action of actions) {
+ if (action.kind === 'begin' || action.kind === 'invalidate') {
+ if (action.kind === 'begin') expect(store.beginDrag(source())).toBe(true)
+ else store.invalidate('authority')
+ generation += 1
+ dispatched = 0
+ inFlight = 0
+ active = action.kind === 'begin'
+ } else if (action.kind === 'end') {
+ store.endDrag()
+ active = false
+ } else if (action.kind === 'acquire') {
+ const expected = generation + Math.sign(action.value)
+ const allowed = active && expected === generation && dispatched < 8 && inFlight < 2
+ const lease = store.beginHoverCheck(expected)
+ expect(lease !== null).toBe(allowed)
+ if (lease) {
+ dispatched += 1
+ inFlight += 1
+ leases.push({ generation, completed: false, lease })
+ }
+ } else if (leases.length > 0) {
+ const entry = leases[Math.abs(action.value) % leases.length]!
+ entry.lease.complete()
+ entry.lease.complete()
+ if (!entry.completed && entry.generation === generation) inFlight -= 1
+ entry.completed = true
+ }
+ }
+ }
+ ),
+ { numRuns: 300 }
+ )
+ })
+})
diff --git a/desktop-app/ui/src/gfs/dragAdjudication.ts b/desktop-app/ui/src/gfs/dragAdjudication.ts
index d73f966e8..9328c4ea0 100644
--- a/desktop-app/ui/src/gfs/dragAdjudication.ts
+++ b/desktop-app/ui/src/gfs/dragAdjudication.ts
@@ -1,9 +1,10 @@
-import { useCallback, useRef } from 'react'
+import { useCallback, useEffect, useRef } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { decideDragAuthority, decideDragStructure } from '@clerum/gfs-interaction-policy'
-import { DRAG_COLD_CHECK_BUDGET, DRAG_COLD_CHECK_DEBOUNCE_MS } from '@constants/gfsBrowser'
+import { DRAG_COLD_CHECK_DEBOUNCE_MS } from '@constants/gfsBrowser'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { describeGfsReadError, parseHttpStatus } from '@lib/gfsGrantErrors'
+import { GfsHoverCheckBudget, useGfsDragSession } from './dragSession'
import type {
GfsDragSource,
GfsDropDecision,
@@ -85,9 +86,10 @@ function requiredProbeRejection(error: unknown): GfsDropRejection {
*/
export function useGfsDragAdjudication(deps: GfsDragAdjudicationDeps) {
const queryClient = useQueryClient()
- const coldChecksRef = useRef(0)
+ const session = useGfsDragSession()
+ const localGestureRef = useRef({ generation: 0, active: false })
+ const localBudgetRef = useRef(new GfsHoverCheckBudget())
const debounceTimerRef = useRef<number | null>(null)
- const inFlightRef = useRef(0)
const readCachedAffordances = useCallback(
(resourceId: string): HeldAffordances | null => {
@@ -159,55 +161,78 @@ export function useGfsDragAdjudication(deps: GfsDragAdjudicationDeps) {
[readCachedAffordances]
)
- /**
- * Schedule one budgeted cold check for a hovered target: at most two
- * feature requests (destination + known source parent) run concurrently
- * after the dwell debounce; over-budget stays silent (drop performs the
- * priority check). No network resolves happen on hover.
- */
+ /** A dwell belongs to its schedule-time gesture. Canceled/warm checks are
+ * free; a cold chain acquires one shared slot only when it dispatches. */
const scheduleColdCheck = useCallback(
(target: GfsDropTargetFact, sourceParentId: string | null, onComplete: () => void) => {
- if (inFlightRef.current >= 2) return
- if (coldChecksRef.current >= DRAG_COLD_CHECK_BUDGET) return
- coldChecksRef.current += 1
- inFlightRef.current += 1
+ const localGeneration = localGestureRef.current.generation
+ const expectedGeneration = session?.currentGeneration() ?? localGeneration
+ const isCurrent = () =>
+ deps.scope !== null &&
+ localGeneration === localGestureRef.current.generation &&
+ (session
+ ? session.currentGeneration() === expectedGeneration && session.matchesScope(deps.scope)
+ : localGestureRef.current.active)
if (debounceTimerRef.current !== null) window.clearTimeout(debounceTimerRef.current)
debounceTimerRef.current = window.setTimeout(() => {
debounceTimerRef.current = null
+ if (!isCurrent()) return
+ const warm =
+ readCachedAffordances(target.resourceId) !== null &&
+ (sourceParentId === null || readCachedAffordances(sourceParentId) !== null)
+ if (warm) {
+ if (isCurrent()) onComplete()
+ return
+ }
+ const lease = session
+ ? session.beginHoverCheck(expectedGeneration)
+ : localBudgetRef.current.beginCheck(
+ expectedGeneration,
+ localGestureRef.current.generation,
+ localGestureRef.current.active
+ )
+ if (!lease) return
void (async () => {
try {
+ if (!isCurrent()) return
if (readCachedAffordances(target.resourceId) === null) {
await fetchAffordances(target.resourceId, AFFORDANCES_HOVER_STALE_MS)
}
+ if (!isCurrent()) return
if (sourceParentId !== null && readCachedAffordances(sourceParentId) === null) {
await fetchAffordances(sourceParentId, AFFORDANCES_HOVER_STALE_MS)
}
- onComplete()
+ if (isCurrent()) onComplete()
} finally {
- inFlightRef.current -= 1
+ lease.complete()
}
})()
}, DRAG_COLD_CHECK_DEBOUNCE_MS)
},
- [fetchAffordances, readCachedAffordances]
+ [deps.scope, fetchAffordances, readCachedAffordances, session]
)
- /** Reset the per-drag budget (new dragstart). */
- const beginDragSession = useCallback(() => {
- coldChecksRef.current = 0
- inFlightRef.current = 0
+ const cancelHover = useCallback(() => {
if (debounceTimerRef.current !== null) {
window.clearTimeout(debounceTimerRef.current)
debounceTimerRef.current = null
}
}, [])
+ const beginDragSession = useCallback(() => {
+ localGestureRef.current = { generation: localGestureRef.current.generation + 1, active: true }
+ cancelHover()
+ }, [cancelHover])
+
const endDragSession = useCallback(() => {
- if (debounceTimerRef.current !== null) {
- window.clearTimeout(debounceTimerRef.current)
- debounceTimerRef.current = null
- }
- }, [])
+ localGestureRef.current = { generation: localGestureRef.current.generation + 1, active: false }
+ cancelHover()
+ }, [cancelHover])
+
+ useEffect(() => {
+ endDragSession()
+ return endDragSession
+ }, [deps.scope, endDragSession])
/**
* Bounded upward continuation of the target's ancestor chain (rev-2 §3.1):
diff --git a/desktop-app/ui/src/gfs/dragSession.tsx b/desktop-app/ui/src/gfs/dragSession.tsx
index e06fea4a6..7647fc117 100644
--- a/desktop-app/ui/src/gfs/dragSession.tsx
+++ b/desktop-app/ui/src/gfs/dragSession.tsx
@@ -1,11 +1,44 @@
import React, { createContext, useContext, useEffect, useMemo, useRef } from 'react'
import { useAuthContext } from '@contexts/AuthContext'
import { useQuery } from '@tanstack/react-query'
+import { DRAG_COLD_CHECK_BUDGET, DRAG_COLD_CHECK_MAX_CONCURRENCY } from '@constants/gfsBrowser'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
-import type { GfsDragSessionApi, GfsDragSource } from './dragSession.types'
+import type { GfsDragSessionApi, GfsDragSource, GfsHoverCheckLease } from './dragSession.types'
type GfsAccessState = 'active' | 'revoked'
+/** Same lease rules for shared gestures and provider-absent single-surface mode. */
+export class GfsHoverCheckBudget {
+ private ledger = { generation: -1, dispatched: 0, inFlight: 0 }
+
+ beginCheck(
+ expectedGeneration: number,
+ currentGeneration: number,
+ active: boolean
+ ): GfsHoverCheckLease | null {
+ if (!active || expectedGeneration !== currentGeneration) return null
+ if (this.ledger.generation !== currentGeneration) {
+ this.ledger = { generation: currentGeneration, dispatched: 0, inFlight: 0 }
+ }
+ const ledger = this.ledger
+ if (
+ ledger.dispatched >= DRAG_COLD_CHECK_BUDGET ||
+ ledger.inFlight >= DRAG_COLD_CHECK_MAX_CONCURRENCY
+ )
+ return null
+ ledger.dispatched += 1
+ ledger.inFlight += 1
+ let completed = false
+ return {
+ complete: () => {
+ if (completed) return
+ completed = true
+ if (this.ledger === ledger) ledger.inFlight -= 1
+ },
+ }
+ }
+}
+
/**
* Per-session drag coordinator (rev-2 §4): exactly one active in-window
* source, held in refs (dragover never re-renders the tree). The store is
@@ -21,6 +54,7 @@ export class GfsDragSessionStore implements GfsDragSessionApi {
private active: GfsDragSource | null = null
private generation = 0
private boundScope: string | null = null
+ private hoverBudget = new GfsHoverCheckBudget()
beginDrag(source: Omit<GfsDragSource, 'generation'>): boolean {
if (this.active && this.boundScope !== source.scope) return false
@@ -52,6 +86,10 @@ export class GfsDragSessionStore implements GfsDragSessionApi {
currentGeneration(): number {
return this.generation
}
+
+ beginHoverCheck(expectedGeneration: number): GfsHoverCheckLease | null {
+ return this.hoverBudget.beginCheck(expectedGeneration, this.generation, this.active !== null)
+ }
}
export type {
@@ -124,6 +162,7 @@ export function GfsDragSessionProvider({ children }: { children: React.ReactNode
matchesScope: candidate => store.matchesScope(candidate),
invalidate: reason => store.invalidate(reason),
currentGeneration: () => store.currentGeneration(),
+ beginHoverCheck: expectedGeneration => store.beginHoverCheck(expectedGeneration),
}),
[accessState, scope, store]
)
diff --git a/desktop-app/ui/src/gfs/dragSession.types.ts b/desktop-app/ui/src/gfs/dragSession.types.ts
index 0563b52e3..eba7697a8 100644
--- a/desktop-app/ui/src/gfs/dragSession.types.ts
+++ b/desktop-app/ui/src/gfs/dragSession.types.ts
@@ -79,6 +79,11 @@ export interface GfsDropRejection {
export type GfsDropDecision = GfsDropAdmission | GfsDropRejection
+/** One cold-hover chain's slot; release is idempotent and generation-bound. */
+export interface GfsHoverCheckLease {
+ complete(): void
+}
+
/** Provider API (rev-2 §4): one ephemeral source per session; no registry,
* no nonce MIME, no credentials. */
export interface GfsDragSessionApi {
@@ -91,4 +96,6 @@ export interface GfsDragSessionApi {
/** Monotonic gesture counter; lets a surface release the shared store only
* when the store still belongs to the gesture that captured it. */
currentGeneration(): number
+ /** Acquire only for a still-active captured gesture; never charge a newer one. */
+ beginHoverCheck(expectedGeneration: number): GfsHoverCheckLease | null
}