Skip to content

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

TypeScript

fix: close remaining desktop session review gaps

Josué8a434434ad34
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 618f2fd27..7552c9d57 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.336",
+ "version": "0.1.337",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.336",
+ "version": "0.1.337",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index e39cf27b8..38769e9a8 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.336",
+ "version": "0.1.337",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.ts
index 41e501fce..071dcf843 100644
--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts
+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts
@@ -192,7 +192,7 @@ describe('AppService invitation configuration lookup', () => {
expect(service.authClient.passwordLogin).toHaveBeenCalledWith('[email protected]', 'password123')
})
- it('keeps a saved token when startup session restore has a transient failure', async () => {
+ it('does not repeat a failed startup restore before the login screen can paint', async () => {
const configPath = await createTempConfigPath('clerum-desktop-restore-local')
await fs.writeFile(
configPath,
@@ -208,21 +208,7 @@ describe('AppService invitation configuration lookup', () => {
delete process.env.PROFILE_UI_BASE_URL
vi.resetModules()
- const [{ AppService }, { resolveEnvKey }] = await Promise.all([
- import('../appService.js'),
- import('../config.js'),
- ])
- const { bindChatStoreForUser } = await import('../chatStoreBinding.js')
-
- const me = {
- id: 'user-1',
- email: '[email protected]',
- name: null,
- picture: null,
- teamId: 'team-1',
- teamName: 'Marketing',
- role: 'member',
- }
+ const { AppService } = await import('../appService.js')
const getSessionToken = vi.fn().mockResolvedValue('stored-token')
const clearSessionToken = vi.fn().mockResolvedValue(undefined)
const service = new AppService() as unknown as {
@@ -237,7 +223,7 @@ describe('AppService invitation configuration lookup', () => {
}
service.authClient = {
- getMe: vi.fn().mockRejectedValueOnce(new Error('fetch failed')).mockResolvedValueOnce(me),
+ getMe: vi.fn().mockRejectedValue(new Error('fetch failed')),
} as never
service.tokenStore = {
getSessionToken,
@@ -253,15 +239,12 @@ describe('AppService invitation configuration lookup', () => {
expect(clearSessionToken).not.toHaveBeenCalled()
- await expect(service.getSessionState()).resolves.toMatchObject({
- authenticated: true,
- me: { email: '[email protected]' },
+ await expect(service.getSessionState()).resolves.toEqual({
+ authenticated: false,
+ me: null,
})
- expect(getSessionToken).toHaveBeenCalledTimes(2)
- expect(bindChatStoreForUser).toHaveBeenCalledWith(
- 'user-1',
- resolveEnvKey('http://127.0.0.1:8091')
- )
+ expect(getSessionToken).toHaveBeenCalledTimes(1)
+ expect(service.authClient.getMe).toHaveBeenCalledTimes(1)
} finally {
warn.mockRestore()
}
diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.ts
index 0f92dd570..b5fd929ad 100644
--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts
+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts
@@ -170,6 +170,42 @@ describe('chatStoreBinding', () => {
expect(() => requireChatStore()).toThrow(/Not authenticated/)
})
+ it('sweeps expired corrupt transcript quarantines while retaining recent recovery data', async () => {
+ const agentDir = path.join(tmpBase, ENV_A, 'user-retention', 'agent-x')
+ const legacyCorruptDir = path.join(agentDir, '.corrupt')
+ const snapshotRoot = path.join(agentDir, 'chats', '.snapshots', 'encoded-chat')
+ const oldPagedCorrupt = path.join(snapshotRoot, 'corrupt-old')
+ const recentPagedCorrupt = path.join(snapshotRoot, 'corrupt-recent')
+ const oldLegacyCorrupt = path.join(legacyCorruptDir, 'old.json')
+ const recentLegacyCorrupt = path.join(legacyCorruptDir, 'recent.json')
+ await fs.mkdir(legacyCorruptDir, { recursive: true })
+ await fs.mkdir(oldPagedCorrupt, { recursive: true })
+ await fs.mkdir(recentPagedCorrupt, { recursive: true })
+ await fs.writeFile(
+ path.join(agentDir, 'index.json'),
+ JSON.stringify({
+ version: 2,
+ chats: [],
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ })
+ )
+ await fs.writeFile(oldLegacyCorrupt, 'old legacy transcript')
+ await fs.writeFile(recentLegacyCorrupt, 'recent legacy transcript')
+ await fs.writeFile(path.join(oldPagedCorrupt, 'meta.json'), 'old paged transcript')
+ await fs.writeFile(path.join(recentPagedCorrupt, 'meta.json'), 'recent paged transcript')
+ const expiredAt = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000)
+ await fs.utimes(oldLegacyCorrupt, expiredAt, expiredAt)
+ await fs.utimes(oldPagedCorrupt, expiredAt, expiredAt)
+
+ await bindChatStoreForUser('user-retention', ENV_A)
+
+ expect(await exists(oldLegacyCorrupt)).toBe(false)
+ expect(await exists(oldPagedCorrupt)).toBe(false)
+ expect(await exists(recentLegacyCorrupt)).toBe(true)
+ expect(await exists(recentPagedCorrupt)).toBe(true)
+ })
+
// §5.2 / §7.1 — bootstrap wipes any pre-v2 (legacy schema) per-agent cache dir
// WITHIN the env-scoped user directory.
describe('legacy schema wipe on bind', () => {
diff --git a/desktop-app/src/__tests__/rpcProxyClient.test.ts b/desktop-app/src/__tests__/rpcProxyClient.test.ts
index f823f5e59..ba3130362 100644
--- a/desktop-app/src/__tests__/rpcProxyClient.test.ts
+++ b/desktop-app/src/__tests__/rpcProxyClient.test.ts
@@ -12,6 +12,26 @@ vi.mock('../config.js', () => ({
},
}))
+describe('RpcProxyClient.listSessions', () => {
+ let client: RpcProxyClient
+
+ beforeEach(() => {
+ client = new RpcProxyClient()
+ vi.restoreAllMocks()
+ })
+
+ it.each(['.', '..', 'host/name', 'host\\name'])(
+ 'rejects an unsafe host path before issuing a request: %s',
+ async hostRef => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+
+ await expect(client.listSessions('rpc-token', hostRef)).rejects.toThrow(/unsafe path segment/)
+ expect(fetchMock).not.toHaveBeenCalled()
+ }
+ )
+})
+
describe('RpcProxyClient.cancelTask', () => {
let client: RpcProxyClient
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 7af2af7b6..df0d95576 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -270,6 +270,7 @@ export class AppService {
private teamDirectoryCache: TeamDirectoryResult | null = null
private teamContextQueue: Promise<void> = Promise.resolve()
private restoreSavedSessionInFlight: Promise<SessionState> | null = null
+ private savedSessionRestoreAttemptedEnvKey: string | null = null
private logoutInProgress = false
private sessionGeneration = 0
private workflowApprovalTeamById = new Map<string, string>()
@@ -556,6 +557,7 @@ export class AppService {
const restoreGeneration = this.sessionGeneration
hydrateDesktopRuntimeConfig()
const envKey = getActiveEnvKey()
+ this.savedSessionRestoreAttemptedEnvKey = envKey
let token: string | null
try {
token = await this.tokenStore.getSessionToken(envKey)
@@ -1050,7 +1052,17 @@ export class AppService {
}
async getSessionState(): Promise<SessionState> {
- if (!this.sessionToken || !this.me) return this.restoreSavedSession()
+ if (!this.sessionToken || !this.me) {
+ if (this.restoreSavedSessionInFlight) return this.restoreSavedSession()
+ // createWindow() already performs the saved-token restore before showing
+ // the renderer. Do not immediately repeat a failed 60-second network
+ // attempt from the renderer bootstrap; a new app launch or environment
+ // selection gets a fresh attempt because its service/env key is new.
+ if (this.savedSessionRestoreAttemptedEnvKey === getActiveEnvKey()) {
+ return { authenticated: false, me: null }
+ }
+ return this.restoreSavedSession()
+ }
return { authenticated: true, me: this.me }
}
diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.ts
index 49bec7291..f5e414c16 100644
--- a/desktop-app/src/chatStoreBinding.ts
+++ b/desktop-app/src/chatStoreBinding.ts
@@ -9,6 +9,7 @@ import { ChatStore } from './chatStore.js'
*/
const SCHEMA_VERSION = 2
const PREVIOUS_PAGED_INDEX_VERSION = 3
+const CORRUPT_QUARANTINE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000
// Default base dir derived from Electron's userData path. Tests override via
// __setChatStoreBaseDirForTests to point at a tmpdir, which means the
@@ -73,6 +74,7 @@ export async function bindChatStoreForUser(userId: string, envKey: string): Prom
await maybeWipePreEnvLegacyCache(baseDir)
const userDir = join(baseDir, envKey, userId)
await maybeWipeLegacyCache(userDir)
+ await sweepExpiredCorruptQuarantines(userDir)
if (generation !== bindingGeneration) return
activeChatStore = new ChatStore(userDir)
activeUserId = userId
@@ -219,6 +221,55 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {
}
}
+/**
+ * Corrupt snapshots preserve recoverable local work, but they also retain full
+ * transcript content. Keep recent quarantines for downgrade/crash recovery and
+ * remove abandoned copies after a bounded retention window on each bind.
+ */
+async function sweepExpiredCorruptQuarantines(userDir: string, nowMs = Date.now()): Promise<void> {
+ const agentEntries = await fs.readdir(userDir, { withFileTypes: true }).catch(() => [])
+ await Promise.all(
+ agentEntries
+ .filter(entry => entry.isDirectory())
+ .map(async entry => {
+ const agentDir = join(userDir, entry.name)
+ await removeExpiredQuarantineEntries(join(agentDir, '.corrupt'), () => true, nowMs)
+
+ const snapshotRoot = join(agentDir, 'chats', '.snapshots')
+ const chatEntries = await fs.readdir(snapshotRoot, { withFileTypes: true }).catch(() => [])
+ await Promise.all(
+ chatEntries
+ .filter(chatEntry => chatEntry.isDirectory())
+ .map(chatEntry =>
+ removeExpiredQuarantineEntries(
+ join(snapshotRoot, chatEntry.name),
+ name => name.startsWith('corrupt-'),
+ nowMs
+ )
+ )
+ )
+ })
+ )
+}
+
+async function removeExpiredQuarantineEntries(
+ directory: string,
+ shouldRemove: (name: string) => boolean,
+ nowMs: number
+): Promise<void> {
+ const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => [])
+ await Promise.all(
+ entries
+ .filter(entry => shouldRemove(entry.name))
+ .map(async entry => {
+ const target = join(directory, entry.name)
+ const stat = await fs.lstat(target).catch(() => null)
+ if (!stat || nowMs - stat.mtimeMs < CORRUPT_QUARANTINE_RETENTION_MS) return
+ await fs.rm(target, { recursive: entry.isDirectory(), force: true }).catch(() => undefined)
+ })
+ )
+}
+
export function unbindChatStore(): void {
bindingGeneration += 1
bindInFlight = null
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index 67f9eef1e..09b267213 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -556,6 +556,7 @@ export class RpcProxyClient {
hostRef: string,
query: SessionsListQuery = {}
): Promise<SessionsListResult> {
+ assertSafePathSegment('hostRef', hostRef)
const requestUrl = new URL(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`))
if (query.agent) requestUrl.searchParams.set('agent', query.agent)
if (query.limit !== undefined) requestUrl.searchParams.set('limit', String(query.limit))
diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts b/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts
index aca5f5457..4acea1549 100644
--- a/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts
+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts
@@ -37,6 +37,19 @@ describe('buildMessageGroupChunks', () => {
)
})
+ it('keeps existing server-turn chunks stable when older turns are prepended', () => {
+ const before = buildMessageGroupChunks(turnGroups(5, 12))
+ const after = buildMessageGroupChunks(turnGroups(1, 12))
+ const afterByKey = new Map(after.map(chunk => [chunk.chunkKey, chunk]))
+
+ expect(before.map(chunk => chunk.chunkKey)).toEqual(['server-turns-1', 'server-turns-2'])
+ for (const chunk of before) {
+ expect(afterByKey.get(chunk.chunkKey)?.groups.map(({ group }) => group.groupKey)).toEqual(
+ chunk.groups.map(({ group }) => group.groupKey)
+ )
+ }
+ })
+
it('suffixes repeated server buckets separated by a local-only group', () => {
const local = { groupKey: 'local-message', items: [{}] }
const chunks = buildMessageGroupChunks([group(1, 'user'), local, group(2, 'assistant')])
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
index 8ff3aedff..2584ab806 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx
@@ -102,7 +102,6 @@ describe('pendingChatSelection effect', () => {
expect.objectContaining({
id: 'legacy-summary',
messageCount: 0,
- turnCount: 7,
}),
])
)
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index be3de4c87..423c55671 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -33,7 +33,6 @@ const SESSION_CATALOG_PAGE_LIMIT = 50
export interface SidebarChatEntry extends ChatMetadata {
remote?: boolean
- turnCount?: number
}
/** Cross-agent sidebar entry (dev's `latestChatSessions`): a chat plus its owning agent. */
@@ -213,7 +212,6 @@ export function useChatListController({
// instead of fabricating two messages per turn and overstating
// Activity totals when tool/system messages vary by session.
messageCount: knownServerMessageCount(s),
- turnCount: s.turnCount,
remote: true,
}))
return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)
@@ -308,7 +306,6 @@ export function useChatListController({
createdAt: s.lastActivityAt,
updatedAt: s.lastActivityAt,
messageCount: knownServerMessageCount(s),
- turnCount: s.turnCount,
}))
return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)
})
@@ -656,7 +653,6 @@ export function useChatListController({
updatedAt: session.lastActivityAt,
messageCount: knownServerMessageCount(session),
remote: true,
- turnCount: session.turnCount,
agentRef: group.agentRef,
})
}
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 840f4102a..37c76770f 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -428,26 +428,21 @@ export function useAppController() {
const refreshWorkspaceDataForRoute = useCallback(
async (route: NavItem) => {
- let cycleCatalogPromise: Promise<AccessCatalog> | null = null
- const getCycleCatalogPromise = () => {
- if (!cycleCatalogPromise) {
- cycleCatalogPromise = getCatalogRefreshPromise()
- }
- return cycleCatalogPromise
- }
-
+ // Route refreshes deliberately update only the visible section. Hidden
+ // route data remains deferred until that route becomes visible; shared
+ // menu/composer data is loaded by the post-paint bootstrap instead.
const refreshers = [
{
route: DESKTOP_ROUTES.agents,
- refresh: () => agentsData.refreshWithCatalog(getCycleCatalogPromise()),
+ refresh: () => agentsData.refreshWithCatalog(getCatalogRefreshPromise()),
},
{
route: DESKTOP_ROUTES.contexts,
- refresh: () => contextsData.refreshWithCatalog(getCycleCatalogPromise()),
+ refresh: () => contextsData.refreshWithCatalog(getCatalogRefreshPromise()),
},
{
route: DESKTOP_ROUTES.connectors,
- refresh: () => mcpServersData.refreshWithCatalog(getCycleCatalogPromise()),
+ refresh: () => mcpServersData.refreshWithCatalog(getCatalogRefreshPromise()),
},
{ route: DESKTOP_ROUTES.teams, refresh: teamsData.refresh },
{ route: DESKTOP_ROUTES.plugins, refresh: refreshWorkflowsData },
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index e99ec57b3..6e78f8eb2 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.56",
+ "version": "0.1.57",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.56",
+ "version": "0.1.57",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 0b35a6d1c..d0ca6b303 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.56",
+ "version": "0.1.57",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
index 015c8f0a4..86747ed6e 100644
--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
@@ -120,6 +120,7 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {
'/rpc/hosts/chatllm/sessions?cursor=one&cursor=two',
'/rpc/hosts/chatllm/sessions?agent=one&agent=two',
'/rpc/hosts/chatllm/sessions?agent=.',
+ '/rpc/hosts/chat%2Fllm/sessions',
])('rejects malformed session pagination before forwarding upstream: %s', async path => {
const fetchMock = vi.fn()
globalThis.fetch = fetchMock as unknown as typeof fetch
diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.ts
index 6a67906d0..e1dce1961 100644
--- a/rpc-proxy/src/routes/rpc.ts
+++ b/rpc-proxy/src/routes/rpc.ts
@@ -428,7 +428,7 @@ export function createRpcRouter(): Router {
const auth = req.auth!
const rpcAccessToken = extractAuthToken(req)
const hostRef = String(req.params.hostRef || '').trim()
- if (!hostRef) {
+ if (!isSafeUpstreamPathSegment(hostRef)) {
res.status(400).json({ error: 'hostRef is required' })
return
}
@@ -640,7 +640,7 @@ export function createRpcRouter(): Router {
const auth = req.auth!
const rpcAccessToken = extractAuthToken(req)
const hostRef = String(req.params.hostRef || '').trim()
- if (!hostRef) {
+ if (!isSafeUpstreamPathSegment(hostRef)) {
res.status(400).json({ error: 'hostRef is required' })
return
}