Skip to content

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

TypeScript

fix(desktop): order tied catalog rows totally and harden A/B diagnostics

Alfredo Lopez9f4e378e8afe
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index b49eb17a8..4b15d370d 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -1933,8 +1933,12 @@ export class ChatStore {
let artifactsRemoved = false
try {
// Every catalog read starts a retry pass from its own snapshot of the
- // queue, so overlapping passes reach the same tombstone. They are
- // serialized per chat; the later one finds it already dequeued and stops.
+ // queue, so overlapping passes reach the same tombstone. Retry passes
+ // are serialized per chat (`retryAgentPendingDeleteCleanups`); the later
+ // one finds it already dequeued and stops. `deleteChat` calls this
+ // outside `serializeChat`, so a catalog read racing the delete can still
+ // remove twice; the removal is idempotent (`force`) and can cost one
+ // more index save.
const index = await this.getIndex(agentRef)
const stillPending = (index.pendingChatCleanup ?? []).some(
existing =>
diff --git a/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts b/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts
index 5b3832d46..c23e181c8 100644
--- a/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts
+++ b/desktop-app/test/e2e-playwright/chat-open-ab.spec.ts
@@ -457,13 +457,19 @@ if (
// process was doing and whether macOS shows a prompt; never answer or bypass it.
const diagnoseFirstWindow = (starting: ElectronApplication): string => {
const samplePath = testInfo.outputPath(`sample-${launches}.txt`)
- execFileSync('sample', [String(starting.process().pid), '5', '-file', samplePath])
+ // A failed sample is reported in the diagnosis; it must not replace the timeout.
+ let sampleNote = `sample in ${samplePath}`
+ try {
+ execFileSync('sample', [String(starting.process().pid), '5', '-file', samplePath])
+ } catch (error) {
+ sampleNote = `sample failed (${String((error as Error)?.message ?? error)})`
+ }
const agent = spawnSync('pgrep', ['-x', 'SecurityAgent'])
if (agent.status !== 0 && agent.status !== 1)
throw new Error(`pgrep SecurityAgent failed with status ${agent.status}.`)
return agent.status === 0
- ? `KEYCHAIN_PROMPT_PENDING: SecurityAgent is running; sample in ${samplePath}`
- : `FIRST_WINDOW_TIMEOUT: no SecurityAgent process; sample in ${samplePath}`
+ ? `KEYCHAIN_PROMPT_PENDING: SecurityAgent is running; ${sampleNote}`
+ : `FIRST_WINDOW_TIMEOUT: no SecurityAgent process; ${sampleNote}`
}
// A closed build's background requests can exhaust control-api's per-minute
// limits; the next build's session restore then fails. Start each launch in
@@ -502,13 +508,14 @@ if (
app = launched.app
page = launched.page
} catch (error) {
- const diagnosis =
- starting && /firstWindow: Timeout/.test(String((error as Error)?.message))
- ? diagnoseFirstWindow(starting)
- : undefined
- await starting?.close()
- if (diagnosis) throw new Error(diagnosis, { cause: error })
- throw error
+ // The starting process is closed even when the diagnosis itself throws.
+ try {
+ if (starting && /firstWindow: Timeout/.test(String((error as Error)?.message)))
+ throw new Error(diagnoseFirstWindow(starting), { cause: error })
+ throw error
+ } finally {
+ await starting?.close()
+ }
}
launchedBuild = build
// Public process identities only: the pinned Electron, this build's code and the run's profile.
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx
index d51919ad5..e0c930f44 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.transcriptMemo.test.tsx
@@ -402,6 +402,12 @@ describe('switchToChat transcript memo (#1091 A9)', () => {
const invalidations = [
['no invalidating event (control), reopening is served from memory', 'none', false],
['a team change, reopening opens blank', 'team', true],
+ ['an environment change and restore, reopening opens blank', 'env', true],
+ [
+ 'a rerender with the same environment (control), reopening is served from memory',
+ 'env-same',
+ false,
+ ],
['a logout and login, reopening opens blank', 'logout', true],
['resetChat, reopening opens blank', 'reset', true],
['a confirmed revocation of the Host, reopening opens blank', 'revoked', true],
@@ -427,6 +433,11 @@ describe('switchToChat transcript memo (#1091 A9)', () => {
if (event === 'team') {
act(() => controller.rerender({ currentTeamId: 'team-2', chatAuthorityTeamId: 'team-2' }))
act(() => controller.rerender({ currentTeamId: 'team-1', chatAuthorityTeamId: 'team-1' }))
+ } else if (event === 'env') {
+ act(() => controller.rerender({ currentEnvironmentKey: 'env-other' }))
+ act(() => controller.rerender({ currentEnvironmentKey: 'env-test' }))
+ } else if (event === 'env-same') {
+ act(() => controller.rerender({ currentEnvironmentKey: 'env-test' }))
} else if (event === 'logout') {
act(() => controller.rerender({ isAuthenticated: false }))
act(() => controller.rerender({ isAuthenticated: true }))
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index 061ca1023..71088566b 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -1699,6 +1699,9 @@ export function useChatListController({
)
.map(session => ({ ...session, agentRef }))
seedSessionSnapshots(fsm, agentRef, sessions)
+ // Hardening: tombstones are read again inside the updater. The filter
+ // above already dropped them from `sessions`, and no test deletes a
+ // chat between that filter and this updater.
setLatestChatSessions(previous => {
if (!requestStillCurrent()) return previous
const deleted = deletedChatIdsByAgentRef.current.get(agentRef)
diff --git a/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts b/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts
index 0ec8df028..5c09e204e 100644
--- a/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts
@@ -296,6 +296,43 @@ describe('mergeByUpdatedDesc', () => {
.sort(byUpdatedDesc)
)
+ it('breaks a time tie by Host, then chat id', () => {
+ const at = '2026-10-15T10:00:00.000Z'
+ const rows = [
+ { id: 'b', agentRef: 'host-b', updatedAt: at },
+ { id: 'b', agentRef: 'host-a', updatedAt: at },
+ { id: 'a', agentRef: 'host-a', updatedAt: at },
+ ]
+ expect([...rows].sort(byUpdatedDesc).map(row => `${row.agentRef}/${row.id}`)).toEqual([
+ 'host-a/a',
+ 'host-a/b',
+ 'host-b/b',
+ ])
+ })
+
+ it('orders rows with equal times the same whichever Host arrives first', () => {
+ // Few distinct times so most rows tie; each Host's rows are unique by id.
+ const hostRowsArb = (agentRef: string) =>
+ fc
+ .uniqueArray(
+ fc.record({
+ id: fc.constantFrom(...CHAT_IDS),
+ updatedAt: fc.constantFrom('2026-10-15T10:00:00.000Z', '2026-10-15T11:00:00.000Z'),
+ }),
+ { selector: row => row.id, minLength: 1, maxLength: CHAT_IDS.length }
+ )
+ .map(rows => rows.map(row => ({ ...row, agentRef })).sort(byUpdatedDesc))
+ fc.assert(
+ fc.property(hostRowsArb('host-a'), hostRowsArb('host-b'), (hostA, hostB) => {
+ const aFirst = mergeByUpdatedDesc(hostA, hostB)
+ const bFirst = mergeByUpdatedDesc(hostB, hostA)
+ expect(bFirst).toEqual(aFirst)
+ // Witness: both Hosts' rows are present, so a tie between them was possible.
+ expect(aFirst).toHaveLength(hostA.length + hostB.length)
+ })
+ )
+ })
+
it('equals a stable sort of both sorted lists, first list first on ties', () => {
fc.assert(
fc.property(rowsArb('first'), rowsArb('second'), (first, second) => {
diff --git a/desktop-app/ui/src/lib/catalogMerge.ts b/desktop-app/ui/src/lib/catalogMerge.ts
index 544d99965..ce8f305cd 100644
--- a/desktop-app/ui/src/lib/catalogMerge.ts
+++ b/desktop-app/ui/src/lib/catalogMerge.ts
@@ -52,14 +52,30 @@ function sortableTimestamp(value: string): number {
return Number.isFinite(timestamp) ? timestamp : 0
}
-export function byUpdatedDesc(a: { updatedAt: string }, b: { updatedAt: string }): number {
- return sortableTimestamp(b.updatedAt) - sortableTimestamp(a.updatedAt)
+interface SortableCatalogRow {
+ updatedAt: string
+ agentRef?: string
+ id?: string
+}
+
+const compareText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0)
+
+/**
+ * Newest first, then by Host and chat id, so the order of rows with the same
+ * time does not depend on which Host's catalog arrived first.
+ */
+export function byUpdatedDesc(a: SortableCatalogRow, b: SortableCatalogRow): number {
+ return (
+ sortableTimestamp(b.updatedAt) - sortableTimestamp(a.updatedAt) ||
+ compareText(a.agentRef ?? '', b.agentRef ?? '') ||
+ compareText(a.id ?? '', b.id ?? '')
+ )
}
/**
- * Merges two lists already sorted by `byUpdatedDesc` in linear time. Ties keep
- * `first` ahead of `second`, the order a stable sort of `[...first, ...second]`
- * gives.
+ * Merges two lists already sorted by `byUpdatedDesc` in linear time. Rows that
+ * compare equal keep `first` ahead of `second`, the order a stable sort of
+ * `[...first, ...second]` gives.
*/
export function mergeByUpdatedDesc<T extends { updatedAt: string }>(first: T[], second: T[]): T[] {
const merged: T[] = []