Skip to content

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

TypeScript

fix(desktop): rebind the chat store after a failed team restore and pin test gaps

Alfredo Lopez13f5aa0f079a
diff --git a/desktop-app/src/__tests__/appService.chatStoreTeamHop.test.ts b/desktop-app/src/__tests__/appService.chatStoreTeamHop.test.ts
index 972519648..7d933b994 100644
--- a/desktop-app/src/__tests__/appService.chatStoreTeamHop.test.ts
+++ b/desktop-app/src/__tests__/appService.chatStoreTeamHop.test.ts
@@ -103,6 +103,121 @@ describe('chat store scope across a transient team hop', () => {
expect(await store.loadMessages('agent-1', 'c1')).toEqual([])
})
+ it('releases the home-team pin once the hop completes so the store follows the session again', async () => {
+ const service = signedInService(['team-b', 'team-a', 'team-c'])
+ const internals = service as unknown as {
+ bindCurrentChatStore(userId: string): Promise<void>
+ runWithTeamContext<T>(teamId: string, op: (token: string) => Promise<T>): Promise<T>
+ switchSessionToTeam(teamId: string): Promise<string>
+ chatStoreTeamId(): string | null
+ me: { teamId: string }
+ }
+ await internals.bindCurrentChatStore('user-1')
+
+ const during: { sessionTeam?: string; chatStoreTeam?: string | null } = {}
+ await internals.runWithTeamContext('team-b', async () => {
+ during.sessionTeam = internals.me.teamId
+ during.chatStoreTeam = internals.chatStoreTeamId()
+ })
+
+ // Liveness witness: the pin was really held during the hop (the session was on
+ // team-b while the store team stayed on team-a) and the hop restored team-a.
+ expect(during).toEqual({ sessionTeam: 'team-b', chatStoreTeam: 'team-a' })
+ expect(internals.me.teamId).toBe('team-a')
+ expect(internals.chatStoreTeamId()).toBe('team-a')
+
+ // A genuine team switch after the hop: the store team follows `me.teamId`, it
+ // is not stuck on the team the finished hop was pinned to.
+ await internals.switchSessionToTeam('team-c')
+
+ expect(internals.me.teamId).toBe('team-c')
+ expect(internals.chatStoreTeamId()).toBe('team-c')
+ expect(requireChatStore().getAuthorityScope()?.teamId).toBe('team-c')
+ expect(service.getChatDeletionFenceAuthority().authorityScope.teamId).toBe('team-c')
+ })
+
+ describe('when the switch back to the home team fails', () => {
+ type HopInternals = {
+ bindCurrentChatStore(userId: string): Promise<void>
+ runWithTeamContext<T>(teamId: string, op: (token: string) => Promise<T>): Promise<T>
+ me: { teamId: string }
+ }
+
+ /** team-a service whose auth client accepts the hop to team-b and refuses the way back. */
+ function serviceFailingToRestore(): { service: AppService; internals: HopInternals } {
+ const service = signedInService(['team-b'])
+ const authClient = (service as unknown as { authClient: { switchTeam: unknown } }).authClient
+ authClient.switchTeam = vi.fn(async (_token: string, teamId: string) => {
+ if (teamId === 'team-a') throw new Error('network down')
+ return { token: `${teamId}-token`, team: { id: teamId, name: teamId, role: 'member' } }
+ })
+ return { service, internals: service as unknown as HopInternals }
+ }
+
+ it('rebinds the store to the team the session is really on so the delete fence still matches', async () => {
+ const { service, internals } = serviceFailingToRestore()
+ await internals.bindCurrentChatStore('user-1')
+ const store = requireChatStore()
+ await store.createChat('agent-1', 'c1')
+
+ const during: { store?: string | null; fence?: string | null } = {}
+ await expect(
+ internals.runWithTeamContext('team-b', async () => {
+ during.store = store.getAuthorityScope()?.teamId
+ during.fence = service.getChatDeletionFenceAuthority().authorityScope.teamId
+ return 'done'
+ })
+ ).rejects.toThrow('network down')
+
+ // Liveness witness: the hop really happened (store and fence stayed on
+ // team-a while the operation ran) and the switch back really failed
+ // (the session is left on team-b).
+ expect(during).toEqual({ store: 'team-a', fence: 'team-a' })
+ expect(internals.me.teamId).toBe('team-b')
+ // The pin is gone and the store follows the session again.
+ const fence = service.getChatDeletionFenceAuthority()
+ expect(fence.authorityScope.teamId).toBe('team-b')
+ expect(requireChatStore().getAuthorityScope()?.teamId).toBe('team-b')
+ // A deletion authorized by that fence is accepted instead of throwing
+ // "Chat authority scope changed".
+ await requireChatStore().createChat('agent-1', 'c2')
+ await requireChatStore().deleteChat('agent-1', 'c2', fence.authorityScope)
+ expect(await requireChatStore().loadMessages('agent-1', 'c2')).toEqual([])
+ })
+
+ it('logs a failed rebind and keeps the error of the failed operation', async () => {
+ const { internals } = serviceFailingToRestore()
+ await internals.bindCurrentChatStore('user-1')
+ const realBind = internals.bindCurrentChatStore.bind(internals)
+ let hopFinished = false
+ const rebindAttempts: string[] = []
+ internals.bindCurrentChatStore = vi.fn(async (userId: string) => {
+ if (!hopFinished) return realBind(userId)
+ rebindAttempts.push(userId)
+ throw new Error('rebind exploded')
+ })
+ const errorLog = vi.spyOn(console, 'error').mockImplementation(() => undefined)
+
+ try {
+ await expect(
+ internals.runWithTeamContext('team-b', async () => {
+ hopFinished = true
+ throw new Error('operation failed')
+ })
+ ).rejects.toThrow('operation failed')
+
+ // Liveness witness: the rebind ran and failed, and it was reported.
+ expect(rebindAttempts).toEqual(['user-1'])
+ expect(errorLog).toHaveBeenCalledWith(
+ expect.stringContaining('Failed to rebind the chat store'),
+ expect.objectContaining({ message: 'rebind exploded' })
+ )
+ } finally {
+ errorLog.mockRestore()
+ }
+ })
+ })
+
it('still rebinds the store when the team changes without a restoring hop', async () => {
const service = signedInService(['team-b'])
const internals = service as unknown as {
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index c9a960279..8fdd16907 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -399,6 +399,304 @@ describe('deleteChat', () => {
})
})
+// ── deletion identity guards ─────────────────────────────────────────────────
+
+/**
+ * The store's authority scope can change while a deletion is in flight (sign-out,
+ * account or environment switch). Every `sameChatDeletionIdentity` guard inside
+ * the cleanup path exists for that window, so each test moves the scope from
+ * inside a filesystem call the cleanup is awaiting and then checks what the
+ * cleanup did NOT do afterwards. Every negative check is paired with a witness
+ * that the call which moved the scope really ran.
+ */
+describe('deleted-chat cleanup when the identity changes mid-operation', () => {
+ const FOREIGN_SCOPES = [
+ ['a different user', { ...TEAM_A_SCOPE, userId: 'user-b' }],
+ ['a different environment', { ...TEAM_A_SCOPE, environmentKey: 'env-b' }],
+ ] as const
+ const CHAT_ID = 'mid-operation-chat'
+
+ function snapshotRootPath(chatId: string): string {
+ return agentPath('chats', '.snapshots', Buffer.from(chatId, 'utf8').toString('base64url'))
+ }
+
+ async function seedChat(chatId: string): Promise<void> {
+ await store.createChat('agent-1', chatId)
+ await store.saveMessages('agent-1', chatId, [
+ { id: 'm1', role: 'user', content: 'private', timestamp: 1 },
+ ])
+ const sibling = chatSnapshotDir(chatId, 'previous', 'sibling')
+ await fs.mkdir(sibling, { recursive: true })
+ await fs.writeFile(join(sibling, 'marker'), 'sibling')
+ await expect(fs.access(chatCacheDir(chatId))).resolves.toBeUndefined()
+ await expect(fs.access(join(sibling, 'marker'))).resolves.toBeUndefined()
+ }
+
+ /** Records every `fs.rm` path and runs `afterRm` once the real removal finished. */
+ function interceptRm(afterRm: (path: string) => void): string[] {
+ const realRm = fs.rm.bind(fs)
+ const paths: string[] = []
+ vi.spyOn(fs, 'rm').mockImplementation(async (...args) => {
+ paths.push(String(args[0]))
+ await realRm(...(args as Parameters<typeof fs.rm>))
+ afterRm(String(args[0]))
+ })
+ return paths
+ }
+
+ async function expectTombstoneAndCleanupStillQueued(chatId: string): Promise<void> {
+ const index = await store.getIndex('agent-1')
+ expect(index.deletedChatTombstones).toContainEqual({
+ chatId,
+ authorityScope: TEAM_A_SCOPE,
+ })
+ expect(index.pendingChatCleanup).toContainEqual({ chatId, authorityScope: TEAM_A_SCOPE })
+ }
+
+ /** The interrupted cleanup stays resumable: the owning identity finishes it. */
+ async function expectOwningIdentityFinishesCleanup(chatId: string): Promise<void> {
+ vi.restoreAllMocks()
+ store.setAuthorityScope(TEAM_A_SCOPE)
+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE)
+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toEqual([])
+ await expect(fs.access(chatCacheDir(chatId))).rejects.toThrow()
+ await expect(fs.access(snapshotRootPath(chatId))).rejects.toThrow()
+ }
+
+ function failingRm(): void {
+ vi.spyOn(fs, 'rm').mockRejectedValue(Object.assign(new Error('denied'), { code: 'EACCES' }))
+ vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ }
+
+ type CleanupInternals = {
+ finishPendingDeleteCleanup(
+ agentRef: string,
+ tombstone: { chatId: string; authorityScope: unknown }
+ ): Promise<boolean>
+ }
+
+ it.each(FOREIGN_SCOPES)(
+ 'stops before the next removal when the identity changes to %s during one',
+ async (_label, foreign) => {
+ await seedChat(CHAT_ID)
+ const removed = interceptRm(() => store.setAuthorityScope(foreign))
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+
+ // Witness: the first removal ran (and moved the scope); none followed it.
+ expect(removed).toHaveLength(1)
+ await expect(fs.access(chatCacheDir(CHAT_ID))).resolves.toBeUndefined()
+ await expectTombstoneAndCleanupStillQueued(CHAT_ID)
+ await expectOwningIdentityFinishesCleanup(CHAT_ID)
+ }
+ )
+
+ it.each(FOREIGN_SCOPES)(
+ 'removes nothing when the identity changes to %s while the legacy quarantine is listed',
+ async (_label, foreign) => {
+ await seedChat(CHAT_ID)
+ const realReaddir = fs.readdir.bind(fs)
+ const listed: string[] = []
+ vi.spyOn(fs, 'readdir').mockImplementation(async (...args) => {
+ listed.push(String(args[0]))
+ try {
+ // The quarantine directory does not exist here: the real listing fails
+ // with ENOENT, which the cleanup treats as "nothing quarantined".
+ return await realReaddir(...(args as Parameters<typeof fs.readdir>))
+ } finally {
+ if (String(args[0]) === agentPath('.corrupt')) store.setAuthorityScope(foreign)
+ }
+ })
+ const removed = interceptRm(() => undefined)
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+
+ // Witness: the quarantine listing ran (and moved the scope) before any removal.
+ expect(listed).toContain(agentPath('.corrupt'))
+ expect(removed).toEqual([])
+ await expect(fs.access(chatCacheDir(CHAT_ID))).resolves.toBeUndefined()
+ await expectTombstoneAndCleanupStillQueued(CHAT_ID)
+ await expectOwningIdentityFinishesCleanup(CHAT_ID)
+ }
+ )
+
+ it.each(FOREIGN_SCOPES)(
+ 'leaves the snapshot siblings alone when the identity changes to %s during the last artifact removal',
+ async (_label, foreign) => {
+ await seedChat(CHAT_ID)
+ const removed = interceptRm(path => {
+ if (path === chatCacheDir(CHAT_ID)) store.setAuthorityScope(foreign)
+ })
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+
+ // Witness: the chat directory really was removed (moving the scope), and the
+ // snapshot siblings, which the cleanup removes right after it, were not.
+ expect(removed).toContain(chatCacheDir(CHAT_ID))
+ await expect(fs.access(chatCacheDir(CHAT_ID))).rejects.toThrow()
+ expect(removed).not.toContain(snapshotRootPath(CHAT_ID))
+ await expect(
+ fs.access(join(chatSnapshotDir(CHAT_ID, 'previous', 'sibling'), 'marker'))
+ ).resolves.toBeUndefined()
+ await expectTombstoneAndCleanupStillQueued(CHAT_ID)
+ await expectOwningIdentityFinishesCleanup(CHAT_ID)
+ }
+ )
+
+ it.each(FOREIGN_SCOPES)(
+ 'keeps the cleanup queued when the identity changes to %s during the snapshot sibling removal',
+ async (_label, foreign) => {
+ await seedChat(CHAT_ID)
+ const removed = interceptRm(path => {
+ if (path === snapshotRootPath(CHAT_ID)) store.setAuthorityScope(foreign)
+ })
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+
+ // Witness: every artifact removal ran, the last one moved the scope, and the
+ // pending entry was still not cleared for an identity that no longer owns it.
+ expect(removed.at(-1)).toBe(snapshotRootPath(CHAT_ID))
+ await expect(fs.access(chatCacheDir(CHAT_ID))).rejects.toThrow()
+ await expect(fs.access(snapshotRootPath(CHAT_ID))).rejects.toThrow()
+ await expectTombstoneAndCleanupStillQueued(CHAT_ID)
+ await expectOwningIdentityFinishesCleanup(CHAT_ID)
+ }
+ )
+
+ it.each(FOREIGN_SCOPES)(
+ 'does not start the cleanup when the identity changes to %s while the deletion is persisted',
+ async (_label, foreign) => {
+ await seedChat(CHAT_ID)
+ const realRename = fs.rename.bind(fs)
+ const indexRenames: string[] = []
+ vi.spyOn(fs, 'rename').mockImplementation(async (...args) => {
+ await realRename(...(args as Parameters<typeof fs.rename>))
+ if (String(args[1]) === agentPath('index.json')) {
+ indexRenames.push(String(args[1]))
+ store.setAuthorityScope(foreign)
+ }
+ })
+ const realReaddir = fs.readdir.bind(fs)
+ const listed: string[] = []
+ vi.spyOn(fs, 'readdir').mockImplementation(async (...args) => {
+ listed.push(String(args[0]))
+ return realReaddir(...(args as Parameters<typeof fs.readdir>))
+ })
+ const removed = interceptRm(() => undefined)
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+
+ // Witness: the deletion was persisted (moving the scope) before the cleanup
+ // would have listed the quarantine or removed anything.
+ expect(indexRenames.length).toBeGreaterThan(0)
+ expect(listed).not.toContain(agentPath('.corrupt'))
+ expect(removed).toEqual([])
+ await expectTombstoneAndCleanupStillQueued(CHAT_ID)
+ await expectOwningIdentityFinishesCleanup(CHAT_ID)
+ }
+ )
+
+ it.each(FOREIGN_SCOPES)(
+ "keeps another identity's pending entry for the same chat when the owner finishes (%s)",
+ async (_label, foreign) => {
+ failingRm()
+ await store.deleteChat('agent-1', 'shared-chat-id', TEAM_A_SCOPE)
+ store.setAuthorityScope(foreign)
+ await store.deleteChat('agent-1', 'shared-chat-id', foreign)
+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toEqual([
+ { chatId: 'shared-chat-id', authorityScope: TEAM_A_SCOPE },
+ { chatId: 'shared-chat-id', authorityScope: foreign },
+ ])
+ vi.restoreAllMocks()
+
+ store.setAuthorityScope(TEAM_A_SCOPE)
+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE)
+
+ // Witness: the owner's own entry was processed and cleared; the other
+ // identity's entry for the same chat id is still queued, its tombstone too.
+ const index = await store.getIndex('agent-1')
+ expect(index.pendingChatCleanup).toEqual([
+ { chatId: 'shared-chat-id', authorityScope: foreign },
+ ])
+ expect(index.deletedChatTombstones).toHaveLength(2)
+ }
+ )
+
+ it('hands only entries of the calling identity to the cleanup', async () => {
+ const foreign = { ...TEAM_A_SCOPE, userId: 'user-b' }
+ failingRm()
+ await store.deleteChat('agent-1', 'foreign-entry', TEAM_A_SCOPE)
+ store.setAuthorityScope(foreign)
+ await store.deleteChat('agent-1', 'own-entry', foreign)
+ vi.restoreAllMocks()
+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toHaveLength(2)
+ const finish = vi.spyOn(store as unknown as CleanupInternals, 'finishPendingDeleteCleanup')
+
+ await store.retryPendingDeleteCleanups(foreign)
+
+ // Witness: the retry did hand work to the cleanup (the calling identity's entry).
+ expect(finish.mock.calls.map(call => call[1].chatId)).toEqual(['own-entry'])
+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toEqual([
+ { chatId: 'foreign-entry', authorityScope: TEAM_A_SCOPE },
+ ])
+ })
+
+ it('stops the retry sweep when the identity changes to another user during it', async () => {
+ failingRm()
+ await store.deleteChat('agent-1', 'sweep-1', TEAM_A_SCOPE)
+ await store.deleteChat('agent-1', 'sweep-2', TEAM_A_SCOPE)
+ vi.restoreAllMocks()
+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toHaveLength(2)
+ const finish = vi.spyOn(store as unknown as CleanupInternals, 'finishPendingDeleteCleanup')
+ const removed = interceptRm(() =>
+ store.setAuthorityScope({ ...TEAM_A_SCOPE, userId: 'user-b' })
+ )
+
+ await store.retryPendingDeleteCleanups(TEAM_A_SCOPE)
+
+ // Witness: the first entry was handed to the cleanup and its removal moved the
+ // scope; the second entry was never handed over, and both stay queued.
+ expect(removed).toHaveLength(1)
+ expect(finish).toHaveBeenCalledTimes(1)
+ expect((await store.getIndex('agent-1')).pendingChatCleanup).toHaveLength(2)
+ })
+
+ it('records one tombstone and one pending entry when the same chat is deleted twice', async () => {
+ await seedChat(CHAT_ID)
+ failingRm()
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+ // Witness: the first deletion queued its entries before the repeat.
+ const afterFirst = await store.getIndex('agent-1')
+ expect(afterFirst.deletedChatTombstones).toHaveLength(1)
+ expect(afterFirst.pendingChatCleanup).toHaveLength(1)
+
+ await expect(store.deleteChat('agent-1', CHAT_ID, TEAM_A_SCOPE)).resolves.toEqual({
+ cleanupPending: true,
+ })
+
+ const afterSecond = await store.getIndex('agent-1')
+ expect(afterSecond.deletedChatTombstones).toEqual([
+ { chatId: CHAT_ID, authorityScope: TEAM_A_SCOPE },
+ ])
+ expect(afterSecond.pendingChatCleanup).toEqual([
+ { chatId: CHAT_ID, authorityScope: TEAM_A_SCOPE },
+ ])
+ })
+})
+
// ── tombstone durability ─────────────────────────────────────────────────────
describe('tombstone durability', () => {
diff --git a/desktop-app/src/__tests__/httpClient.upstreamErrors.test.ts b/desktop-app/src/__tests__/httpClient.upstreamErrors.test.ts
index 58a02362e..d2d0dbaf4 100644
--- a/desktop-app/src/__tests__/httpClient.upstreamErrors.test.ts
+++ b/desktop-app/src/__tests__/httpClient.upstreamErrors.test.ts
@@ -1,6 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { AuthClient } from '../authClient.js'
import { ApiError, requestJson } from '../httpClient.js'
-import { RpcProxyClient } from '../rpcProxyClient.js'
+import { RpcProxyClient, SandboxUiSessionError } from '../rpcProxyClient.js'
+import { SharedFilesClient } from '../sharedFilesClient.js'
import {
ERROR_EXCERPT_MAX_CHARS,
HOST_ACCESS_DENIED_MESSAGE,
@@ -159,6 +161,109 @@ describe('bounded upstream error excerpts', () => {
})
})
+describe('bounded upstream error excerpts at every remaining call site', () => {
+ const HUGE = 'y'.repeat(100 * 1024)
+ const BOUNDED = `${'y'.repeat(ERROR_EXCERPT_MAX_CHARS)}…`
+ const signal = () => new AbortController().signal
+
+ // Each entry drives one `boundedErrorExcerpt` call site through the public
+ // method that owns it and names the exact message it must produce.
+ const SITES: Array<[string, () => Promise<unknown>, string]> = [
+ [
+ 'RpcProxyClient.mintSandboxUiSession',
+ () => new RpcProxyClient().mintSandboxUiSession('t', 'ns', 'app'),
+ `sandbox-ui session mint failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.requestSandboxUiOauthAuthorizeUrl',
+ () => new RpcProxyClient().requestSandboxUiOauthAuthorizeUrl('t', 'ns', 'app', 'client'),
+ `sandbox-ui authorize-url request failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.requestMcpOauthAuthorizeUrl',
+ () => new RpcProxyClient().requestMcpOauthAuthorizeUrl('t', 'server'),
+ `mcp-oauth authorize-url request failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.openHostStatusStream',
+ () => new RpcProxyClient().openHostStatusStream('t', 'host', () => undefined, signal()),
+ `Host stream failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.denyToolCall',
+ () => new RpcProxyClient().denyToolCall('t', 'host', 'task', 'tool', 'reason'),
+ `Deny failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.cancelTask',
+ () => new RpcProxyClient().cancelTask('t', 'host', 'task'),
+ `cancelTask failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.downloadArtifact',
+ () => new RpcProxyClient().downloadArtifact('t', 'host', 'file.txt'),
+ `Download artifact failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.getContextBreakdown',
+ () => new RpcProxyClient().getContextBreakdown('t', 'host', 'agent', 'chat'),
+ `Get context breakdown failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'RpcProxyClient.postDesktopSession',
+ () => new RpcProxyClient().postDesktopSession('t', 'host'),
+ `Desktop session exchange failed: 500 ${BOUNDED}`,
+ ],
+ [
+ 'AuthClient.openWorkflowNotificationStream',
+ () => new AuthClient().openWorkflowNotificationStream('t', () => undefined, signal()),
+ `Notification stream failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'AuthClient.downloadWorkflowRunArtifact',
+ () => new AuthClient().downloadWorkflowRunArtifact('t', 'ns', 'flow', 'run', 'out.txt'),
+ `Download workflow artifact failed (500): ${BOUNDED}`,
+ ],
+ [
+ 'SharedFilesClient.downloadFile',
+ () => new SharedFilesClient().downloadFile('t', 'ctx', 'sfs', 'a.txt'),
+ `500 Internal Server Error: ${BOUNDED}`,
+ ],
+ ]
+
+ it.each(SITES)('bounds the upstream body in the message of %s', async (_name, call, message) => {
+ const fetchMock = stubResponse(500, 'Internal Server Error', HUGE)
+
+ const error = await call().then(
+ () => null,
+ (e: unknown) => e as Error & { status?: number; bodyText?: string; body?: string }
+ )
+
+ // Liveness witness: the request went out and the failure path really ran.
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ expect(error).toBeInstanceOf(Error)
+ // The message carries the 512-character excerpt and nothing beyond it, while the
+ // full upstream body stays on the typed error for diagnostics.
+ expect(error?.message).toBe(message)
+ expect(error?.message.length).toBeLessThan(700)
+ const fullBody = error?.bodyText ?? error?.body
+ if (fullBody !== undefined) expect(fullBody).toBe(HUGE)
+ })
+
+ it('keeps the typed status of the sandbox-ui session error while bounding its message', async () => {
+ stubResponse(500, 'Internal Server Error', HUGE)
+
+ const error = await new RpcProxyClient().mintSandboxUiSession('t', 'ns', 'app').then(
+ () => null,
+ (e: unknown) => e
+ )
+
+ expect(error).toBeInstanceOf(SandboxUiSessionError)
+ expect((error as SandboxUiSessionError).status).toBe(500)
+ expect((error as SandboxUiSessionError).body).toBe(HUGE)
+ })
+})
+
describe('upstreamErrors helpers', () => {
it('collapses whitespace, cuts at the bound with an ellipsis and defuses reserved tokens', () => {
expect(boundedErrorExcerpt(' a\n\n b\t c ')).toBe('a b c')
@@ -168,6 +273,17 @@ describe('upstreamErrors helpers', () => {
expect(defused).toBe('a host-access-revoked and host-access-DENIED here')
})
+ it('cuts exactly above the bound: 511 and 512 characters are kept, 513 gets the ellipsis', () => {
+ expect(ERROR_EXCERPT_MAX_CHARS).toBe(512)
+ const kept511 = 'q'.repeat(ERROR_EXCERPT_MAX_CHARS - 1)
+ const kept512 = 'q'.repeat(ERROR_EXCERPT_MAX_CHARS)
+ const cut513 = 'q'.repeat(ERROR_EXCERPT_MAX_CHARS + 1)
+
+ expect(boundedErrorExcerpt(kept511)).toBe(kept511)
+ expect(boundedErrorExcerpt(kept512)).toBe(kept512)
+ expect(boundedErrorExcerpt(cut513)).toBe(`${kept512}…`)
+ })
+
it('decides Host-access messages from the parsed code of a 403 only', () => {
expect(hostAccessDenialMessage(403, '{"code":"host_access_revoked"}')).toBe(
HOST_ACCESS_REVOKED_MESSAGE
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index c6289e002..e7b54a12e 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -1209,7 +1209,25 @@ export class AppService {
}
}
} finally {
- if (shouldRestore) this.chatStoreHomeTeamId = null
+ if (shouldRestore) {
+ this.chatStoreHomeTeamId = null
+ // A failed switch back leaves the session on the hop team while the
+ // store is still bound to the pinned home team. Rebind so the store
+ // scope and the delete-fence authority (both derived from
+ // chatStoreTeamId) agree again. A rebind failure is logged and never
+ // replaces the error of the operation or of the failed restore.
+ const sessionUserId = this.me?.id
+ if (sessionUserId && this.me?.teamId !== originalTeamId) {
+ try {
+ await this.bindCurrentChatStore(sessionUserId)
+ } catch (rebindError) {
+ console.error(
+ '[AppService] Failed to rebind the chat store after a failed team restore:',
+ rebindError
+ )
+ }
+ }
+ }
releaseTransientHop?.()
}
} finally {
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 0faa9f704..9e7e3198b 100644
--- a/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/catalogMerge.prop.test.ts
@@ -174,6 +174,77 @@ describe('mergeCatalogPage', () => {
)
})
+ it('orders known dates newest first with an unparseable date as the epoch (fixed oracle)', () => {
+ // The property test above checks order with the production comparator, so an
+ // inverted comparator or a different fallback for NaN passes it. This case
+ // states the expected order literally.
+ const cached: Entry[] = [
+ { id: 'jan', title: 'Jan', updatedAt: '2026-01-01T00:00:00.000Z', messageCount: 0 },
+ { id: 'invalid', title: 'Invalid', updatedAt: 'no-fecha', messageCount: 0 },
+ { id: 'pre-epoch', title: 'Pre', updatedAt: '1969-06-01T00:00:00.000Z', messageCount: 0 },
+ { id: 'mar', title: 'Mar', updatedAt: '2026-03-01T00:00:00.000Z', messageCount: 0 },
+ ]
+ const sessions: Session[] = [
+ { chatId: 'feb', title: 'Feb', lastActivityAt: '2026-02-01T00:00:00.000Z' },
+ ]
+ expect(merge(cached, sessions, {}).map(entry => entry.id)).toEqual([
+ 'mar',
+ 'feb',
+ 'jan',
+ 'invalid',
+ 'pre-epoch',
+ ])
+ })
+
+ it('names the placeholder after the cached entry id, not the reported chat id', () => {
+ // Entry and session share a key but not an id, so the two placeholder calls
+ // are distinguishable. The cached title is empty and the server has none, so
+ // the placeholder is what the entry ends up titled.
+ const calls: string[] = []
+ const merged = mergeCatalogPage<Entry, Session>({
+ cached: [
+ { id: 'cached-id', title: '', updatedAt: '2026-01-01T00:00:00.000Z', messageCount: 0 },
+ ],
+ sessions: [{ chatId: 'reported-chat-id', lastActivityAt: '2026-02-01T00:00:00.000Z' }],
+ entryKey: () => 'shared-key',
+ sessionKey: () => 'shared-key',
+ entryPendingRename: () => 'none',
+ sessionPendingRename: () => 'none',
+ placeholderFor: chatId => {
+ calls.push(chatId)
+ return `Chat ${chatId}`
+ },
+ serverOnlyEntry: (session, title) => ({
+ id: session.chatId,
+ title,
+ updatedAt: session.lastActivityAt,
+ messageCount: 0,
+ }),
+ })
+ // Liveness witness: the merge reached the placeholder path for the shared key.
+ expect(calls).toEqual(['cached-id'])
+ expect(merged.map(entry => entry.title)).toEqual(['Chat cached-id'])
+ })
+
+ it('names a server-only session placeholder after its chat id', () => {
+ const merged = mergeCatalogPage<Entry, Session>({
+ cached: [],
+ sessions: [{ chatId: 'reported-chat-id', lastActivityAt: '2026-02-01T00:00:00.000Z' }],
+ entryKey: entry => entry.id,
+ sessionKey: session => session.chatId,
+ entryPendingRename: () => 'none',
+ sessionPendingRename: () => 'none',
+ placeholderFor,
+ serverOnlyEntry: (session, title) => ({
+ id: session.chatId,
+ title,
+ updatedAt: session.lastActivityAt,
+ messageCount: 0,
+ }),
+ })
+ expect(merged.map(entry => entry.title)).toEqual(['Chat reported-chat-id'])
+ })
+
it('keeps a pending local rename over a server title (case E)', () => {
const cached: Entry[] = [
{ id: 'a', title: 'Renamed', updatedAt: '2026-09-12T00:00:00.000Z', messageCount: 3 },