From a200afb0e0dd1b263631ee5851ed38bd65eecd6b Mon Sep 17 00:00:00 2001 From: ryan-di Date: Mon, 12 Oct 2026 15:11:37 +0800 Subject: [PATCH 01/66] fix(agent): load every page of Chat history listThreads read a single page, and the server's default page is 20 threads, so Chat history showed only the 20 newest chats. It now follows the cursor at the server's maximum page size (100), sharing the page walk with listCloudWorkflows. A failed later page fails the whole refresh, as a first-page failure does. Thread-list mocks now match the page query. --- .../agentAutogrowHandWiredLinkFixture.ts | 2 +- .../fixtures/agentConversationFixture.ts | 2 +- .../fixtures/agentCrdtIdCollisionFixture.ts | 2 +- browser_tests/fixtures/agentNewChatFixture.ts | 2 +- browser_tests/fixtures/agentPanelFixture.ts | 4 +- .../fixtures/agentPromptHistoryFixture.ts | 2 +- .../fixtures/agentTurnLockFixture.ts | 2 +- .../fixtures/agentTwoSessionCrdtFixture.ts | 2 +- .../helpers/MultiAutogrowRealignHarness.ts | 2 +- browser_tests/fixtures/load3dAgentFixture.ts | 2 +- .../agentAttachmentRefRehydration.spec.ts | 2 +- .../agentCanvasBlanksDuringRunTurn.spec.ts | 2 +- .../agentCanvasLagsToolCallCompletion.spec.ts | 2 +- .../agent/agentChatHistoryTitleSync.spec.ts | 2 +- .../agentDuplicateWorkflowNameBinding.spec.ts | 2 +- ...namicComboSetWidgetSilentlyDropped.spec.ts | 2 +- .../agentGraphOpLostOnDisconnect.spec.ts | 2 +- .../agent/agentHistoryFocusesDraftTab.spec.ts | 2 +- .../agentHistoryReopensClosedWorkflow.spec.ts | 2 +- .../agentOverflowWidgetOnNodeCreate.spec.ts | 2 +- browser_tests/tests/agent/agentPanelMocks.ts | 2 +- .../tests/agent/agentReplyDrafts.spec.ts | 2 +- .../agent/agentRunApprovalConsent.spec.ts | 2 +- .../agentStaleWorkflowTabBinding.spec.ts | 2 +- .../agent/agentTemplatePlacement.spec.ts | 2 +- .../agentZeroNodesOnUnreadableSchema.spec.ts | 2 +- browser_tests/tests/agent/renameFocus.spec.ts | 2 +- .../extensions/agent/AgentPanelRoot.test.ts | 24 ++-- .../services/agent/agentRestClient.test.ts | 107 +++++++++++++++++- .../agent/services/agent/agentRestClient.ts | 88 +++++++++----- 30 files changed, 204 insertions(+), 71 deletions(-) diff --git a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts index 5a854116b18..68cd2a6402a 100644 --- a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts +++ b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts @@ -218,7 +218,7 @@ async function setUpFixture(page: Page) { 'apply' ) await hostSocket.install() - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/run-mode', (route) => diff --git a/browser_tests/fixtures/agentConversationFixture.ts b/browser_tests/fixtures/agentConversationFixture.ts index 4fce30a735a..5864b0d2460 100644 --- a/browser_tests/fixtures/agentConversationFixture.ts +++ b/browser_tests/fixtures/agentConversationFixture.ts @@ -667,7 +667,7 @@ export class AgentConversationHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts b/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts index 5c5829dc501..3a438d7506b 100644 --- a/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts +++ b/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts @@ -453,7 +453,7 @@ export class IdCollisionHarness { threads: [], pagination: { has_more: false, limit: 100, offset: 0, total: 0 } } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/fixtures/agentNewChatFixture.ts b/browser_tests/fixtures/agentNewChatFixture.ts index d1703a963ba..63de6f4b2eb 100644 --- a/browser_tests/fixtures/agentNewChatFixture.ts +++ b/browser_tests/fixtures/agentNewChatFixture.ts @@ -102,7 +102,7 @@ class AgentNewChatServer { this.recording.add(record) void record.finally(() => this.recording.delete(record)) }) - await this.page.route('**/api/agent/threads', async (route) => { + await this.page.route('**/api/agent/threads?*', async (route) => { await this.settled().catch((error: unknown) => { this.ackFailures.push(`${route.request().url()}: ${String(error)}`) }) diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index e31624e45ae..f250811e39d 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -130,7 +130,7 @@ export async function mockAgentTurnApi( await page.route('**/api/experiment/models', (route) => route.fulfill(jsonRoute([])) ) - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/run-mode', (route) => @@ -221,7 +221,7 @@ export const agentComposerPerformanceTest = await page.route('**/api/experiment/models', (route) => route.fulfill(jsonRoute([])) ) - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/run-mode', (route) => diff --git a/browser_tests/fixtures/agentPromptHistoryFixture.ts b/browser_tests/fixtures/agentPromptHistoryFixture.ts index e2807f89f00..868695a7031 100644 --- a/browser_tests/fixtures/agentPromptHistoryFixture.ts +++ b/browser_tests/fixtures/agentPromptHistoryFixture.ts @@ -54,7 +54,7 @@ export const promptHistoryTest = base.extend<{ const historyRequestThreadIds: string[] = [] let threadId = '' let historyReads = 0 - await page.route('**/api/agent/threads', (route) => { + await page.route('**/api/agent/threads?*', (route) => { const threads: AgentThreadListResponse = { threads: threadId ? [ diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 6fc191088d7..13bb6572b41 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -401,7 +401,7 @@ async function routeTurnLock( page: Page, server: TurnLockServer ): Promise { - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill( jsonRoute({ threads: [ diff --git a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts index 84b12f75aac..fb736d03df8 100644 --- a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts +++ b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts @@ -295,7 +295,7 @@ export class AgentTwoSessionCrdtHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts b/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts index 9b1b8b155a4..a6d7f56f74d 100644 --- a/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts +++ b/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts @@ -170,7 +170,7 @@ export class MultiAutogrowRealignHarness { pagination: { has_more: false, limit: 100, offset: 0, total: 0 }, threads: [] } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threadList)) ) const runModePreference: AgentRunModePreference = { diff --git a/browser_tests/fixtures/load3dAgentFixture.ts b/browser_tests/fixtures/load3dAgentFixture.ts index 283f7a1ca45..f1ca6561222 100644 --- a/browser_tests/fixtures/load3dAgentFixture.ts +++ b/browser_tests/fixtures/load3dAgentFixture.ts @@ -276,7 +276,7 @@ class Load3dAgentHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => diff --git a/browser_tests/tests/agent/agentAttachmentRefRehydration.spec.ts b/browser_tests/tests/agent/agentAttachmentRefRehydration.spec.ts index d95051f77b1..1a27d0fea80 100644 --- a/browser_tests/tests/agent/agentAttachmentRefRehydration.spec.ts +++ b/browser_tests/tests/agent/agentAttachmentRefRehydration.spec.ts @@ -154,7 +154,7 @@ test( await page.route(`**/view?filename=${BARE_DIGEST}&type=input`, (route) => route.fulfill({ path: assetPath('image64x64.webp') }) ) - await page.route('**/api/agent/threads', (route) => { + await page.route('**/api/agent/threads?*', (route) => { const listed = [ { id: attachmentThreadId, title: 'Attachment thread' }, { id: otherThreadId, title: 'Other thread' } diff --git a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts index 582a8bf3398..1fb060cb9e4 100644 --- a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts +++ b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts @@ -208,7 +208,7 @@ async function driveThroughDocReset( socket.send(JSON.stringify(frame)) } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts index 3ad0c660311..d2aadaaf7b9 100644 --- a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts +++ b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts @@ -150,7 +150,7 @@ async function driveThroughToolCallDone( socket.send(JSON.stringify(frame)) } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts b/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts index 76fd5aa55f9..57881625a0a 100644 --- a/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts +++ b/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts @@ -78,7 +78,7 @@ test.describe( test.setTimeout(60_000) let resolveThreadsRefetch: (() => void) | undefined - await page.route('**/api/agent/threads', async (route) => { + await page.route('**/api/agent/threads?*', async (route) => { await route.fulfill(jsonRoute(staleThreadList)) resolveThreadsRefetch?.() }) diff --git a/browser_tests/tests/agent/agentDuplicateWorkflowNameBinding.spec.ts b/browser_tests/tests/agent/agentDuplicateWorkflowNameBinding.spec.ts index 8eddb7c5c01..001395cdc62 100644 --- a/browser_tests/tests/agent/agentDuplicateWorkflowNameBinding.spec.ts +++ b/browser_tests/tests/agent/agentDuplicateWorkflowNameBinding.spec.ts @@ -150,7 +150,7 @@ test( ], pagination: { offset: 0, limit: 100, total: 1, has_more: false } } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/threads/*/messages', (route) => diff --git a/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts b/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts index fe8e2799849..d51bda332ed 100644 --- a/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts +++ b/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts @@ -140,7 +140,7 @@ test.describe( pagination: { has_more: false, limit: 100, offset: 0, total: 0 }, threads: [] } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threadList)) ) const runModePreference: AgentRunModePreference = { diff --git a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts index c1200065c59..4c97633ccb1 100644 --- a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts +++ b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts @@ -106,7 +106,7 @@ test.describe( socket.send(JSON.stringify(frame)) } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentHistoryFocusesDraftTab.spec.ts b/browser_tests/tests/agent/agentHistoryFocusesDraftTab.spec.ts index e77893f56ae..5884988cbc1 100644 --- a/browser_tests/tests/agent/agentHistoryFocusesDraftTab.spec.ts +++ b/browser_tests/tests/agent/agentHistoryFocusesDraftTab.spec.ts @@ -149,7 +149,7 @@ test.describe( await bootAgentApp(page, agentFlagEnabled, { beforeNavigate: async (page) => { - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts b/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts index bd8480226d4..234d7e8a54f 100644 --- a/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts +++ b/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts @@ -165,7 +165,7 @@ test.describe( // stub: the saved workflow is in the user's workflow list from boot, // but its tab is never opened. beforeNavigate: async (page) => { - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/threads/*/messages', async (route) => { diff --git a/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts b/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts index 780fb175435..bfd9ac82ece 100644 --- a/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts +++ b/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts @@ -134,7 +134,7 @@ test.describe( pagination: { has_more: false, limit: 100, offset: 0, total: 0 }, threads: [] } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threadList)) ) const runModePreference: AgentRunModePreference = { diff --git a/browser_tests/tests/agent/agentPanelMocks.ts b/browser_tests/tests/agent/agentPanelMocks.ts index 37e72f158e6..db48cd8b802 100644 --- a/browser_tests/tests/agent/agentPanelMocks.ts +++ b/browser_tests/tests/agent/agentPanelMocks.ts @@ -452,7 +452,7 @@ async function mockAgentBoot( threads: [], pagination: { offset: 0, limit: 100, total: 0, has_more: false } } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) const storedConsent: GlobalSetting = { diff --git a/browser_tests/tests/agent/agentReplyDrafts.spec.ts b/browser_tests/tests/agent/agentReplyDrafts.spec.ts index bb86019e062..86aa81b96ea 100644 --- a/browser_tests/tests/agent/agentReplyDrafts.spec.ts +++ b/browser_tests/tests/agent/agentReplyDrafts.spec.ts @@ -65,7 +65,7 @@ async function startTurn(page: Page, prompt: string): Promise { socket.send(JSON.stringify(frame)) } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts b/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts index ff662a2b37c..41b4e185b04 100644 --- a/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts +++ b/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts @@ -131,7 +131,7 @@ async function startTurn( }) return route.fulfill(jsonRoute({ status: 'answered' })) }) - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts b/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts index b6ceb8b343e..f89c7300b19 100644 --- a/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts +++ b/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts @@ -141,7 +141,7 @@ test.describe( pagination: { offset: 0, limit: 100, total: 1, has_more: false } } const posted: unknown[] = [] - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentTemplatePlacement.spec.ts b/browser_tests/tests/agent/agentTemplatePlacement.spec.ts index 7884e509e58..9bf34efbffa 100644 --- a/browser_tests/tests/agent/agentTemplatePlacement.spec.ts +++ b/browser_tests/tests/agent/agentTemplatePlacement.spec.ts @@ -259,7 +259,7 @@ class TemplatePlacementHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts index c3f0f12f8b2..1e77a4424a8 100644 --- a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts +++ b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts @@ -97,7 +97,7 @@ test.describe( socket.send(JSON.stringify(frame)) } - await page.route('**/api/agent/threads', (route) => + await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute({ threads: [] })) ) await page.route('**/api/agent/threads/*/messages', (route) => { diff --git a/browser_tests/tests/agent/renameFocus.spec.ts b/browser_tests/tests/agent/renameFocus.spec.ts index ee0f7845980..41d05c7be57 100644 --- a/browser_tests/tests/agent/renameFocus.spec.ts +++ b/browser_tests/tests/agent/renameFocus.spec.ts @@ -49,7 +49,7 @@ async function seedOneThread(page: Parameters[0]) { ] } satisfies AgentThreadListResponse - await page.route('**/agent/threads', (route) => + await page.route('**/agent/threads?*', (route) => route.fulfill(jsonRoute(response)) ) } diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 01223f01b66..e167a01b899 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -495,6 +495,11 @@ function agentThread({ } } +/** The Chat history list request, which carries a page query. */ +function isThreadListUrl(url: string): boolean { + return url.split('?')[0].endsWith('/api/agent/threads') +} + function agentThreadList( threads: AgentThreadSummary[] = [] ): AgentThreadListResponse { @@ -1914,8 +1919,7 @@ describe('AgentPanelRoot standing credits-exhausted paywall', () => { async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) - return json(200, agentThreadList()) + if (isThreadListUrl(url)) return json(200, agentThreadList()) messageBodies.push(JSON.parse(String(init?.body))) return json(202, { thread_id: 'th-1', message_id: 'm-1' }) } @@ -4379,8 +4383,7 @@ describe('AgentPanelRoot canvas draft on send', () => { async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) - return json(200, agentThreadList()) + if (isThreadListUrl(url)) return json(200, agentThreadList()) messageBodies.push(JSON.parse(String(init?.body))) return json(202, { thread_id: 'th-1', message_id: 'm-1' }) } @@ -4419,8 +4422,7 @@ describe('AgentPanelRoot canvas draft on send', () => { async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) - return json(200, agentThreadList()) + if (isThreadListUrl(url)) return json(200, agentThreadList()) messageBodies.push(JSON.parse(String(init?.body))) return json(202, { thread_id: 'th-1', message_id: 'm-1' }) } @@ -4447,7 +4449,7 @@ describe('AgentPanelRoot history', () => { async function renderWithActiveThread(): Promise { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - return url.endsWith('/api/agent/threads') + return isThreadListUrl(url) ? new Response( JSON.stringify( agentThreadList([ @@ -4664,7 +4666,7 @@ describe('AgentPanelRoot history', () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) { + if (isThreadListUrl(url)) { return new Response( JSON.stringify( agentThreadList([ @@ -4709,7 +4711,7 @@ describe('AgentPanelRoot history', () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) + if (isThreadListUrl(url)) return json( 200, agentThreadList([ @@ -4810,7 +4812,7 @@ describe('AgentPanelRoot history', () => { it('marks the restored thread as the current session', async () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - return url.endsWith('/api/agent/threads') + return isThreadListUrl(url) ? new Response('{"threads":[]}', { status: 200, headers: { 'Content-Type': 'application/json' } @@ -4840,7 +4842,7 @@ describe('AgentPanelRoot transcript copy', () => { async (loaded) => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - return url.endsWith('/api/agent/threads') + return isThreadListUrl(url) ? new Response( JSON.stringify( agentThreadList([ diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index ed5c3ea3e78..7e9b6d5108c 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -8,7 +8,10 @@ import type { AuthCredential, AuthScheme } from '@/types/authTypes' import * as authRejection from '@/platform/auth/authRejection' import { api } from '@/scripts/api' -import type { CloudWorkflowEntry } from '../../schemas/agentApiSchema' +import type { + AgentThreadSummary, + CloudWorkflowEntry +} from '../../schemas/agentApiSchema' vi.mock(import('@/scripts/api')) vi.mock(import('@/platform/telemetry/reportError')) @@ -322,6 +325,108 @@ describe('agentRestClient route + method', () => { }) }) +describe('listThreads pagination', () => { + function threadPage( + ids: string[], + hasMore: boolean, + nextCursor?: string + ): Response { + const threads: AgentThreadSummary[] = ids.map((id) => ({ + id, + title: id, + preview: '', + workflow_id: '', + status: 'active', + message_count: 1, + created_at: '2026-10-01T00:00:00Z', + updated_at: '2026-10-01T00:00:00Z', + last_message_at: '2026-10-01T00:00:00Z' + })) + return jsonResponse(200, { + threads, + pagination: { + offset: 0, + limit: 100, + total: ids.length, + has_more: hasMore, + next_cursor: nextCursor + } + }) + } + + function requestedRoutes(): string[] { + return vi.mocked(api.fetchApi).mock.calls.map(([route]) => route) + } + + it('follows next_cursor at the maximum page size until has_more is false', async () => { + respond(threadPage(['th-1', 'th-2'], true, 'next page')) + respond(threadPage(['th-3'], false)) + + const threads = await makeClient().listThreads() + + expect(requestedRoutes()).toEqual([ + '/agent/threads?limit=100', + '/agent/threads?limit=100&after=next%20page' + ]) + expect(threads.map(({ id }) => id)).toEqual(['th-1', 'th-2', 'th-3']) + expect(console.warn).not.toHaveBeenCalled() + }) + + it.for([ + { + name: 'gives no cursor', + pages: [threadPage(['th-1'], true)], + listed: ['th-1'] + }, + { + name: 'repeats a cursor it already gave', + pages: [threadPage(['th-1'], true, 'a'), threadPage(['th-2'], true, 'a')], + listed: ['th-1', 'th-2'] + } + ])( + 'keeps the threads read so far when the server $name', + async ({ pages, listed }) => { + pages.forEach(respond) + + const threads = await makeClient().listThreads() + + expect(api.fetchApi).toHaveBeenCalledTimes(pages.length) + expect(threads.map(({ id }) => id)).toEqual(listed) + expect(console.warn).toHaveBeenCalledExactlyOnceWith( + `[agent] thread list truncated at ${listed.length} entries` + ) + } + ) + + // A partial list could hide chats that an earlier full refresh showed. + it.for([ + { + name: 'an HTTP error', + fail: () => respond(jsonResponse(503, { error: 'unavailable' })), + error: { name: 'AgentApiError', status: 503 } + }, + { + name: 'a network error', + fail: () => + vi + .mocked(api.fetchApi) + .mockRejectedValueOnce(new TypeError('Failed to fetch')), + error: { name: 'TypeError' } + }, + { + name: 'a malformed body', + fail: () => respond(jsonResponse(200, { threads: [] })), + error: { name: 'ZodError' } + } + ])('rejects when a later page fails with $name', async ({ fail, error }) => { + respond(threadPage(['th-1'], true, 'page-2')) + fail() + + await expect(makeClient().listThreads()).rejects.toMatchObject(error) + expect(api.fetchApi).toHaveBeenCalledTimes(2) + }) +}) + // The one read that can tell a live version-less draft from a deleted // workflow: cloud's `GetByID` excludes soft-deleted rows but, unlike `List`, // not version-less ones. diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index eae56c0159e..6553b19d406 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -1,5 +1,6 @@ import type { AgentPostMessageRequest, + PaginationInfo, UploadImageResponse, WorkflowResponse } from '@comfyorg/ingest-types' @@ -44,7 +45,8 @@ import type { CloudWorkflowEntry } from '../../schemas/agentApiSchema' -const CLOUD_WORKFLOW_PAGE_SIZE = 100 +/** The largest page the cursor-paged list endpoints serve. */ +const LIST_PAGE_SIZE = 100 /** * PM-1658: tightens `fetchApi`'s shared 60s header deadline for the one @@ -559,6 +561,47 @@ export function createAgentRestClient() { } } + /** + * Reads every page of a cursor-paged list. Stops early, with a warning and + * `complete: false`, when the server reports more pages but gives no new + * cursor. + */ + async function listAllPages< + Page extends { pagination: PaginationInfo }, + Item + >( + operation: AgentApiOperation, + path: string, + schema: z.ZodType, + itemsOf: (page: Page) => Item[], + label: string + ): Promise<{ items: Item[]; complete: boolean }> { + const items: Item[] = [] + let hasMore: boolean + let cursor: string | undefined + const seenCursors = new Set() + do { + const after = cursor ? `&after=${encodeURIComponent(cursor)}` : '' + const page = await request( + operation, + `${path}?limit=${LIST_PAGE_SIZE}${after}`, + { method: 'GET' }, + schema + ) + items.push(...itemsOf(page)) + hasMore = page.pagination.has_more + if (hasMore) { + const nextCursor = page.pagination.next_cursor + if (!nextCursor || seenCursors.has(nextCursor)) break + seenCursors.add(nextCursor) + cursor = nextCursor + } + } while (hasMore) + if (hasMore) + console.warn(`[agent] ${label} truncated at ${items.length} entries`) + return { items, complete: !hasMore } + } + async function postMessage( threadId: string, req: PostMessageInput @@ -596,13 +639,14 @@ export function createAgentRestClient() { } async function listThreads(): Promise { - const page = await request( + const { items } = await listAllPages( 'list_threads', '/agent/threads', - { method: 'GET' }, - zAgentThreads + zAgentThreads, + (page) => page.threads, + 'thread list' ) - return page.threads + return items } async function getRunMode(): Promise { @@ -626,32 +670,14 @@ export function createAgentRestClient() { } async function listCloudWorkflows(): Promise { - const entries: CloudWorkflowEntry[] = [] - let hasMore: boolean - let cursor: string | undefined - const seenCursors = new Set() - do { - const after = cursor ? `&after=${encodeURIComponent(cursor)}` : '' - const result = await request( - 'list_cloud_workflows', - `/workflows?limit=${CLOUD_WORKFLOW_PAGE_SIZE}${after}`, - { method: 'GET' }, - zCloudWorkflowIndex - ) - entries.push(...result.data) - hasMore = result.pagination.has_more - if (hasMore) { - const nextCursor = result.pagination.next_cursor - if (!nextCursor || seenCursors.has(nextCursor)) break - seenCursors.add(nextCursor) - cursor = nextCursor - } - } while (hasMore) - if (hasMore) - console.warn( - `[agent] cloud workflow index truncated at ${entries.length} entries` - ) - return { entries, complete: !hasMore } + const { items, complete } = await listAllPages( + 'list_cloud_workflows', + '/workflows', + zCloudWorkflowIndex, + (page) => page.data, + 'cloud workflow index' + ) + return { entries: items, complete } } async function getCloudWorkflow( From 44905dfa2d6b2321fbef23b6d6c7472b3240ce92 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Mon, 12 Oct 2026 16:18:27 +0800 Subject: [PATCH 02/66] test(agent): give thread-list mocks a valid empty page Eleven thread-list mocks answered with { threads: [] } and no pagination, which the thread-list schema rejects, so those specs ran the Chat history load-error path instead of an empty history. They now return an empty page typed with the generated AgentThreadListResponse. --- .../fixtures/agentAutogrowHandWiredLinkFixture.ts | 8 +++++++- browser_tests/fixtures/agentConversationFixture.ts | 12 ++++++++++-- browser_tests/fixtures/agentTwoSessionCrdtFixture.ts | 12 ++++++++++-- browser_tests/fixtures/load3dAgentFixture.ts | 8 +++++++- .../agent/agentCanvasBlanksDuringRunTurn.spec.ts | 8 +++++++- .../agent/agentCanvasLagsToolCallCompletion.spec.ts | 12 ++++++++++-- .../tests/agent/agentGraphOpLostOnDisconnect.spec.ts | 12 ++++++++++-- browser_tests/tests/agent/agentReplyDrafts.spec.ts | 12 ++++++++++-- .../tests/agent/agentRunApprovalConsent.spec.ts | 12 ++++++++++-- .../tests/agent/agentTemplatePlacement.spec.ts | 8 +++++++- .../agent/agentZeroNodesOnUnreadableSchema.spec.ts | 12 ++++++++++-- .../extensions/agent/AgentPanelRoot.test.ts | 2 +- 12 files changed, 99 insertions(+), 19 deletions(-) diff --git a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts index 68cd2a6402a..63c166deea2 100644 --- a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts +++ b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts @@ -2,6 +2,7 @@ import type { Page } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' +import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { toNodeId } from '@/types/nodeId' @@ -219,7 +220,12 @@ async function setUpFixture(page: Page) { ) await hostSocket.install() await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/run-mode', (route) => route.fulfill(jsonRoute({ mode: 'ask_approval', credit_limit: null })) diff --git a/browser_tests/fixtures/agentConversationFixture.ts b/browser_tests/fixtures/agentConversationFixture.ts index 5864b0d2460..c9ec8c840a8 100644 --- a/browser_tests/fixtures/agentConversationFixture.ts +++ b/browser_tests/fixtures/agentConversationFixture.ts @@ -1,7 +1,10 @@ import type { Locator, Page, TestInfo } from '@playwright/test' import { expect } from '@playwright/test' import type { ApplyOutcome, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { ListAssetsResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + ListAssetsResponse +} from '@comfyorg/ingest-types' import { z } from 'zod' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -668,7 +671,12 @@ export class AgentConversationHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { const request = route.request() diff --git a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts index fb736d03df8..252e6576a77 100644 --- a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts +++ b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts @@ -3,7 +3,10 @@ import { expect } from '@playwright/test' import { z } from 'zod' import type { WidgetCatalog } from '@comfyorg/comfy-multi-player' -import type { WorkflowListResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' import enMessages from '@/locales/en/main.json' with { type: 'json' } import type { @@ -296,7 +299,12 @@ export class AgentTwoSessionCrdtHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { const request = route.request() diff --git a/browser_tests/fixtures/load3dAgentFixture.ts b/browser_tests/fixtures/load3dAgentFixture.ts index f1ca6561222..6994188e22b 100644 --- a/browser_tests/fixtures/load3dAgentFixture.ts +++ b/browser_tests/fixtures/load3dAgentFixture.ts @@ -2,6 +2,7 @@ import type { Page, Request } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' +import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { ComfyApiWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' import { @@ -277,7 +278,12 @@ class Load3dAgentHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => route.fulfill(jsonRoute([])) diff --git a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts index 1fb060cb9e4..88139f3c77a 100644 --- a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts +++ b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts @@ -3,6 +3,7 @@ import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' import type { + AgentThreadListResponse, DocResetFrame, WorkflowListResponse } from '@comfyorg/ingest-types' @@ -209,7 +210,12 @@ async function driveThroughDocReset( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts index d2aadaaf7b9..e502108866d 100644 --- a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts +++ b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts @@ -2,7 +2,10 @@ import type { Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { WorkflowListResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -151,7 +154,12 @@ async function driveThroughToolCallDone( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts index 4c97633ccb1..ca7474666bc 100644 --- a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts +++ b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts @@ -2,7 +2,10 @@ import type { WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { WorkflowListResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -107,7 +110,12 @@ test.describe( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentReplyDrafts.spec.ts b/browser_tests/tests/agent/agentReplyDrafts.spec.ts index 86aa81b96ea..6e9b9f60652 100644 --- a/browser_tests/tests/agent/agentReplyDrafts.spec.ts +++ b/browser_tests/tests/agent/agentReplyDrafts.spec.ts @@ -2,7 +2,10 @@ import type { Locator, Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { WorkflowListResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' import { zAgentAnswerRequest } from '@comfyorg/ingest-types/zod' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -66,7 +69,12 @@ async function startTurn(page: Page, prompt: string): Promise { } await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts b/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts index 41b4e185b04..78b5a901143 100644 --- a/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts +++ b/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts @@ -2,7 +2,10 @@ import type { Locator, Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { AgentRunMode } from '@comfyorg/ingest-types' +import type { + AgentRunMode, + AgentThreadListResponse +} from '@comfyorg/ingest-types' import enMessages from '@/locales/en/main.json' with { type: 'json' } import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' @@ -132,7 +135,12 @@ async function startTurn( return route.fulfill(jsonRoute({ status: 'answered' })) }) await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentTemplatePlacement.spec.ts b/browser_tests/tests/agent/agentTemplatePlacement.spec.ts index 9bf34efbffa..eabf6d7c6be 100644 --- a/browser_tests/tests/agent/agentTemplatePlacement.spec.ts +++ b/browser_tests/tests/agent/agentTemplatePlacement.spec.ts @@ -1,6 +1,7 @@ import type { Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' +import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { AgentCancelAccepted, AgentMessages, @@ -260,7 +261,12 @@ class TemplatePlacementHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts index 1e77a4424a8..4e3d8f9f7fc 100644 --- a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts +++ b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts @@ -2,7 +2,10 @@ import type { WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { WorkflowListResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -98,7 +101,12 @@ test.describe( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute({ threads: [] })) + route.fulfill( + jsonRoute({ + threads: [], + pagination: { offset: 0, limit: 100, total: 0, has_more: false } + } satisfies AgentThreadListResponse) + ) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index e167a01b899..11edaa0e682 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -4813,7 +4813,7 @@ describe('AgentPanelRoot history', () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) return isThreadListUrl(url) - ? new Response('{"threads":[]}', { + ? new Response(JSON.stringify(agentThreadList()), { status: 200, headers: { 'Content-Type': 'application/json' } }) From fef8efafa92a83eef9810c6d606266187b38282f Mon Sep 17 00:00:00 2001 From: ryan-di Date: Mon, 12 Oct 2026 16:31:52 +0800 Subject: [PATCH 03/66] fix(agent): keep Chat history when paging ends early --- .../extensions/agent/AgentPanelRoot.test.ts | 51 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 41 +++++++++------ .../composables/agent/useAgentSession.test.ts | 38 ++++++++------ .../services/agent/agentRestClient.test.ts | 8 +-- .../agent/services/agent/agentRestClient.ts | 12 +++-- 5 files changed, 113 insertions(+), 37 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 11edaa0e682..67ca0270179 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -4809,6 +4809,57 @@ describe('AgentPanelRoot history', () => { expect(useAgentChatHistoryStore().sessions).toHaveLength(0) }) + it('keeps the loaded chat list when a refresh ends before its last page', async () => { + let truncated = false + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (!isThreadListUrl(url)) return json(200, []) + if (!truncated) + return json( + 200, + agentThreadList([ + agentThread({ + id: 'th-kept', + title: 'Kept chat', + last_message_at: '2026-07-07T10:00:00Z' + }) + ]) + ) + return json(200, { + ...agentThreadList([ + agentThread({ + id: 'th-partial', + title: 'Partial chat', + last_message_at: '2026-07-07T11:00:00Z' + }) + ]), + pagination: { has_more: true, limit: 1, offset: 0, total: 2 } + }) + }) + renderWithSelectedTarget() + const history = useAgentChatHistoryStore() + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) + ) + executionErrors.showErrorOverlay.mockClear() + telemetry.trackAgentError.mockClear() + truncated = true + + await userEvent.click( + await screen.findByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + + await vi.waitFor(() => + expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) + ) + expect(telemetry.trackAgentError).toHaveBeenCalledWith( + expect.objectContaining({ error_class: 'thread_list_load_failed' }) + ) + expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) + }) + it('marks the restored thread as the current session', async () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 67f46577f11..bec2d77e261 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1399,24 +1399,35 @@ function toChatSession(thread: AgentThreadSummary): ChatSession { } } +function reportThreadListLoadFailure(error: unknown): void { + reportError(error, { + surface: 'agent', + errorType: 'agent_thread_list_load_failed' + }) + surfaceAgentError( + 'agent_api_failed', + error instanceof Error ? error.message : String(error) + ) + trackAgentError( + 'thread_list_load_failed', + 'pre_acceptance', + 'error_overlay', + { + retryable: isRetryableRequestFailure(error, false) + } + ) +} + async function refreshHistory(): Promise { try { - history.replaceAll((await listThreads()).map(toChatSession)) + const { threads, complete } = await listThreads() + if (complete) history.replaceAll(threads.map(toChatSession)) + else + reportThreadListLoadFailure( + 'Agent thread list ended before its last page' + ) } catch (error) { - reportError(error, { - surface: 'agent', - errorType: 'agent_thread_list_load_failed' - }) - surfaceAgentError( - 'agent_api_failed', - error instanceof Error ? error.message : String(error) - ) - trackAgentError( - 'thread_list_load_failed', - 'pre_acceptance', - 'error_overlay', - { retryable: isRetryableRequestFailure(error, false) } - ) + reportThreadListLoadFailure(error) } } diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index 5fe7c5c0787..58367f1106a 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -22,7 +22,6 @@ import type { AgentCancelAccepted, AgentMessages, AgentRunModePreference, - AgentThreadSummary, AgentTurnAccepted, TurnId } from '../../schemas/agentApiSchema' @@ -38,6 +37,7 @@ import { } from '../../services/agent/agentRestClient' import type { AgentRestClient, + AgentThreadListing, PostMessageInput } from '../../services/agent/agentRestClient' import { useAgentConversationStore } from '../../stores/agent/agentConversationStore' @@ -65,7 +65,9 @@ function fakeRest(overrides: Partial = {}): AgentRestClient { }) ), getMessages: vi.fn(async (): Promise => []), - listThreads: vi.fn(async (): Promise => []), + listThreads: vi.fn( + async (): Promise => ({ threads: [], complete: true }) + ), getRunMode: vi.fn( async (): Promise => ({ mode: 'auto', @@ -6265,25 +6267,29 @@ describe('thread resume (B17)', () => { it('listThreads returns the REST client thread list', async () => { const listThreads = vi.fn( - async (): Promise => [ - { - created_at: '2026-07-07T00:00:00Z', - id: 'th-9', - last_message_at: '2026-07-07T00:00:00Z', - message_count: 2, - preview: 'build a duck', - status: 'active', - title: 'build a duck', - updated_at: '2026-07-07T00:00:00Z', - workflow_id: 'wf-9' - } - ] + async (): Promise => ({ + complete: true, + threads: [ + { + created_at: '2026-07-07T00:00:00Z', + id: 'th-9', + last_message_at: '2026-07-07T00:00:00Z', + message_count: 2, + preview: 'build a duck', + status: 'active', + title: 'build a duck', + updated_at: '2026-07-07T00:00:00Z', + workflow_id: 'wf-9' + } + ] + }) ) const session = useAgentSession({ rest: fakeRest({ listThreads }), events: fakeEvents().source }) - const threads = await session.listThreads() + const { threads, complete } = await session.listThreads() + expect(complete).toBe(true) expect(threads).toHaveLength(1) expect(threads[0]).toMatchObject({ id: 'th-9', title: 'build a duck' }) }) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index 7e9b6d5108c..72a9c65f251 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -362,13 +362,14 @@ describe('listThreads pagination', () => { respond(threadPage(['th-1', 'th-2'], true, 'next page')) respond(threadPage(['th-3'], false)) - const threads = await makeClient().listThreads() + const { threads, complete } = await makeClient().listThreads() expect(requestedRoutes()).toEqual([ '/agent/threads?limit=100', '/agent/threads?limit=100&after=next%20page' ]) expect(threads.map(({ id }) => id)).toEqual(['th-1', 'th-2', 'th-3']) + expect(complete).toBe(true) expect(console.warn).not.toHaveBeenCalled() }) @@ -384,14 +385,15 @@ describe('listThreads pagination', () => { listed: ['th-1', 'th-2'] } ])( - 'keeps the threads read so far when the server $name', + 'reports an incomplete list when the server $name', async ({ pages, listed }) => { pages.forEach(respond) - const threads = await makeClient().listThreads() + const { threads, complete } = await makeClient().listThreads() expect(api.fetchApi).toHaveBeenCalledTimes(pages.length) expect(threads.map(({ id }) => id)).toEqual(listed) + expect(complete).toBe(false) expect(console.warn).toHaveBeenCalledExactlyOnceWith( `[agent] thread list truncated at ${listed.length} entries` ) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 6553b19d406..66fefe9d12a 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -178,6 +178,12 @@ export interface CloudWorkflowListing { complete: boolean } +/** The user's threads and whether pagination reached its last page. */ +export interface AgentThreadListing { + threads: AgentThreadSummary[] + complete: boolean +} + export type OpenTabsSnapshot = Pick< AgentPostMessageRequest, 'open_tabs' | 'current_tab' @@ -638,15 +644,15 @@ export function createAgentRestClient() { ) } - async function listThreads(): Promise { - const { items } = await listAllPages( + async function listThreads(): Promise { + const { items, complete } = await listAllPages( 'list_threads', '/agent/threads', zAgentThreads, (page) => page.threads, 'thread list' ) - return items + return { threads: items, complete } } async function getRunMode(): Promise { From 2f6832c9a832161639ec38616f88bc84a26de346 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 14:16:14 +0800 Subject: [PATCH 04/66] refactor(agent): remove doc comments from internal paging helpers The repository allows JSDoc only on exported APIs; LIST_PAGE_SIZE and listAllPages are module-internal. --- .../extensions/agent/services/agent/agentRestClient.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 17672086f57..cd318fab72f 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -48,7 +48,6 @@ import type { CloudWorkflowEntry } from '../../schemas/agentApiSchema' -/** The largest page the cursor-paged list endpoints serve. */ const LIST_PAGE_SIZE = 100 /** @@ -572,11 +571,6 @@ export function createAgentRestClient() { } } - /** - * Reads every page of a cursor-paged list. Stops early, with - * `complete: false`, when the server reports more pages but gives no new - * cursor. - */ async function listAllPages< Page extends { pagination: PaginationInfo }, Item From 0a6ad205e5e057ddc8dcdb4179360d1b47f8a5aa Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 15:04:22 +0800 Subject: [PATCH 05/66] fix(agent): reject the thread list when paging stops early listThreads keeps returning the thread array and now rejects with AgentThreadListIncompleteError when the server says has_more but gives no next cursor or repeats one. The error carries which of the two it was. Chat history reports it through its existing catch, so the loaded list stays and the same error overlay opens, and the telemetry marks it not retryable because a retry would get the same page. This removes AgentThreadListing and the separate string-error branch in refreshHistory. --- .../extensions/agent/AgentPanelRoot.test.ts | 49 +++++------ .../extensions/agent/AgentPanelRoot.vue | 41 ++++----- .../composables/agent/useAgentSession.test.ts | 35 +------- .../composables/agent/useAgentSession.ts | 6 +- .../services/agent/agentRestClient.test.ts | 87 +++++++------------ .../agent/services/agent/agentRestClient.ts | 51 ++++++----- 6 files changed, 103 insertions(+), 166 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 90bb03b8eaa..ee4b774b534 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5301,22 +5301,26 @@ describe('AgentPanelRoot history', () => { }) it('keeps the loaded chat list when a refresh ends before its last page', async () => { - let truncated = false - vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { - const url = String(input) - if (!isThreadListUrl(url)) return json(200, []) - if (!truncated) - return json( - 200, - agentThreadList([ - agentThread({ - id: 'th-kept', - title: 'Kept chat', - last_message_at: '2026-07-07T10:00:00Z' - }) - ]) - ) - return json(200, { + respondToFetch({}, () => json(200, [])) + respondToFetch(/\/api\/agent\/threads\?/, () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-kept', + title: 'Kept chat', + last_message_at: '2026-07-07T10:00:00Z' + }) + ]) + ) + ) + renderWithSelectedTarget() + const history = useAgentChatHistoryStore() + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) + ) + respondToFetch(/\/api\/agent\/threads\?/, () => + json(200, { ...agentThreadList([ agentThread({ id: 'th-partial', @@ -5326,15 +5330,7 @@ describe('AgentPanelRoot history', () => { ]), pagination: { has_more: true, limit: 1, offset: 0, total: 2 } }) - }) - renderWithSelectedTarget() - const history = useAgentChatHistoryStore() - await vi.waitFor(() => - expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) ) - executionErrors.showErrorOverlay.mockClear() - telemetry.trackAgentError.mockClear() - truncated = true await userEvent.click( await screen.findByRole('button', { @@ -5346,7 +5342,10 @@ describe('AgentPanelRoot history', () => { expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) ) expect(telemetry.trackAgentError).toHaveBeenCalledWith( - expect.objectContaining({ error_class: 'thread_list_load_failed' }) + expect.objectContaining({ + error_class: 'thread_list_load_failed', + retryable: false + }) ) expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) }) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 19c547353b8..ed387952f1b 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1411,35 +1411,24 @@ function toChatSession(thread: AgentThreadSummary): ChatSession { } } -function reportThreadListLoadFailure(error: unknown): void { - reportError(error, { - surface: 'agent', - errorType: 'agent_thread_list_load_failed' - }) - surfaceAgentError( - 'agent_api_failed', - error instanceof Error ? error.message : String(error) - ) - trackAgentError( - 'thread_list_load_failed', - 'pre_acceptance', - 'error_overlay', - { - retryable: isRetryableRequestFailure(error, false) - } - ) -} - async function refreshHistory(): Promise { try { - const { threads, complete } = await listThreads() - if (complete) history.replaceAll(threads.map(toChatSession)) - else - reportThreadListLoadFailure( - 'Agent thread list ended before its last page' - ) + history.replaceAll((await listThreads()).map(toChatSession)) } catch (error) { - reportThreadListLoadFailure(error) + reportError(error, { + surface: 'agent', + errorType: 'agent_thread_list_load_failed' + }) + surfaceAgentError( + 'agent_api_failed', + error instanceof Error ? error.message : String(error) + ) + trackAgentError( + 'thread_list_load_failed', + 'pre_acceptance', + 'error_overlay', + { retryable: isRetryableRequestFailure(error, false) } + ) } } diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index ffc50c89e61..28f25c09d9d 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -22,6 +22,7 @@ import type { AgentCancelAccepted, AgentMessages, AgentRunModePreference, + AgentThreadSummary, AgentTurnAccepted, TurnId } from '../../schemas/agentApiSchema' @@ -37,7 +38,6 @@ import { } from '../../services/agent/agentRestClient' import type { AgentRestClient, - AgentThreadListing, PostMessageInput } from '../../services/agent/agentRestClient' import { useAgentConversationStore } from '../../stores/agent/agentConversationStore' @@ -65,9 +65,7 @@ function fakeRest(overrides: Partial = {}): AgentRestClient { }) ), getMessages: vi.fn(async (): Promise => []), - listThreads: vi.fn( - async (): Promise => ({ threads: [], complete: true }) - ), + listThreads: vi.fn(async (): Promise => []), getRunMode: vi.fn( async (): Promise => ({ mode: 'auto', @@ -6344,35 +6342,6 @@ describe('thread resume (B17)', () => { expect(await session.loadThread('th-history')).toBe(false) }) - - it('listThreads returns the REST client thread list', async () => { - const listThreads = vi.fn( - async (): Promise => ({ - complete: true, - threads: [ - { - created_at: '2026-07-07T00:00:00Z', - id: 'th-9', - last_message_at: '2026-07-07T00:00:00Z', - message_count: 2, - preview: 'build a duck', - status: 'active', - title: 'build a duck', - updated_at: '2026-07-07T00:00:00Z', - workflow_id: 'wf-9' - } - ] - }) - ) - const session = useAgentSession({ - rest: fakeRest({ listThreads }), - events: fakeEvents().source - }) - const { threads, complete } = await session.listThreads() - expect(complete).toBe(true) - expect(threads).toHaveLength(1) - expect(threads[0]).toMatchObject({ id: 'th-9', title: 'build a duck' }) - }) }) describe('app:agent_error telemetry (TEL-8)', () => { diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index ed2c34a3615..47adbde7a31 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -38,7 +38,8 @@ import { } from '../../schemas/agentApiSchema' import { AgentApiError, - AgentResponseUnreadableError + AgentResponseUnreadableError, + AgentThreadListIncompleteError } from '../../services/agent/agentRestClient' import type { AgentRestClient, @@ -261,7 +262,8 @@ export function isRetryableRequestFailure( if (accepted) return false if ( error instanceof ZodError || - error instanceof AgentResponseUnreadableError + error instanceof AgentResponseUnreadableError || + error instanceof AgentThreadListIncompleteError ) return false if (error instanceof AgentApiError) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index 3b9d185479c..264d284434f 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -1,3 +1,4 @@ +import type { PaginationInfo } from '@comfyorg/ingest-types' import { describe, expect, it, vi } from 'vitest' import { @@ -328,8 +329,7 @@ describe('agentRestClient route + method', () => { describe('listThreads pagination', () => { function threadPage( ids: string[], - hasMore: boolean, - nextCursor?: string + { has_more, next_cursor }: Pick ): Response { const threads: AgentThreadSummary[] = ids.map((id) => ({ id, @@ -344,84 +344,57 @@ describe('listThreads pagination', () => { })) return jsonResponse(200, { threads, - pagination: { - offset: 0, - limit: 100, - total: ids.length, - has_more: hasMore, - next_cursor: nextCursor - } + pagination: { offset: 0, limit: 100, total: 0, has_more, next_cursor } }) } - function requestedRoutes(): string[] { - return vi.mocked(api.fetchApi).mock.calls.map(([route]) => route) - } - it('follows next_cursor at the maximum page size until has_more is false', async () => { - respond(threadPage(['th-1', 'th-2'], true, 'next page')) - respond(threadPage(['th-3'], false)) + respond( + threadPage(['th-1', 'th-2'], { has_more: true, next_cursor: 'next page' }) + ) + respond(threadPage(['th-3'], { has_more: false })) - const { threads, complete } = await makeClient().listThreads() + const threads = await makeClient().listThreads() - expect(requestedRoutes()).toEqual([ + expect(vi.mocked(api.fetchApi).mock.calls.map(([route]) => route)).toEqual([ '/agent/threads?limit=100', '/agent/threads?limit=100&after=next%20page' ]) expect(threads.map(({ id }) => id)).toEqual(['th-1', 'th-2', 'th-3']) - expect(complete).toBe(true) }) it.for([ { - name: 'gives no cursor', - pages: [threadPage(['th-1'], true)], - listed: ['th-1'] + reason: 'missing_cursor', + pages: () => [threadPage(['th-1'], { has_more: true })] }, { - name: 'repeats a cursor it already gave', - pages: [threadPage(['th-1'], true, 'a'), threadPage(['th-2'], true, 'a')], - listed: ['th-1', 'th-2'] + reason: 'repeated_cursor', + pages: () => [ + threadPage(['th-1'], { has_more: true, next_cursor: 'a' }), + threadPage(['th-2'], { has_more: true, next_cursor: 'a' }) + ] } ])( - 'reports an incomplete list when the server $name', - async ({ pages, listed }) => { - pages.forEach(respond) + 'rejects with $reason when paging stops before the last page', + async ({ reason, pages }) => { + pages().forEach(respond) - const { threads, complete } = await makeClient().listThreads() - - expect(api.fetchApi).toHaveBeenCalledTimes(pages.length) - expect(threads.map(({ id }) => id)).toEqual(listed) - expect(complete).toBe(false) + await expect(makeClient().listThreads()).rejects.toMatchObject({ + name: 'AgentThreadListIncompleteError', + reason + }) } ) - // A partial list could hide chats that an earlier full refresh showed. - it.for([ - { - name: 'an HTTP error', - fail: () => respond(jsonResponse(503, { error: 'unavailable' })), - error: { name: 'AgentApiError', status: 503 } - }, - { - name: 'a network error', - fail: () => - vi - .mocked(api.fetchApi) - .mockRejectedValueOnce(new TypeError('Failed to fetch')), - error: { name: 'TypeError' } - }, - { - name: 'a malformed body', - fail: () => respond(jsonResponse(200, { threads: [] })), - error: { name: 'ZodError' } - } - ])('rejects when a later page fails with $name', async ({ fail, error }) => { - respond(threadPage(['th-1'], true, 'page-2')) - fail() + it('rejects instead of returning a partial list when a later page fails', async () => { + respond(threadPage(['th-1'], { has_more: true, next_cursor: 'page-2' })) + respond(jsonResponse(503, { error: 'unavailable' })) - await expect(makeClient().listThreads()).rejects.toMatchObject(error) - expect(api.fetchApi).toHaveBeenCalledTimes(2) + await expect(makeClient().listThreads()).rejects.toMatchObject({ + name: 'AgentApiError', + status: 503 + }) }) }) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index cd318fab72f..623e3f5ce51 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -168,18 +168,25 @@ export class AgentResponseUnreadableError extends Error { } } +type PaginationStop = 'missing_cursor' | 'repeated_cursor' + +/** The thread list's pagination stopped before its last page. */ +export class AgentThreadListIncompleteError extends Error { + readonly reason: PaginationStop + + constructor(reason: PaginationStop) { + super('Agent thread list ended before its last page') + this.name = 'AgentThreadListIncompleteError' + this.reason = reason + } +} + /** A workflow index and whether pagination reached its last page. */ export interface CloudWorkflowListing { entries: CloudWorkflowEntry[] complete: boolean } -/** The user's threads and whether pagination reached its last page. */ -export interface AgentThreadListing { - threads: AgentThreadSummary[] - complete: boolean -} - export type OpenTabsSnapshot = Pick< AgentPostMessageRequest, 'open_tabs' | 'current_tab' @@ -579,12 +586,11 @@ export function createAgentRestClient() { path: string, schema: z.ZodType, itemsOf: (page: Page) => Item[] - ): Promise<{ items: Item[]; complete: boolean }> { + ): Promise<{ items: Item[]; stop?: PaginationStop }> { const items: Item[] = [] - let hasMore: boolean let cursor: string | undefined const seenCursors = new Set() - do { + for (;;) { const after = cursor ? `&after=${encodeURIComponent(cursor)}` : '' const page = await request( operation, @@ -593,15 +599,13 @@ export function createAgentRestClient() { schema ) items.push(...itemsOf(page)) - hasMore = page.pagination.has_more - if (hasMore) { - const nextCursor = page.pagination.next_cursor - if (!nextCursor || seenCursors.has(nextCursor)) break - seenCursors.add(nextCursor) - cursor = nextCursor - } - } while (hasMore) - return { items, complete: !hasMore } + if (!page.pagination.has_more) return { items } + const nextCursor = page.pagination.next_cursor + if (!nextCursor) return { items, stop: 'missing_cursor' } + if (seenCursors.has(nextCursor)) return { items, stop: 'repeated_cursor' } + seenCursors.add(nextCursor) + cursor = nextCursor + } } async function postMessage( @@ -640,14 +644,15 @@ export function createAgentRestClient() { ) } - async function listThreads(): Promise { - const { items, complete } = await listAllPages( + async function listThreads(): Promise { + const { items, stop } = await listAllPages( 'list_threads', '/agent/threads', zAgentThreads, (page) => page.threads ) - return { threads: items, complete } + if (stop) throw new AgentThreadListIncompleteError(stop) + return items } async function getRunMode(): Promise { @@ -671,13 +676,13 @@ export function createAgentRestClient() { } async function listCloudWorkflows(): Promise { - const { items, complete } = await listAllPages( + const { items, stop } = await listAllPages( 'list_cloud_workflows', '/workflows', zCloudWorkflowIndex, (page) => page.data ) - return { entries: items, complete } + return { entries: items, complete: stop === undefined } } async function getCloudWorkflow( From fcc87379ce9b83b590773238b09650dadb8f5e50 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 15:07:30 +0800 Subject: [PATCH 06/66] fix(agent): ignore a chat history refresh that a newer one replaced Chat history refreshes on mount, on picking a chat and on opening the list, and with paging each refresh can take several requests. An older refresh that finished after a newer one could put back a list without the newest chat, or open the error overlay over a list that loaded fine. A generation counter now drops any refresh that is no longer the latest, the same way the panel already guards active-tab updates. --- .../extensions/agent/AgentPanelRoot.test.ts | 83 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 8 +- 2 files changed, 90 insertions(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index ee4b774b534..6ad776e2f4e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5350,6 +5350,89 @@ describe('AgentPanelRoot history', () => { expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) }) + it.for([ + { + outcome: 'a list', + staleResponse: () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-stale', + title: 'Stale chat', + last_message_at: '2026-07-07T09:00:00Z' + }) + ]) + ) + }, + { outcome: 'a failure', staleResponse: () => json(500, {}) } + ])( + 'ignores an older history refresh that ends with $outcome after a newer one', + async ({ staleResponse }) => { + const threadListRoute = /\/api\/agent\/threads\?/ + let resolveStale!: (response: Response) => void + const staleList = new Promise((resolve) => { + resolveStale = resolve + }) + const openHistory = async () => + userEvent.click( + await screen.findByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + respondToFetch({}, () => json(200, [])) + respondToFetch(threadListRoute, () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-old', + title: 'Old chat', + last_message_at: '2026-07-07T08:00:00Z' + }) + ]) + ) + ) + renderWithSelectedTarget() + const history = useAgentChatHistoryStore() + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-old']) + ) + respondToFetch(threadListRoute, () => staleList, { times: 1 }) + await openHistory() + await vi.waitFor(() => + expect(fetchRequests(threadListRoute)).toHaveLength(2) + ) + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.backToPreviousChat') + }) + ) + respondToFetch(threadListRoute, () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-new', + title: 'New chat', + last_message_at: '2026-07-07T10:00:00Z' + }) + ]) + ) + ) + await openHistory() + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) + ) + + resolveStale(staleResponse()) + await new Promise((resolve) => setTimeout(resolve)) + + expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + } + ) + it('marks the restored thread as the current session', async () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index ed387952f1b..9011bc37e1e 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1411,10 +1411,16 @@ function toChatSession(thread: AgentThreadSummary): ChatSession { } } +let historyRefreshGeneration = 0 + async function refreshHistory(): Promise { + const generation = ++historyRefreshGeneration try { - history.replaceAll((await listThreads()).map(toChatSession)) + const threads = await listThreads() + if (generation === historyRefreshGeneration) + history.replaceAll(threads.map(toChatSession)) } catch (error) { + if (generation !== historyRefreshGeneration) return reportError(error, { surface: 'agent', errorType: 'agent_thread_list_load_failed' From 8f7c54e7f8383c73147991db9fd7f253ba858735 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 15:08:03 +0800 Subject: [PATCH 07/66] test(agent): drop stale comments in history tests The rename-focus spec quoted a refreshHistory line that no longer exists, and a test helper carried JSDoc that only restated its name. --- browser_tests/tests/agent/renameFocus.spec.ts | 6 ------ src/workbench/extensions/agent/AgentPanelRoot.test.ts | 1 - 2 files changed, 7 deletions(-) diff --git a/browser_tests/tests/agent/renameFocus.spec.ts b/browser_tests/tests/agent/renameFocus.spec.ts index 41d05c7be57..b9fc13d1985 100644 --- a/browser_tests/tests/agent/renameFocus.spec.ts +++ b/browser_tests/tests/agent/renameFocus.spec.ts @@ -21,12 +21,6 @@ const RENAME_LABEL = enMessages.g.rename // failure - that was the locator (see below). const PANEL_MOUNT_TIMEOUT = 30_000 -// Precondition, not the criterion. The history list is populated by -// AgentPanelRoot.vue -> history.replaceAll((await listThreads())...), and -// listThreads() GETs /agent/threads (agentRestClient.ts). Seeding through that -// route is the app's own load path, so the row under test is rendered by the -// real component from real store state - nothing is injected into the DOM and -// no state is faked past the UI. const SEEDED_THREAD_ID = 'thread-rename-focus' const SEEDED_TITLE = 'Seeded session' const SEEDED_AT = new Date(0).toISOString() diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 6ad776e2f4e..e3da5e6740b 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -499,7 +499,6 @@ function agentThread({ } } -/** The Chat history list request, which carries a page query. */ function isThreadListUrl(url: string): boolean { return url.split('?')[0].endsWith('/api/agent/threads') } From cfbfe4692cf9a2b0fa41013119930ade793526f5 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:12:18 +0800 Subject: [PATCH 08/66] test(agent): share one empty thread-list page across browser mocks Adds emptyAgentThreadList() in fixtures/data/agent/agentThreadList.ts and uses it in the 18 browser mocks that hand-copied the same empty page, so the next response-shape change is a one-file edit. --- .../fixtures/agentAutogrowHandWiredLinkFixture.ts | 9 ++------- browser_tests/fixtures/agentConversationFixture.ts | 13 +++---------- .../fixtures/agentCrdtIdCollisionFixture.ts | 7 ++----- browser_tests/fixtures/agentPanelFixture.ts | 7 ++----- .../fixtures/agentTwoSessionCrdtFixture.ts | 13 +++---------- .../fixtures/agentWorkflowSelectionFixture.ts | 8 ++------ .../fixtures/data/agent/agentThreadList.ts | 8 ++++++++ .../fixtures/helpers/MultiAutogrowRealignHarness.ts | 11 +++-------- browser_tests/fixtures/load3dAgentFixture.ts | 9 ++------- .../agent/agentCanvasBlanksDuringRunTurn.spec.ts | 9 ++------- .../agent/agentCanvasLagsToolCallCompletion.spec.ts | 13 +++---------- ...gentDynamicComboSetWidgetSilentlyDropped.spec.ts | 11 +++-------- .../agent/agentGraphOpLostOnDisconnect.spec.ts | 13 +++---------- .../agent/agentOverflowWidgetOnNodeCreate.spec.ts | 7 ++----- browser_tests/tests/agent/agentPanelMocks.ts | 7 ++----- browser_tests/tests/agent/agentReplyDrafts.spec.ts | 13 +++---------- .../tests/agent/agentRunApprovalConsent.spec.ts | 13 +++---------- .../tests/agent/agentTemplatePlacement.spec.ts | 9 ++------- .../agent/agentZeroNodesOnUnreadableSchema.spec.ts | 13 +++---------- 19 files changed, 53 insertions(+), 140 deletions(-) create mode 100644 browser_tests/fixtures/data/agent/agentThreadList.ts diff --git a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts index 63c166deea2..b3a8dc9bbc2 100644 --- a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts +++ b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts @@ -2,7 +2,6 @@ import type { Page } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import { toNodeId } from '@/types/nodeId' @@ -16,6 +15,7 @@ import { AgentFollowerHostSocket } from '@e2e/fixtures/agentFollowerHostSocket' import { Topbar } from '@e2e/fixtures/components/Topbar' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { loadSeedIntoActiveTab } from '@e2e/fixtures/utils/seedActiveTab' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -220,12 +220,7 @@ async function setUpFixture(page: Page) { ) await hostSocket.install() await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/run-mode', (route) => route.fulfill(jsonRoute({ mode: 'ask_approval', credit_limit: null })) diff --git a/browser_tests/fixtures/agentConversationFixture.ts b/browser_tests/fixtures/agentConversationFixture.ts index 9400a2ce522..606ff09eda4 100644 --- a/browser_tests/fixtures/agentConversationFixture.ts +++ b/browser_tests/fixtures/agentConversationFixture.ts @@ -1,10 +1,7 @@ import type { Locator, Page, TestInfo } from '@playwright/test' import { expect } from '@playwright/test' import type { ApplyOutcome, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - ListAssetsResponse -} from '@comfyorg/ingest-types' +import type { ListAssetsResponse } from '@comfyorg/ingest-types' import { z } from 'zod' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -52,6 +49,7 @@ import { import { agentReplayNodeDefs } from '@e2e/fixtures/data/agentReplayNodeDefs' import type { ExpectedTurn } from '@e2e/fixtures/data/agent/agentConversationExpectations' import { RECORDED_EXPECTATIONS } from '@e2e/fixtures/data/agent/agentConversationExpectations' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import type { TabSwitchLens, WorkspaceStore } from '@e2e/types/globals' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -673,12 +671,7 @@ export class AgentConversationHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { const request = route.request() diff --git a/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts b/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts index 3a438d7506b..38846ba7d47 100644 --- a/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts +++ b/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts @@ -30,7 +30,6 @@ import { expect } from '@playwright/test' import type { AgentRunMode, - AgentThreadListResponse, AgentTurnAccepted, JobsListResponse, WorkflowListResponse @@ -59,6 +58,7 @@ import { ContextMenu } from '@e2e/fixtures/components/ContextMenu' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { Topbar } from '@e2e/fixtures/components/Topbar' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' @@ -449,10 +449,7 @@ export class IdCollisionHarness { private async mockAgentApi(): Promise { const { page } = this - const threads: AgentThreadListResponse = { - threads: [], - pagination: { has_more: false, limit: 100, offset: 0, total: 0 } - } + const threads = emptyAgentThreadList() await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) diff --git a/browser_tests/fixtures/agentPanelFixture.ts b/browser_tests/fixtures/agentPanelFixture.ts index f250811e39d..4414b4e6d22 100644 --- a/browser_tests/fixtures/agentPanelFixture.ts +++ b/browser_tests/fixtures/agentPanelFixture.ts @@ -2,7 +2,6 @@ import type { Page, Route } from '@playwright/test' import type { AgentRunMode, - AgentThreadListResponse, BillingStatusResponse, GlobalSetting, ListAssetsResponse, @@ -26,6 +25,7 @@ import { createAgentComposerConversation, createAgentComposerThreadList } from '@e2e/fixtures/data/agent/agentComposerPerformance' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' import { bootCloud, mockCloudBoot } from '@e2e/fixtures/utils/cloudBootMocks' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -122,10 +122,7 @@ export async function mockAgentTurnApi( page: Page, turnAccepted: AgentTurnAccepted ): Promise { - const threads: AgentThreadListResponse = { - threads: [], - pagination: { has_more: false, limit: 100, offset: 0, total: 0 } - } + const threads = emptyAgentThreadList() const runMode: AgentRunMode = { mode: 'ask_approval', credit_limit: null } await page.route('**/api/experiment/models', (route) => route.fulfill(jsonRoute([])) diff --git a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts index 252e6576a77..55b1900224d 100644 --- a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts +++ b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts @@ -3,10 +3,7 @@ import { expect } from '@playwright/test' import { z } from 'zod' import type { WidgetCatalog } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - WorkflowListResponse -} from '@comfyorg/ingest-types' +import type { WorkflowListResponse } from '@comfyorg/ingest-types' import enMessages from '@/locales/en/main.json' with { type: 'json' } import type { @@ -32,6 +29,7 @@ import { Topbar } from '@e2e/fixtures/components/Topbar' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' import type { RecordedGraphOperation } from '@e2e/fixtures/data/agent/agentConversation' import { emptySeed } from '@e2e/fixtures/data/agent/agentRemoteApply' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' const SOCKET_SID = 'b6f0a2c1-8e34-4d21-9c07-2a1b3c4d5e60' @@ -299,12 +297,7 @@ export class AgentTwoSessionCrdtHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { const request = route.request() diff --git a/browser_tests/fixtures/agentWorkflowSelectionFixture.ts b/browser_tests/fixtures/agentWorkflowSelectionFixture.ts index 36afd8e815e..5ca479d0a2d 100644 --- a/browser_tests/fixtures/agentWorkflowSelectionFixture.ts +++ b/browser_tests/fixtures/agentWorkflowSelectionFixture.ts @@ -5,6 +5,7 @@ import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { CloudWorkflowEntry } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { bootAgentApp } from '@e2e/fixtures/agentPanelFixture' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' type WorkflowSelection = { @@ -88,12 +89,7 @@ export const workflowSelectionTest = base.extend<{ await page.route('**/api/agent/threads**', (route) => { if (route.request().method() === 'POST') postedMessages.push(route.request().postData() ?? '') - return route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - }) - ) + return route.fulfill(jsonRoute(emptyAgentThreadList())) }) await page.route('**/api/userdata?*', (route) => { const dir = new URL(route.request().url()).searchParams.get('dir') diff --git a/browser_tests/fixtures/data/agent/agentThreadList.ts b/browser_tests/fixtures/data/agent/agentThreadList.ts new file mode 100644 index 00000000000..8bdf8189e1a --- /dev/null +++ b/browser_tests/fixtures/data/agent/agentThreadList.ts @@ -0,0 +1,8 @@ +import type { AgentThreadListResponse } from '@comfyorg/ingest-types' + +export function emptyAgentThreadList(): AgentThreadListResponse { + return { + threads: [], + pagination: { has_more: false, limit: 100, offset: 0, total: 0 } + } +} diff --git a/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts b/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts index a6d7f56f74d..4de41be1ff4 100644 --- a/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts +++ b/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts @@ -1,10 +1,7 @@ import type { Locator, Page } from '@playwright/test' import { expect } from '@playwright/test' -import type { - AgentThreadListResponse, - JobsListResponse -} from '@comfyorg/ingest-types' +import type { JobsListResponse } from '@comfyorg/ingest-types' import type { ModelFolderInfo } from '@/platform/assets/schemas/assetSchema' import type { PromptResponse } from '@/platform/remote/comfyui/types' import type { @@ -50,6 +47,7 @@ import { seed, sourceNodeDef } from '@e2e/fixtures/data/agent/agentCrdtMultiAutogrowRealignFixture' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import enMessages from '@/locales/en/main.json' with { type: 'json' } export const SENTINEL_PROMPT = 'multi-autogrow-realign-sentinel-prompt' @@ -166,10 +164,7 @@ export class MultiAutogrowRealignHarness { await this.hostSocket.install() - const threadList: AgentThreadListResponse = { - pagination: { has_more: false, limit: 100, offset: 0, total: 0 }, - threads: [] - } + const threadList = emptyAgentThreadList() await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threadList)) ) diff --git a/browser_tests/fixtures/load3dAgentFixture.ts b/browser_tests/fixtures/load3dAgentFixture.ts index 6994188e22b..bd490e38b56 100644 --- a/browser_tests/fixtures/load3dAgentFixture.ts +++ b/browser_tests/fixtures/load3dAgentFixture.ts @@ -2,7 +2,6 @@ import type { Page, Request } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { ComfyApiWorkflow } from '@/platform/workflow/validation/schemas/workflowSchema' import { @@ -17,6 +16,7 @@ import { AgentFollowerHostSocket } from '@e2e/fixtures/agentFollowerHostSocket' import { agentTest, bootAgentApp } from '@e2e/fixtures/agentPanelFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import type { RecordedGraphOperation } from '@e2e/fixtures/data/agent/agentConversation' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { TestIds } from '@e2e/fixtures/selectors' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { assetPath } from '@e2e/fixtures/utils/paths' @@ -278,12 +278,7 @@ class Load3dAgentHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => route.fulfill(jsonRoute([])) diff --git a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts index 88139f3c77a..dd06e470201 100644 --- a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts +++ b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts @@ -3,7 +3,6 @@ import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' import type { - AgentThreadListResponse, DocResetFrame, WorkflowListResponse } from '@comfyorg/ingest-types' @@ -25,6 +24,7 @@ import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' import { loadSeedIntoActiveTab } from '@e2e/fixtures/utils/seedActiveTab' @@ -210,12 +210,7 @@ async function driveThroughDocReset( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts index e502108866d..9ca8ed6891d 100644 --- a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts +++ b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts @@ -2,10 +2,7 @@ import type { Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - WorkflowListResponse -} from '@comfyorg/ingest-types' +import type { WorkflowListResponse } from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -20,6 +17,7 @@ import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' @@ -154,12 +152,7 @@ async function driveThroughToolCallDone( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts b/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts index d51bda332ed..0be6c74e5a1 100644 --- a/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts +++ b/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts @@ -1,10 +1,7 @@ import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - WorkflowListResponse -} from '@comfyorg/ingest-types' +import type { WorkflowListResponse } from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import type { ComfyNodeDef } from '@/schemas/nodeDefSchema' import type { GraphOperation } from '@/workbench/extensions/agent/crdt/graphOperations' @@ -21,6 +18,7 @@ import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import { AgentFollowerHostSocket } from '@e2e/fixtures/agentFollowerHostSocket' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import enMessages from '@/locales/en/main.json' with { type: 'json' } import { mintWireOps } from '@/workbench/extensions/agent/crdt/opEnvelope' @@ -136,10 +134,7 @@ test.describe( ) await hostSocket.install() - const threadList: AgentThreadListResponse = { - pagination: { has_more: false, limit: 100, offset: 0, total: 0 }, - threads: [] - } + const threadList = emptyAgentThreadList() await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threadList)) ) diff --git a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts index ca7474666bc..25a55de264d 100644 --- a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts +++ b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts @@ -2,10 +2,7 @@ import type { WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - WorkflowListResponse -} from '@comfyorg/ingest-types' +import type { WorkflowListResponse } from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -21,6 +18,7 @@ import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' @@ -110,12 +108,7 @@ test.describe( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts b/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts index bfd9ac82ece..cd37ddef1d9 100644 --- a/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts +++ b/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts @@ -1,7 +1,6 @@ import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { ComfyNodeDef, InputSpec } from '@/schemas/nodeDefSchema' import type { AgentRunModePreference } from '@/workbench/extensions/agent/schemas/agentApiSchema' @@ -14,6 +13,7 @@ import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import { AgentFollowerHostSocket } from '@e2e/fixtures/agentFollowerHostSocket' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -130,10 +130,7 @@ test.describe( ) await hostSocket.install() - const threadList: AgentThreadListResponse = { - pagination: { has_more: false, limit: 100, offset: 0, total: 0 }, - threads: [] - } + const threadList = emptyAgentThreadList() await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threadList)) ) diff --git a/browser_tests/tests/agent/agentPanelMocks.ts b/browser_tests/tests/agent/agentPanelMocks.ts index 6e7e25799e4..53e8b5d8797 100644 --- a/browser_tests/tests/agent/agentPanelMocks.ts +++ b/browser_tests/tests/agent/agentPanelMocks.ts @@ -2,7 +2,6 @@ import { zGlobalSettingValue } from '@comfyorg/ingest-types/zod' import type { Page, Route, WebSocketRoute } from '@playwright/test' import type { - AgentThreadListResponse, BillingStatusResponse, GlobalSetting, WorkflowListResponse @@ -22,6 +21,7 @@ import type { import { zAgentAdmissionError } from '@/workbench/extensions/agent/schemas/agentApiSchema' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { mockBilling } from '@e2e/fixtures/utils/cloudBillingMocks' import { mockCloudBootRoutes } from '@e2e/fixtures/utils/cloudBootMocks' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -459,10 +459,7 @@ async function mockAgentBoot( } return route.fulfill(jsonRoute(workflows)) }) - const threads: AgentThreadListResponse = { - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } + const threads = emptyAgentThreadList() await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) ) diff --git a/browser_tests/tests/agent/agentReplyDrafts.spec.ts b/browser_tests/tests/agent/agentReplyDrafts.spec.ts index 6e9b9f60652..4deb5eb105b 100644 --- a/browser_tests/tests/agent/agentReplyDrafts.spec.ts +++ b/browser_tests/tests/agent/agentReplyDrafts.spec.ts @@ -2,10 +2,7 @@ import type { Locator, Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - WorkflowListResponse -} from '@comfyorg/ingest-types' +import type { WorkflowListResponse } from '@comfyorg/ingest-types' import { zAgentAnswerRequest } from '@comfyorg/ingest-types/zod' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -19,6 +16,7 @@ import { import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' @@ -69,12 +67,7 @@ async function startTurn(page: Page, prompt: string): Promise { } await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts b/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts index 78b5a901143..550572fb900 100644 --- a/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts +++ b/browser_tests/tests/agent/agentRunApprovalConsent.spec.ts @@ -2,10 +2,7 @@ import type { Locator, Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentRunMode, - AgentThreadListResponse -} from '@comfyorg/ingest-types' +import type { AgentRunMode } from '@comfyorg/ingest-types' import enMessages from '@/locales/en/main.json' with { type: 'json' } import type { AgentWsEvent } from '@/workbench/extensions/agent/schemas/agentApiSchema' @@ -18,6 +15,7 @@ import { import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' @@ -135,12 +133,7 @@ async function startTurn( return route.fulfill(jsonRoute({ status: 'answered' })) }) await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentTemplatePlacement.spec.ts b/browser_tests/tests/agent/agentTemplatePlacement.spec.ts index eabf6d7c6be..d7244fd67d1 100644 --- a/browser_tests/tests/agent/agentTemplatePlacement.spec.ts +++ b/browser_tests/tests/agent/agentTemplatePlacement.spec.ts @@ -1,7 +1,6 @@ import type { Page, WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' -import type { AgentThreadListResponse } from '@comfyorg/ingest-types' import type { AgentCancelAccepted, AgentMessages, @@ -17,6 +16,7 @@ import { import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { nextFrame } from '@e2e/fixtures/utils/timing' @@ -261,12 +261,7 @@ class TemplatePlacementHarness { private async mockAgentApi(): Promise { const { page } = this await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { diff --git a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts index 4e3d8f9f7fc..86a302155c6 100644 --- a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts +++ b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts @@ -2,10 +2,7 @@ import type { WebSocketRoute } from '@playwright/test' import { expect } from '@playwright/test' import type { WidgetCatalog, WorkflowJSON } from '@comfyorg/comfy-multi-player' -import type { - AgentThreadListResponse, - WorkflowListResponse -} from '@comfyorg/ingest-types' +import type { WorkflowListResponse } from '@comfyorg/ingest-types' import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' import enMessages from '@/locales/en/main.json' with { type: 'json' } @@ -20,6 +17,7 @@ import { HostDoc } from '@e2e/fixtures/agentConversationHostDoc' import type { HostFrame } from '@e2e/fixtures/agentConversationHostDoc' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { VueNodeHelpers } from '@e2e/fixtures/VueNodeHelpers' +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { AGENT_COMPOSER_LABEL } from '@e2e/fixtures/utils/agentComposerLabel' @@ -101,12 +99,7 @@ test.describe( } await page.route('**/api/agent/threads?*', (route) => - route.fulfill( - jsonRoute({ - threads: [], - pagination: { offset: 0, limit: 100, total: 0, has_more: false } - } satisfies AgentThreadListResponse) - ) + route.fulfill(jsonRoute(emptyAgentThreadList())) ) await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() === 'POST') { From 0bbc43615025d5d5a2436e8615d063223beefa62 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:15:51 +0800 Subject: [PATCH 09/66] test(agent): wait for the stale history page to be read The stale-refresh test slept one timer tick after releasing the older response. It now waits until the panel has read that response's body, so the assertions run only after the stale refresh got its page. --- src/workbench/extensions/agent/AgentPanelRoot.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index e3da5e6740b..59738b1067b 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5424,8 +5424,9 @@ describe('AgentPanelRoot history', () => { expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) ) - resolveStale(staleResponse()) - await new Promise((resolve) => setTimeout(resolve)) + const stale = staleResponse() + resolveStale(stale) + await vi.waitFor(() => expect(stale.bodyUsed).toBe(true)) expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() From e604413cabb38ad0860bbb0c387e5758a826cd07 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:16:34 +0800 Subject: [PATCH 10/66] fix(agent): ignore a chat history refresh from a closed panel The chat history list is shared, but each panel counts its own refreshes. If the panel closed while a multi-page refresh was still loading and then reopened, the old refresh could still replace the list the new panel had loaded, or open the error overlay. Closing the panel now marks its refreshes as replaced. --- .../extensions/agent/AgentPanelRoot.test.ts | 68 ++++++++++++++++++- .../extensions/agent/AgentPanelRoot.vue | 7 ++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 59738b1067b..3047d049c31 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5349,7 +5349,7 @@ describe('AgentPanelRoot history', () => { expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) }) - it.for([ + const staleRefreshOutcomes = [ { outcome: 'a list', staleResponse: () => @@ -5365,7 +5365,9 @@ describe('AgentPanelRoot history', () => { ) }, { outcome: 'a failure', staleResponse: () => json(500, {}) } - ])( + ] + + it.for(staleRefreshOutcomes)( 'ignores an older history refresh that ends with $outcome after a newer one', async ({ staleResponse }) => { const threadListRoute = /\/api\/agent\/threads\?/ @@ -5433,6 +5435,68 @@ describe('AgentPanelRoot history', () => { } ) + it.for(staleRefreshOutcomes)( + 'ignores a closed panel history refresh that ends with $outcome after the panel reopens', + async ({ staleResponse }) => { + const threadListRoute = /\/api\/agent\/threads\?/ + const secondPageRoute = /\/api\/agent\/threads\?.*after=page-2/ + let resolveStale!: (response: Response) => void + const staleSecondPage = new Promise((resolve) => { + resolveStale = resolve + }) + respondToFetch({}, () => json(200, [])) + respondToFetch(threadListRoute, () => + json(200, { + ...agentThreadList([ + agentThread({ + id: 'th-old', + title: 'Old chat', + last_message_at: '2026-07-07T08:00:00Z' + }) + ]), + pagination: { + has_more: true, + next_cursor: 'page-2', + limit: 1, + offset: 0, + total: 2 + } + }) + ) + respondToFetch(secondPageRoute, () => staleSecondPage, { times: 1 }) + const closedPanel = renderWithSelectedTarget() + await vi.waitFor(() => + expect(fetchRequests(secondPageRoute)).toHaveLength(1) + ) + closedPanel.unmount() + respondToFetch(threadListRoute, () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-new', + title: 'New chat', + last_message_at: '2026-07-07T10:00:00Z' + }) + ]) + ) + ) + renderWithSelectedTarget() + const history = useAgentChatHistoryStore() + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) + ) + + const stale = staleResponse() + resolveStale(stale) + await vi.waitFor(() => expect(stale.bodyUsed).toBe(true)) + + expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + expect(telemetry.trackAgentError).not.toHaveBeenCalled() + } + ) + it('marks the restored thread as the current session', async () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 9011bc37e1e..a18ab1d2e88 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1439,6 +1439,13 @@ async function refreshHistory(): Promise { } void refreshHistory() +onBeforeUnmount(() => + runPanelTeardown({ + invalidateHistoryRefreshGeneration: () => { + ++historyRefreshGeneration + } + }) +) const currentChatReady = computed( () => From 41962f11ec718f20f96f9265e90aa7a0023a8cac Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:17:07 +0800 Subject: [PATCH 11/66] test(agent): drop comments in thread-list route fixtures Removes the comments inside the browser test functions whose thread-list route glob this branch changed, per the repo's no-comment rule for functions a change touches. File headers and helper docs stay. --- .../agentAutogrowHandWiredLinkFixture.ts | 26 ------------------- .../fixtures/agentConversationFixture.ts | 1 - .../fixtures/agentCrdtIdCollisionFixture.ts | 8 ------ .../fixtures/agentPromptHistoryFixture.ts | 1 - .../fixtures/agentTurnLockFixture.ts | 7 ----- .../helpers/MultiAutogrowRealignHarness.ts | 19 -------------- browser_tests/fixtures/load3dAgentFixture.ts | 1 - .../agentCanvasBlanksDuringRunTurn.spec.ts | 25 ------------------ .../agentCanvasLagsToolCallCompletion.spec.ts | 25 ------------------ .../agent/agentChatHistoryTitleSync.spec.ts | 6 ----- ...namicComboSetWidgetSilentlyDropped.spec.ts | 5 ---- .../agentGraphOpLostOnDisconnect.spec.ts | 21 --------------- .../agentHistoryReopensClosedWorkflow.spec.ts | 3 --- .../agentOverflowWidgetOnNodeCreate.spec.ts | 6 ----- .../agentStaleWorkflowTabBinding.spec.ts | 15 ----------- .../agentZeroNodesOnUnreadableSchema.spec.ts | 20 -------------- 16 files changed, 189 deletions(-) diff --git a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts index b3a8dc9bbc2..97891c475f9 100644 --- a/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts +++ b/browser_tests/fixtures/agentAutogrowHandWiredLinkFixture.ts @@ -193,10 +193,6 @@ async function readImageInputs(page: Page) { } async function setUpFixture(page: Page) { - // `objectInfo: 'server'` (passed to `bootAgentApp` below) stops - // `mockCloudBootRoutes` from also registering an (empty) handler for - // this route — Playwright runs the most-recently-registered handler - // first, so a route added here after that call would never fire. await page.route('**/api/object_info', (route) => route.fulfill( jsonRoute({ @@ -207,10 +203,6 @@ async function setUpFixture(page: Page) { ) const host = new HostDoc(WORKFLOW_ID, seed, catalog) - // 'apply' because the hand-wire step below mints a real `doc_ops` batch - // over this socket (any `registerLinkTopology` placement does, canvas or - // agent alike) — the host has to answer it like the relay does instead of - // leaving the batch unacked. const hostSocket = new AgentFollowerHostSocket( page, WORKFLOW_ID, @@ -225,9 +217,6 @@ async function setUpFixture(page: Page) { await page.route('**/api/agent/run-mode', (route) => route.fulfill(jsonRoute({ mode: 'ask_approval', credit_limit: null })) ) - // The CRDT follower only binds a workflow once a real turn's ack - // names one (`bindWorkflow(ack.workflow_id)` in `useAgentSession.ts`) - // — picking a target from the switcher alone does not bind it. await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() !== 'POST') return route.fulfill(jsonRoute([])) return route.fulfill({ @@ -243,19 +232,12 @@ async function setUpFixture(page: Page) { await bootAgentApp(page, true, { objectInfo: 'server', - // Only the Vue node renderer projects follower edits onto the - // canvas as DOM nodes this test can query. settings: { 'Comfy.VueNodes.Enabled': true, 'Comfy.Graph.CanvasInfo': false } }) - // Registered only now, same as `AgentConversationHarness. - // selectWorkflowTarget`: `bootAgentApp`'s own mocks blanket-match - // `**/api/userdata**` for every method, and Playwright runs the - // most-recently-registered matching route first, so this has to - // come after it to take over the workflow-save round trip. await mockWorkflowPersistence(page, WORKFLOW_ID) const topbar = new Topbar(page) @@ -312,10 +294,6 @@ async function setUpFixture(page: Page) { }, toNodeId(GPT_NODE_ID)) expect(freeIndex).toBeGreaterThanOrEqual(0) - // The same runtime path a UI drag-connect takes (`LGraphNode.connect` - // dispatches through `registerLinkTopology`, which the link mint port - // listens to for every connect regardless of how it was made) — this is - // the user wiring a source into the node without any agent involvement. await page.evaluate( ({ sourceId, targetId, targetSlot }) => { const graph = window.app!.graph @@ -329,10 +307,6 @@ async function setUpFixture(page: Page) { targetSlot: freeIndex } ) - // Settles only once the CRDT round trip (now acked by the host, per - // `humanOpsHost: 'apply'` above) and autogrow's own client-side growth - // have both landed on this freshly booted page — the same CI slowness - // the subscribe wait above budgets for. await expect .poll(() => readImageInputs(page), { timeout: 20_000 }) .toEqual([ diff --git a/browser_tests/fixtures/agentConversationFixture.ts b/browser_tests/fixtures/agentConversationFixture.ts index 606ff09eda4..5537b8420c2 100644 --- a/browser_tests/fixtures/agentConversationFixture.ts +++ b/browser_tests/fixtures/agentConversationFixture.ts @@ -698,7 +698,6 @@ export class AgentConversationHarness { target === null || target[1] !== THREAD_ID ? undefined : this.cancelWaiters.get(target[2]) - // A real server knows nothing about any other message. if (release === undefined) return route.fulfill({ status: 404 }) release() const cancelled: AgentCancelAccepted = { status: 'cancelling' } diff --git a/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts b/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts index 38846ba7d47..b4eb0e35d9b 100644 --- a/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts +++ b/browser_tests/fixtures/agentCrdtIdCollisionFixture.ts @@ -456,10 +456,6 @@ export class IdCollisionHarness { await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() !== 'POST') return route.fulfill(jsonRoute([])) - // The ack's `workflow_id` is what `useAgentSession` binds for CRDT - // purposes (`bindWorkflow(ack.workflow_id)`). `workflow_id` is an - // extra beyond the generated `AgentTurnAccepted`, handled deliberately - // elsewhere via `zAgentTurnAccepted...passthrough()`. const accepted = { thread_id: THREAD_ID, message_id: MESSAGE_ID, @@ -478,10 +474,6 @@ export class IdCollisionHarness { } return route.fulfill(jsonRoute(workflows)) }) - // Best-effort background calls the panel makes on mount; none are under - // test here, but an unmocked one 502s through Vite's dev proxy (there is - // no real backend behind DEV_SERVER_COMFYUI_URL in this repro) and the - // panel surfaces that as a toast that can mask the actual assertions. const runMode: AgentRunMode = { credit_limit: null, mode: 'ask_approval' } await page.route('**/api/agent/run-mode', (route) => route.fulfill(jsonRoute(runMode)) diff --git a/browser_tests/fixtures/agentPromptHistoryFixture.ts b/browser_tests/fixtures/agentPromptHistoryFixture.ts index 868695a7031..90776df30bc 100644 --- a/browser_tests/fixtures/agentPromptHistoryFixture.ts +++ b/browser_tests/fixtures/agentPromptHistoryFixture.ts @@ -47,7 +47,6 @@ export const promptHistoryTest = base.extend<{ await use(new AgentPanel(page)) }, promptHistory: async ({ page, workflowSelection, getWebSocket }, use) => { - // Workflow selection boots the app before these agent-specific routes. void workflowSelection const requests: AgentPostMessageRequest[] = [] const messages: MockAgentMessage[] = [] diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 13bb6572b41..3336f04e235 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -451,13 +451,6 @@ async function routeTurnLock( }) }) - /** - * The glob accepts any thread and any ask id, so without these checks an - * answer posted against the wrong ask -- or an option this ask never offered - * -- would still be recorded and `answeredAsks()` would report success. The - * assertion this fixture exists to support is "the answer left the client for - * *this* ask", so the route has to be the thing that enforces it. - */ await page.route('**/api/agent/threads/*/asks/*/answer', (route) => { const url = new URL(route.request().url()) const segments = url.pathname.split('/').map(decodeURIComponent) diff --git a/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts b/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts index 4de41be1ff4..cf3187fa4e8 100644 --- a/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts +++ b/browser_tests/fixtures/helpers/MultiAutogrowRealignHarness.ts @@ -135,10 +135,6 @@ export class MultiAutogrowRealignHarness { options: { settings?: Record } = {} ): Promise { const { page } = this - // Registered before `bootAgentApp` (with `objectInfo: 'server'` below) so - // it wins over the empty handler `mockCloudBootRoutes` would otherwise - // register afterward for the same route -- Playwright runs the - // most-recently-registered matching handler first. await page.route('**/api/object_info', (route) => route.fulfill( jsonRoute({ @@ -148,10 +144,6 @@ export class MultiAutogrowRealignHarness { ) ) - // Neither route is registered by `bootAgentApp`'s own boot mocks: the - // model-folder list is read while the panel chrome renders, and - // `queueStore`'s background job poll runs for the lifetime of every one - // of this file's tests, not only a scenario that sends a second turn. const folders: ModelFolderInfo[] = [] await page.route('**/api/experiment/models', (route) => route.fulfill(jsonRoute(folders)) @@ -180,11 +172,6 @@ export class MultiAutogrowRealignHarness { message_id: MESSAGE_ID, workflow_id: WORKFLOW_ID } - // Stateful once the turn is sent: a page reload re-runs - // `useAgentSession.start()`, which finds the persisted thread id in - // `localStorage` and hydrates from this same endpoint -- the message row's - // `workflow_id` is what lets the agent panel rebind its target and - // resubscribe the CRDT follower after the reload. let turnSent = false await page.route('**/api/agent/threads/*/messages', (route) => { if (route.request().method() !== 'POST') { @@ -214,8 +201,6 @@ export class MultiAutogrowRealignHarness { await bootAgentApp(page, true, { objectInfo: 'server', - // Only the Vue node renderer projects follower edits onto the canvas as - // DOM this test can query. settings: { 'Comfy.VueNodes.Enabled': true, 'Comfy.Graph.CanvasInfo': false, @@ -223,10 +208,6 @@ export class MultiAutogrowRealignHarness { } }) - // Registered only now, same as `AgentConversationHarness. - // selectWorkflowTarget`: `bootAgentApp`'s own mocks blanket-match - // `**/api/userdata**` for every method, and Playwright runs the - // most-recently-registered matching route first. this.persistence = await mockSavedWorkflowPersistence(page, WORKFLOW_ID) await page.route('**/api/prompt', (route) => { diff --git a/browser_tests/fixtures/load3dAgentFixture.ts b/browser_tests/fixtures/load3dAgentFixture.ts index bd490e38b56..27c5739e385 100644 --- a/browser_tests/fixtures/load3dAgentFixture.ts +++ b/browser_tests/fixtures/load3dAgentFixture.ts @@ -283,7 +283,6 @@ class Load3dAgentHarness { await page.route('**/api/agent/threads/*/messages', (route) => route.fulfill(jsonRoute([])) ) - // No cloud workflow carries the agent's id, so the panel opens a new tab for it. await page.route('**/api/workflows**', (route) => route.fulfill( jsonRoute({ diff --git a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts index dd06e470201..7db75b1c10b 100644 --- a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts +++ b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts @@ -324,12 +324,6 @@ async function driveThroughDocReset( await panel.getByRole('button', { name: SEND_LABEL }).click() await expect(panel.getByText('Run the workflow.').first()).toBeVisible() - // The panel doesn't bind (and so doesn't subscribe) the CRDT doc merely - // from selecting a workflow as the agent's target -- `boundWorkflowId` - // (`useAgentSession.ts`) only changes via `bindWorkflow`, which fires from - // this `agent_active_tab` push (`AgentPanelRoot.vue`'s `onAgentActiveTab`). - // The first real subscribe -- and so the seed's two nodes -- can only - // appear after this frame, not merely after picking the workflow tab. send({ type: 'agent_active_tab', data: { @@ -340,9 +334,6 @@ async function driveThroughDocReset( } }) - // Baseline: the healthy first subscribe delivers the seed's two nodes, - // matching the user's report that the canvas held the workflow's nodes - // before the agent started working on the run. await expect(vueNodes.getNodeLocator('1')).toBeVisible() await expect(vueNodes.getNodeLocator('2')).toBeVisible() @@ -369,17 +360,6 @@ async function driveThroughDocReset( } }) - // "The moment the agent started working": a lineage break for the active - // document right as the run-only turn gets going. This used to be the one - // frame able to sweep already-rendered nodes off the canvas; now it only - // arms the next frame to replace the graph. From here on the resubscribe's - // catch-up is governed by `dropCatchUpAfterReset`. - // - // Stamped on the live element before the reset so the assertion below can - // tell a node that was never unmounted from one that was torn down and - // rebuilt. `toBeVisible` cannot: a remounted node is equally visible, and a - // remount is what restarts media playback (PM-1790). Vue does not manage - // this dataset key, so only a fresh element loses it. await page.evaluate((nodeId) => { const el = document.querySelector(`[data-node-id="${nodeId}"]`) if (el instanceof HTMLElement) el.dataset.identityProbe = 'before-reset' @@ -421,11 +401,6 @@ async function driveThroughDocReset( await expect(vueNodes.getNodeLocator('1')).toBeVisible() await expect(vueNodes.getNodeLocator('2')).toBeVisible() - // The same element, not merely an equivalent one: a reset that went back to - // clearing would drop this node and its stamp with it. It does NOT yet say - // anything about `GraphCanvas`'s key -- nothing re-renders between the - // reset and here, so the stamp survives a randomised key too. That is what - // `expectNodeSurvivedReplacement` covers, once content actually lands. await expectNodeSurvivedReset(page) return { vueNodes, send } diff --git a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts index 9ca8ed6891d..a291e0e61e4 100644 --- a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts +++ b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts @@ -121,15 +121,6 @@ function subscribeStateVectorOf(raw: Buffer | string): string | null { */ async function driveThroughToolCallDone( page: Page, - /** - * The healthy-doc-host ordering is the tool call's own terminal frame - * landing before the matching `doc_update` broadcast -- that is what every - * scenario above exercises. 'docUpdateBeforeToolCall' instead releases the - * (already-applied, see `host.apply` below) `doc_update` BEFORE the - * `agent_tool_call success` frame, to exercise the inverted ordering a - * lost-wakeup regression in `notifyCanvasCaughtUp`'s edge-triggering would - * strand at `STALE_AFTER_MS` even though the canvas had already caught up. - */ order: | 'toolCallBeforeDocUpdate' | 'docUpdateBeforeToolCall' = 'toolCallBeforeDocUpdate' @@ -266,10 +257,6 @@ async function driveThroughToolCallDone( } }) - // The doc host records the op on its authoritative document as soon as the - // tool actually executes -- this is not a race the agent lost, the op is - // real -- independent of when its broadcast reaches this client relative - // to the tool call's own terminal frame, which `order` controls below. const update = host.apply([ { op: 'add_node', @@ -293,15 +280,8 @@ async function driveThroughToolCallDone( ]) expect(Object.keys(host.graph().nodes)).toContain(String(ADDED_NODE_ID)) - // The inverted ordering: the doc_update broadcast reaches this client - // while the tool is still (from the chat frames' perspective) running -- - // the healthy-doc-host case most reviewers flagged as the lost-wakeup risk - // for notifyCanvasCaughtUp()'s edge triggering. if (order === 'docUpdateBeforeToolCall') send(update) - // The tool-call-completion affordance: `agentEventTransport.ts`'s `ingest()` - // flips this tool part `done` the instant this frame is read, purely from - // `status`, with nothing checked on the CRDT doc side (see file header). send({ type: 'agent_tool_call', data: { @@ -326,16 +306,11 @@ async function driveThroughToolCallDone( data: { thread_id: THREAD_ID, message_id: MESSAGE_ID, usage: null } }) - // Setup checkpoint: every working affordance the report names has settled -- - // the composer is free again and the turn's own "Worked for Xs" summary is - // up -- while the canvas (asserted by the caller) has nothing yet. await expect(panel.getByRole('button', { name: SEND_LABEL })).toBeVisible() await expect(panel.getByRole('button', { name: /^Worked/ })).toBeVisible() return { vueNodes, - // A no-op once `order` already sent it above -- resending the same - // update twice is not part of what either ordering means to exercise. sendDelayedDocUpdate: () => { if (order !== 'docUpdateBeforeToolCall') send(update) } diff --git a/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts b/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts index 57881625a0a..ff9a1f3fded 100644 --- a/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts +++ b/browser_tests/tests/agent/agentChatHistoryTitleSync.spec.ts @@ -83,9 +83,6 @@ test.describe( resolveThreadsRefetch?.() }) - // The transcript fetch is held until the test has already observed the - // stale list entry with no derived title yet, so the "before" state is - // driven deterministically instead of raced against hydration. let releaseTranscriptHydration: (() => void) | undefined const transcriptGate = new Promise((resolve) => { releaseTranscriptHydration = resolve @@ -102,8 +99,6 @@ test.describe( route.fulfill(jsonRoute([])) ) - // Resume straight into the existing thread, the same way a reopened - // app restores its last chat (useAgentSession.start()). await page.addInitScript( ({ key, threadId }) => localStorage.setItem(key, threadId), { key: StorageKeys.agentThread(WORKSPACE_ID), threadId: THREAD_ID } @@ -131,7 +126,6 @@ test.describe( await panel .getByRole('button', { name: enMessages.agent.backToPreviousChat }) .click() - // Nothing has hydrated yet, so the header has no derived title either. await expect( panel.getByRole('button', { name: enMessages.agent.newChatTitle, diff --git a/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts b/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts index 0be6c74e5a1..91f029985c0 100644 --- a/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts +++ b/browser_tests/tests/agent/agentDynamicComboSetWidgetSilentlyDropped.spec.ts @@ -271,11 +271,6 @@ test.describe( ) }) - // The document now authoritatively records mode: "faithful" (matching - // an agent tool call that reports success), so the canvas should grow - // the `mode.skin_detail` widget the "faithful" option declares in the - // node's real Python schema — exactly what a human clicking the same - // dropdown gets. const skinDetailField = vueNodes .getNodeLocator(String(NODE_ID)) .getByRole('spinbutton', { name: 'mode.skin_detail' }) diff --git a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts index 25a55de264d..f8cc9e0b8a6 100644 --- a/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts +++ b/browser_tests/tests/agent/agentGraphOpLostOnDisconnect.spec.ts @@ -145,10 +145,6 @@ test.describe( } if (frame.type !== 'doc_subscribe' || frame.stateVector === null) return - // The reconnect's re-subscribe never gets an answer: the general - // realtime channel recovered (chat keeps flowing below), but the - // host swallows the doc subscription frame. Only a retry of that - // subscribe is answered. const swallowed = !isFirstConnection && postReconnectSubscribes().length === 1 if (swallowed) return @@ -217,8 +213,6 @@ test.describe( .click() await expect(picker).toHaveText('Unsaved Workflow') - // Setup checkpoint: the follower actually bound and subscribed once on - // the first (and so far only) connection before anything goes wrong. await expect.poll(() => connectionCount).toBe(1) const composer = panel.getByRole('textbox', { @@ -251,8 +245,6 @@ test.describe( } }) - // The op lands on the authoritative document (the CRDT event log the - // debug report quotes) ... const update = host.apply([ { op: 'add_node', @@ -276,14 +268,9 @@ test.describe( ]) expect(Object.keys(host.graph().nodes)).toContain(String(ADDED_NODE_ID)) - // ... but the transport drops right as that update would go out: the - // frame is never sent, and the socket closes under the follower. void update await socket!.close() - // The main realtime channel recovers (exactly one reconnect: chat keeps - // working below), so the agent can still report success. The follower's - // re-subscribe went out on the new socket and is being ignored. await expect.poll(() => connectionCount).toBe(2) await expect.poll(() => postReconnectDocFrames.length).toBe(1) expect(postReconnectDocFrames.map(({ type }) => type)).toEqual([ @@ -303,8 +290,6 @@ test.describe( data: { thread_id: THREAD_ID, message_id: MESSAGE_ID, usage: null } }) - // Setup checkpoint: the agent's turn completes and reports success in - // the panel, exactly as the tester saw it do. await expect( panel.getByRole('button', { name: SEND_LABEL }) ).toBeVisible() @@ -313,16 +298,10 @@ test.describe( ) await expect(panel.getByRole('button', { name: /^Worked/ })).toBeVisible() - // The agent said it added the note, and the op is in the document's own - // record (asserted above). The follower must notice that its subscribe - // was never acknowledged, retry it, and land the node on the live canvas. await expect(vueNodes.getNodeLocator(String(ADDED_NODE_ID))).toBeVisible({ timeout: SUBSCRIBE_ACK_TIMEOUT_MS + 10_000 }) - // The retry is the fix's fingerprint: one more `doc_subscribe` on the - // same lineage (unchanged state vector, no unsubscribe in between) after - // the ack timeout, never an immediate retarget or a reset. await expect .poll(() => postReconnectSubscribes().length, { message: 'the follower never retried the unanswered doc_subscribe' diff --git a/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts b/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts index 234d7e8a54f..518b34c6932 100644 --- a/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts +++ b/browser_tests/tests/agent/agentHistoryReopensClosedWorkflow.spec.ts @@ -161,9 +161,6 @@ test.describe( await bootAgentApp(page, agentFlagEnabled, { objectInfo: NODE_DEFINITIONS, - // Registered after the boot mocks so these win over their userdata - // stub: the saved workflow is in the user's workflow list from boot, - // but its tab is never opened. beforeNavigate: async (page) => { await page.route('**/api/agent/threads?*', (route) => route.fulfill(jsonRoute(threads)) diff --git a/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts b/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts index cd37ddef1d9..da906b02b7e 100644 --- a/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts +++ b/browser_tests/tests/agent/agentOverflowWidgetOnNodeCreate.spec.ts @@ -188,24 +188,18 @@ test.describe( await hostSocket.waitForSubscribe() }) - // The follower creates the node from the document it just received. const node = vueNodes.getNodeLocator(String(NODE_ID)) await expect(node).toBeVisible() await expect(node.getByText('faithful', { exact: true })).toBeVisible() - // `_extra_2` is the aliased tail: it must reach `mode.b`. await expect( node.getByRole('spinbutton', { name: 'mode.b' }) ).toHaveValue('71') - // `mode.a` is catalogued, so its named value is applied after `configure`. await expect( node.getByRole('spinbutton', { name: 'mode.a' }) ).toHaveValue('91') - // A later frame can carry a child before the selector that rebuilds - // the group. The selector must run first so neither saved child value - // is overwritten by the newly selected option's defaults. hostSocket.send( host.replaceDocumentWidgets(NODE_ID, [ ['mode.a', 92], diff --git a/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts b/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts index f89c7300b19..a5770b42d6e 100644 --- a/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts +++ b/browser_tests/tests/agent/agentStaleWorkflowTabBinding.spec.ts @@ -58,9 +58,6 @@ test.describe( const staleWorkflowId = workflow.id const host = new HostDoc(staleWorkflowId, workflow.seed, workflow.catalog) - // The previous tab's own in-app cleanup never ran (its browser tab was - // simply closed), so the binding cache and the thread pointer survive - // untouched into this brand-new page load. await page.addInitScript( ([bindingKey, threadKey, id, path, threadId]) => { localStorage.setItem(bindingKey, JSON.stringify({ [id]: path })) @@ -78,8 +75,6 @@ test.describe( let socket: WebSocketRoute | undefined await page.routeWebSocket(/\/ws/, (ws) => { socket = ws - // Answers a doc_subscribe for the abandoned workflow with its real - // seeded content, the way the production doc host would. ws.onMessage((raw) => { const frame: unknown = JSON.parse(raw.toString()) if (typeof frame !== 'object' || frame === null) return @@ -102,8 +97,6 @@ test.describe( ws.send(JSON.stringify(host.subscribed())) ws.send(JSON.stringify(host.catchUp(state_vector_b64))) }) - // The follower only re-drives a pending subscribe on a status frame, - // which every real connect sends. ws.send( JSON.stringify({ type: 'status', @@ -148,7 +141,6 @@ test.describe( if (route.request().method() === 'GET') return route.fulfill(jsonRoute(history)) posted.push(route.request().postDataJSON()) - // The thread's server-side pointer still names the abandoned workflow. const accepted: AgentTurnAccepted = { thread_id: THREAD_ID, message_id: TURN_ID, @@ -172,17 +164,13 @@ test.describe( ) await bootAgentApp(page, agentFlagEnabled, { - // Only the Vue node renderer projects follower edits onto the canvas. settings: { 'Comfy.VueNodes.Enabled': true, 'Comfy.Graph.CanvasInfo': false }, - // The replayed nodes materialize from registered node types. objectInfo: 'server' }) - // Re-targeting the fresh tab saves it as a new cloud workflow. These - // routes go on after boot so they win over the boot mocks' userdata stub. const savedFiles: UserDataFullInfo[] = [] await page.route('**/api/userdata?*', (route) => { const dir = new URL(route.request().url()).searchParams.get('dir') @@ -224,7 +212,6 @@ test.describe( .getByTestId('node-title') .allTextContents() - // A brand-new page on the surviving thread: nobody has sent anything. const agentPanel = new AgentPanel(page) await agentPanel.open() const panel = agentPanel.root @@ -232,14 +219,12 @@ test.describe( await expect(panel.getByTestId('user-message-bubble')).toHaveText([ EARLIER_REQUEST ]) - // The Cloud no longer lists the abandoned workflow, so the chat says so. const unavailable = panel.getByText( enMessages.agent.targetWorkflowUnavailable ) await expect(unavailable).toBeVisible() if (!socket) throw new Error('the app never opened /ws') - // The user continues the thread in the fresh tab. const workflowPicker = panel.getByRole('button', { name: enMessages.agent.switchWorkflow }) diff --git a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts index 86a302155c6..c8e09f9054d 100644 --- a/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts +++ b/browser_tests/tests/agent/agentZeroNodesOnUnreadableSchema.spec.ts @@ -145,17 +145,9 @@ test.describe( typeof state_vector_b64 !== 'string' ) return - // Simulates the unproven trigger this repro exercises (see file - // header): the catch-up frame's merged doc has no readable - // meta.schema_version at all. host.corruptSchemaVersion() send(host.subscribed()) send(host.catchUp(state_vector_b64)) - // Sent as its own later-seq frame -- not folded silently into a - // later apply()'s delta -- so the fix that stops the latch from - // outliving one bad frame is exercised for real: this repair alone - // is enough for the gate to pass again before the add_node frame - // below arrives. send(host.repairSchemaVersion()) }) }) @@ -227,8 +219,6 @@ test.describe( .click() await expect(picker).toHaveText('Unsaved Workflow') - // Setup checkpoint, still expected to pass: the doc subscription round - // trip (with its corrupted catch-up) actually completed. await expect.poll(() => socket !== null).toBe(true) const composer = panel.getByRole('textbox', { @@ -261,8 +251,6 @@ test.describe( } }) - // The op lands on the host's own authoritative document, and is sent to - // the browser the same way agentConversationFixture's replay does. send( host.apply([ { @@ -301,8 +289,6 @@ test.describe( data: { thread_id: THREAD_ID, message_id: MESSAGE_ID, usage: null } }) - // Setup checkpoint, still expected to pass: the agent's turn completes - // and reports success in the panel — "agent says done". await expect( panel.getByRole('button', { name: SEND_LABEL }) ).toBeVisible() @@ -311,12 +297,6 @@ test.describe( ) await expect(panel.getByRole('button', { name: /^Worked/ })).toBeVisible() - // The fix under test: the agent said it added the note, and the op is - // on the host's own record (asserted above) -- both it and the earlier - // schema-version repair were sent as their own frames. The repair - // un-latches the schema gate before the add_node frame arrives, so the - // node reaches the canvas the user is looking at instead of being - // silently dropped alongside it. await expect(vueNodes.getNodeLocator(String(ADDED_NODE_ID))).toBeVisible() }) } From 8495f30078145b3c1ea84a271631027501ca14e4 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:23:17 +0800 Subject: [PATCH 12/66] test(agent): cover Chat history listing a chat from a second page Serves the thread list as two cursor pages and checks that Chat history shows a chat from each, after requesting limit=100 and then the second page's cursor. The page data lives next to emptyAgentThreadList. --- .../fixtures/data/agent/agentThreadList.ts | 41 +++++++++++- .../agent/agentChatHistoryPagination.spec.ts | 64 +++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 browser_tests/tests/agent/agentChatHistoryPagination.spec.ts diff --git a/browser_tests/fixtures/data/agent/agentThreadList.ts b/browser_tests/fixtures/data/agent/agentThreadList.ts index 8bdf8189e1a..dc7def692c9 100644 --- a/browser_tests/fixtures/data/agent/agentThreadList.ts +++ b/browser_tests/fixtures/data/agent/agentThreadList.ts @@ -1,4 +1,11 @@ -import type { AgentThreadListResponse } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + AgentThreadSummary +} from '@comfyorg/ingest-types' + +const LISTED_AT = '2026-10-01T00:00:00Z' + +export const SECOND_THREAD_PAGE_CURSOR = 'thread-page-2' export function emptyAgentThreadList(): AgentThreadListResponse { return { @@ -6,3 +13,35 @@ export function emptyAgentThreadList(): AgentThreadListResponse { pagination: { has_more: false, limit: 100, offset: 0, total: 0 } } } + +function agentThreadSummary(id: string, title: string): AgentThreadSummary { + return { + id, + title, + preview: title, + status: 'active', + message_count: 1, + created_at: LISTED_AT, + updated_at: LISTED_AT, + last_message_at: LISTED_AT, + workflow_id: '' + } +} + +export const firstAgentThreadPage: AgentThreadListResponse = { + threads: [agentThreadSummary('thread-first-page', 'Chat on the first page')], + pagination: { + has_more: true, + next_cursor: SECOND_THREAD_PAGE_CURSOR, + limit: 100, + offset: 0, + total: 0 + } +} + +export const secondAgentThreadPage: AgentThreadListResponse = { + threads: [ + agentThreadSummary('thread-second-page', 'Chat on the second page') + ], + pagination: { has_more: false, limit: 100, offset: 0, total: 0 } +} diff --git a/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts b/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts new file mode 100644 index 00000000000..1e68b298b3d --- /dev/null +++ b/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts @@ -0,0 +1,64 @@ +import { expect } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } + +import { + agentTest as test, + bootAgentApp +} from '@e2e/fixtures/agentPanelFixture' +import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { + SECOND_THREAD_PAGE_CURSOR, + firstAgentThreadPage, + secondAgentThreadPage +} from '@e2e/fixtures/data/agent/agentThreadList' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' + +const PANEL_MOUNT_TIMEOUT = 30_000 + +test.describe( + 'Agent chat history pagination', + { tag: ['@cloud', '@ui'] }, + () => { + test('lists chats from every page of the thread list', async ({ + page, + agentFlagEnabled + }) => { + const threadListQueries: string[] = [] + await page.route('**/api/agent/threads?*', (route) => { + const { search, searchParams } = new URL(route.request().url()) + threadListQueries.push(search) + return route.fulfill( + jsonRoute( + searchParams.get('after') === SECOND_THREAD_PAGE_CURSOR + ? secondAgentThreadPage + : firstAgentThreadPage + ) + ) + }) + + await bootAgentApp(page, agentFlagEnabled) + const panel = await new AgentPanel(page).open(PANEL_MOUNT_TIMEOUT) + await panel + .getByRole('button', { name: enMessages.agent.showChatHistory }) + .click() + + await expect( + panel.getByRole('button', { + name: firstAgentThreadPage.threads[0].title, + exact: true + }) + ).toBeVisible() + await expect( + panel.getByRole('button', { + name: secondAgentThreadPage.threads[0].title, + exact: true + }) + ).toBeVisible() + expect(threadListQueries[0]).toBe('?limit=100') + expect(threadListQueries).toContain( + `?limit=100&after=${SECOND_THREAD_PAGE_CURSOR}` + ) + }) + } +) From f75f23ae1d01d1eb74106192a923acb1744b0656 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:40:10 +0800 Subject: [PATCH 13/66] test(agent): type the paging overrides in chat history tests The incomplete-list and closed-panel tests spread a hand-written pagination object over agentThreadList, which json() accepts as unknown. agentThreadList now takes a typed partial pagination, so a wrong field fails typecheck. --- .../extensions/agent/AgentPanelRoot.test.ts | 59 ++++++++++--------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 3047d049c31..5276e336771 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -6,6 +6,7 @@ import type { AgentThreadListResponse, AgentThreadSummary, BillingStatus, + PaginationInfo, SubscriptionTier } from '@comfyorg/ingest-types' import { render, screen, waitFor, within } from '@testing-library/vue' @@ -504,7 +505,8 @@ function isThreadListUrl(url: string): boolean { } function agentThreadList( - threads: AgentThreadSummary[] = [] + threads: AgentThreadSummary[] = [], + pagination: Partial = {} ): AgentThreadListResponse { return { threads, @@ -512,7 +514,8 @@ function agentThreadList( has_more: false, limit: Math.max(threads.length, 1), offset: 0, - total: threads.length + total: threads.length, + ...pagination } } } @@ -5319,16 +5322,19 @@ describe('AgentPanelRoot history', () => { expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) ) respondToFetch(/\/api\/agent\/threads\?/, () => - json(200, { - ...agentThreadList([ - agentThread({ - id: 'th-partial', - title: 'Partial chat', - last_message_at: '2026-07-07T11:00:00Z' - }) - ]), - pagination: { has_more: true, limit: 1, offset: 0, total: 2 } - }) + json( + 200, + agentThreadList( + [ + agentThread({ + id: 'th-partial', + title: 'Partial chat', + last_message_at: '2026-07-07T11:00:00Z' + }) + ], + { has_more: true, total: 2 } + ) + ) ) await userEvent.click( @@ -5446,22 +5452,19 @@ describe('AgentPanelRoot history', () => { }) respondToFetch({}, () => json(200, [])) respondToFetch(threadListRoute, () => - json(200, { - ...agentThreadList([ - agentThread({ - id: 'th-old', - title: 'Old chat', - last_message_at: '2026-07-07T08:00:00Z' - }) - ]), - pagination: { - has_more: true, - next_cursor: 'page-2', - limit: 1, - offset: 0, - total: 2 - } - }) + json( + 200, + agentThreadList( + [ + agentThread({ + id: 'th-old', + title: 'Old chat', + last_message_at: '2026-07-07T08:00:00Z' + }) + ], + { has_more: true, next_cursor: 'page-2', total: 2 } + ) + ) ) respondToFetch(secondPageRoute, () => staleSecondPage, { times: 1 }) const closedPanel = renderWithSelectedTarget() From 8325a3e0fb7dfa043b17d2034fb335185032798f Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:41:25 +0800 Subject: [PATCH 14/66] test(agent): name the non-retryable report in the incomplete-list test The test also checks that an incomplete list opens the error overlay and is tracked as not retryable, and it is the only test that does. --- src/workbench/extensions/agent/AgentPanelRoot.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 5276e336771..837087ec640 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5302,7 +5302,7 @@ describe('AgentPanelRoot history', () => { expect(useAgentChatHistoryStore().sessions).toHaveLength(0) }) - it('keeps the loaded chat list when a refresh ends before its last page', async () => { + it('keeps the loaded chat list and reports a non-retryable failure when a refresh ends before its last page', async () => { respondToFetch({}, () => json(200, [])) respondToFetch(/\/api\/agent\/threads\?/, () => json( From f29f7ddadc79bdf4f6904eb778b9b8959ea9e66a Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:41:39 +0800 Subject: [PATCH 15/66] test(agent): keep the page-2 spec to what the user sees The request queries are already pinned by the listThreads unit tests, and the second-page chat can only show if its cursor was followed. The panel timeout is inlined like the sibling specs. --- .../tests/agent/agentChatHistoryPagination.spec.ts | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts b/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts index 1e68b298b3d..0f1fdf4e10a 100644 --- a/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts +++ b/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts @@ -14,8 +14,6 @@ import { } from '@e2e/fixtures/data/agent/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' -const PANEL_MOUNT_TIMEOUT = 30_000 - test.describe( 'Agent chat history pagination', { tag: ['@cloud', '@ui'] }, @@ -24,13 +22,11 @@ test.describe( page, agentFlagEnabled }) => { - const threadListQueries: string[] = [] await page.route('**/api/agent/threads?*', (route) => { - const { search, searchParams } = new URL(route.request().url()) - threadListQueries.push(search) + const after = new URL(route.request().url()).searchParams.get('after') return route.fulfill( jsonRoute( - searchParams.get('after') === SECOND_THREAD_PAGE_CURSOR + after === SECOND_THREAD_PAGE_CURSOR ? secondAgentThreadPage : firstAgentThreadPage ) @@ -38,7 +34,7 @@ test.describe( }) await bootAgentApp(page, agentFlagEnabled) - const panel = await new AgentPanel(page).open(PANEL_MOUNT_TIMEOUT) + const panel = await new AgentPanel(page).open(30_000) await panel .getByRole('button', { name: enMessages.agent.showChatHistory }) .click() @@ -55,10 +51,6 @@ test.describe( exact: true }) ).toBeVisible() - expect(threadListQueries[0]).toBe('?limit=100') - expect(threadListQueries).toContain( - `?limit=100&after=${SECOND_THREAD_PAGE_CURSOR}` - ) }) } ) From 99951ade2021f30b73b5ee34e2ba2d0f9c143ad9 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:41:45 +0800 Subject: [PATCH 16/66] test(agent): type the remaining thread-list mock bodies The turn-lock fixture and the listThreads paging helper now check their bodies against AgentThreadListResponse, like the other thread-list mocks. --- browser_tests/fixtures/agentTurnLockFixture.ts | 3 ++- .../agent/services/agent/agentRestClient.test.ts | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/browser_tests/fixtures/agentTurnLockFixture.ts b/browser_tests/fixtures/agentTurnLockFixture.ts index 3336f04e235..bb9e412a8bc 100644 --- a/browser_tests/fixtures/agentTurnLockFixture.ts +++ b/browser_tests/fixtures/agentTurnLockFixture.ts @@ -7,6 +7,7 @@ import type { AgentError, AgentMessage, AgentPendingAsk, + AgentThreadListResponse, AgentTurnAccepted } from '@comfyorg/ingest-types' import { @@ -429,7 +430,7 @@ async function routeTurnLock( } ], pagination: { offset: 0, limit: 100, total: 2, has_more: false } - }) + } satisfies AgentThreadListResponse) ) ) await page.route('**/api/agent/threads/*/messages', async (route) => { diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index 264d284434f..a9b8bb8fa41 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -1,4 +1,7 @@ -import type { PaginationInfo } from '@comfyorg/ingest-types' +import type { + AgentThreadListResponse, + PaginationInfo +} from '@comfyorg/ingest-types' import { describe, expect, it, vi } from 'vitest' import { @@ -345,7 +348,7 @@ describe('listThreads pagination', () => { return jsonResponse(200, { threads, pagination: { offset: 0, limit: 100, total: 0, has_more, next_cursor } - }) + } satisfies AgentThreadListResponse) } it('follows next_cursor at the maximum page size until has_more is false', async () => { From a95ea49a363aaa76be37752e8ba68178fa27e350 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:42:00 +0800 Subject: [PATCH 17/66] refactor(agent): drop the JSDoc on AgentThreadListIncompleteError It restated the class name and message, and the sibling error classes have none. --- src/workbench/extensions/agent/services/agent/agentRestClient.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 623e3f5ce51..18331e4d395 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -170,7 +170,6 @@ export class AgentResponseUnreadableError extends Error { type PaginationStop = 'missing_cursor' | 'repeated_cursor' -/** The thread list's pagination stopped before its last page. */ export class AgentThreadListIncompleteError extends Error { readonly reason: PaginationStop From e6d9762b3645a56cf161cd2b9425e769db65e2ef Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:48:17 +0800 Subject: [PATCH 18/66] fix(agent): stop chat history refreshes when the panel closes Closing the panel only marked the refreshes already in flight as replaced. Picking a chat and closing the panel before it loaded still started a new refresh afterwards, which could open the error overlay with the panel closed or replace a reopened panel's list, and an abandoned refresh kept fetching its remaining pages. The panel now aborts its history requests when it closes and starts no refresh after that. listThreads takes an abort signal like getMessages. --- .../extensions/agent/AgentPanelRoot.test.ts | 50 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 13 +++-- .../composables/agent/useAgentSession.ts | 4 +- .../services/agent/agentRestClient.test.ts | 12 +++++ .../agent/services/agent/agentRestClient.ts | 12 +++-- 5 files changed, 80 insertions(+), 11 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 837087ec640..4656b783f5a 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5472,6 +5472,12 @@ describe('AgentPanelRoot history', () => { expect(fetchRequests(secondPageRoute)).toHaveLength(1) ) closedPanel.unmount() + const [, secondPageInit] = + vi + .mocked(fetch) + .mock.calls.find(([input]) => secondPageRoute.test(String(input))) ?? + [] + expect(secondPageInit?.signal?.aborted).toBe(true) respondToFetch(threadListRoute, () => json( 200, @@ -5500,6 +5506,50 @@ describe('AgentPanelRoot history', () => { } ) + it('does not refresh chat history once the panel closes while a picked chat loads', async () => { + const threadListRoute = /\/api\/agent\/threads\?/ + const pickedMessagesRoute = /\/th-picked\/messages/ + let resolveMessages!: (response: Response) => void + const pickedMessages = new Promise((resolve) => { + resolveMessages = resolve + }) + respondToFetch({}, () => json(200, [])) + respondToFetch(threadListRoute, () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-picked', + title: 'Picked chat', + last_message_at: '2026-07-07T10:00:00Z' + }) + ]) + ) + ) + respondToFetch(pickedMessagesRoute, () => pickedMessages, { times: 1 }) + const panel = renderWithSelectedTarget() + await userEvent.click( + await screen.findByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click( + await screen.findByRole('button', { name: 'Picked chat' }) + ) + await vi.waitFor(() => + expect(fetchRequests(pickedMessagesRoute)).toHaveLength(1) + ) + const listRequestsBeforeClose = fetchRequests(threadListRoute).length + panel.unmount() + + const messages = json(200, []) + resolveMessages(messages) + await vi.waitFor(() => expect(messages.bodyUsed).toBe(true)) + + expect(fetchRequests(threadListRoute)).toHaveLength(listRequestsBeforeClose) + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + }) + it('marks the restored thread as the current session', async () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index a18ab1d2e88..3acce9c5355 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1412,15 +1412,18 @@ function toChatSession(thread: AgentThreadSummary): ChatSession { } let historyRefreshGeneration = 0 +const historyRefreshAbort = new AbortController() async function refreshHistory(): Promise { + const { signal } = historyRefreshAbort + if (signal.aborted) return const generation = ++historyRefreshGeneration try { - const threads = await listThreads() - if (generation === historyRefreshGeneration) + const threads = await listThreads({ signal }) + if (!signal.aborted && generation === historyRefreshGeneration) history.replaceAll(threads.map(toChatSession)) } catch (error) { - if (generation !== historyRefreshGeneration) return + if (signal.aborted || generation !== historyRefreshGeneration) return reportError(error, { surface: 'agent', errorType: 'agent_thread_list_load_failed' @@ -1441,8 +1444,8 @@ async function refreshHistory(): Promise { void refreshHistory() onBeforeUnmount(() => runPanelTeardown({ - invalidateHistoryRefreshGeneration: () => { - ++historyRefreshGeneration + abortHistoryRefreshes: () => { + historyRefreshAbort.abort() } }) ) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 47adbde7a31..7894182af9b 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -1597,8 +1597,8 @@ export function useAgentSession(deps: AgentSessionDeps) { pendingThreadSource.value = source ?? null } - function listThreads() { - return rest.listThreads() + function listThreads(options?: { signal?: AbortSignal }) { + return rest.listThreads(options) } async function loadThread( diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts index a9b8bb8fa41..cd6b0fff313 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.test.ts @@ -390,6 +390,18 @@ describe('listThreads pagination', () => { } ) + it('passes the caller abort signal to every page request', async () => { + respond(threadPage(['th-1'], { has_more: true, next_cursor: 'page-2' })) + respond(threadPage(['th-2'], { has_more: false })) + const { signal } = new AbortController() + + await makeClient().listThreads({ signal }) + + expect( + vi.mocked(api.fetchApi).mock.calls.map(([, init]) => init?.signal) + ).toEqual([signal, signal]) + }) + it('rejects instead of returning a partial list when a later page fails', async () => { respond(threadPage(['th-1'], { has_more: true, next_cursor: 'page-2' })) respond(jsonResponse(503, { error: 'unavailable' })) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 18331e4d395..429d0809dad 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -584,7 +584,8 @@ export function createAgentRestClient() { operation: AgentApiOperation, path: string, schema: z.ZodType, - itemsOf: (page: Page) => Item[] + itemsOf: (page: Page) => Item[], + signal?: AbortSignal ): Promise<{ items: Item[]; stop?: PaginationStop }> { const items: Item[] = [] let cursor: string | undefined @@ -594,7 +595,7 @@ export function createAgentRestClient() { const page = await request( operation, `${path}?limit=${LIST_PAGE_SIZE}${after}`, - { method: 'GET' }, + { method: 'GET', signal }, schema ) items.push(...itemsOf(page)) @@ -643,12 +644,15 @@ export function createAgentRestClient() { ) } - async function listThreads(): Promise { + async function listThreads( + options: { signal?: AbortSignal } = {} + ): Promise { const { items, stop } = await listAllPages( 'list_threads', '/agent/threads', zAgentThreads, - (page) => page.threads + (page) => page.threads, + options.signal ) if (stop) throw new AgentThreadListIncompleteError(stop) return items From 3dab65ace8b799a133e2e0ec8ab584aa8e098bfe Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:49:32 +0800 Subject: [PATCH 19/66] fix(agent): keep an older chat history result when a newer refresh fails A refresh was dropped whenever a newer one had started, even if the newer one then failed. With several refreshes in flight, a transient failure on the last one left Chat history on its previous list, or empty on first open, although an earlier refresh had loaded fine. A finished refresh now replaces the list unless a newer one already did; only the newest refresh reports a failure. --- .../extensions/agent/AgentPanelRoot.test.ts | 65 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 6 +- 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 4656b783f5a..edad0deb1d2 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5441,6 +5441,71 @@ describe('AgentPanelRoot history', () => { } ) + it('applies an older history refresh that succeeds after a newer one fails', async () => { + const threadListRoute = /\/api\/agent\/threads\?/ + let resolveOlder!: (response: Response) => void + const olderList = new Promise((resolve) => { + resolveOlder = resolve + }) + const openHistory = async () => + userEvent.click( + await screen.findByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + respondToFetch({}, () => json(200, [])) + respondToFetch(threadListRoute, () => + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-old', + title: 'Old chat', + last_message_at: '2026-07-07T08:00:00Z' + }) + ]) + ) + ) + renderWithSelectedTarget() + const history = useAgentChatHistoryStore() + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-old']) + ) + respondToFetch(threadListRoute, () => olderList, { times: 1 }) + await openHistory() + await vi.waitFor(() => + expect(fetchRequests(threadListRoute)).toHaveLength(2) + ) + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.backToPreviousChat') + }) + ) + respondToFetch(threadListRoute, () => json(500, {})) + await openHistory() + await vi.waitFor(() => + expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) + ) + + resolveOlder( + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-older-refresh', + title: 'Older refresh chat', + last_message_at: '2026-07-07T09:00:00Z' + }) + ]) + ) + ) + + await vi.waitFor(() => + expect(history.sessions.map(({ id }) => id)).toEqual(['th-older-refresh']) + ) + expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) + }) + it.for(staleRefreshOutcomes)( 'ignores a closed panel history refresh that ends with $outcome after the panel reopens', async ({ staleResponse }) => { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 3acce9c5355..0be9b4c1e6f 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1412,6 +1412,7 @@ function toChatSession(thread: AgentThreadSummary): ChatSession { } let historyRefreshGeneration = 0 +let appliedHistoryRefreshGeneration = 0 const historyRefreshAbort = new AbortController() async function refreshHistory(): Promise { @@ -1420,8 +1421,9 @@ async function refreshHistory(): Promise { const generation = ++historyRefreshGeneration try { const threads = await listThreads({ signal }) - if (!signal.aborted && generation === historyRefreshGeneration) - history.replaceAll(threads.map(toChatSession)) + if (signal.aborted || generation < appliedHistoryRefreshGeneration) return + appliedHistoryRefreshGeneration = generation + history.replaceAll(threads.map(toChatSession)) } catch (error) { if (signal.aborted || generation !== historyRefreshGeneration) return reportError(error, { From e24e32946e805310b448e05b62a9d8802e49a88f Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 20:50:41 +0800 Subject: [PATCH 20/66] fix(agent): tag an incomplete thread-list report with its reason AgentThreadListIncompleteError carries whether the server gave no next cursor or repeated one, but the Chat history report dropped it. The report now tags it as reason, so the two cases can be told apart. --- src/workbench/extensions/agent/AgentPanelRoot.test.ts | 4 ++++ src/workbench/extensions/agent/AgentPanelRoot.vue | 11 +++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index edad0deb1d2..b918f82a8d5 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5352,6 +5352,10 @@ describe('AgentPanelRoot history', () => { retryable: false }) ) + expect(reportError).toHaveBeenCalledWith( + expect.objectContaining({ name: 'AgentThreadListIncompleteError' }), + expect.objectContaining({ tags: { reason: 'missing_cursor' } }) + ) expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) }) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 0be9b4c1e6f..60422f88aa9 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -123,7 +123,10 @@ import { } from './composables/agent/useAgentSession' import { useAgentDraftSubmission } from './composables/agent/useAgentDraftSubmission' import { useAgentWorkflowTabBindingStore } from './stores/agent/agentWorkflowTabBindingStore' -import { createAgentRestClient } from './services/agent/agentRestClient' +import { + AgentThreadListIncompleteError, + createAgentRestClient +} from './services/agent/agentRestClient' import type { DraftSnapshot } from './services/agent/agentRestClient' import type { AgentPaywallAction } from './services/agent/agentPaywallPresentation' import { @@ -1428,7 +1431,11 @@ async function refreshHistory(): Promise { if (signal.aborted || generation !== historyRefreshGeneration) return reportError(error, { surface: 'agent', - errorType: 'agent_thread_list_load_failed' + errorType: 'agent_thread_list_load_failed', + tags: + error instanceof AgentThreadListIncompleteError + ? { reason: error.reason } + : undefined }) surfaceAgentError( 'agent_api_failed', From c7b064227e36fcc0d24dc6db90490fbb3f06fa78 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 21:10:12 +0800 Subject: [PATCH 21/66] test(agent): cover the aborted history request when the panel closes Closing the panel aborts its history request, which rejects with an AbortError. The test checks that this is not reported, shown in the error overlay or tracked as an agent error. --- .../extensions/agent/AgentPanelRoot.test.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index b918f82a8d5..c542596876d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5575,6 +5575,34 @@ describe('AgentPanelRoot history', () => { } ) + it('does not report the history request it aborts when the panel closes', async () => { + const threadListRoute = /\/api\/agent\/threads\?/ + respondToFetch({}, () => json(200, [])) + respondToFetch( + threadListRoute, + (_input, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => + reject(init.signal?.reason) + ) + }) + ) + const panel = renderWithSelectedTarget() + await vi.waitFor(() => + expect(fetchRequests(threadListRoute)).toHaveLength(1) + ) + + panel.unmount() + await setImmediate() + + expect(reportError).not.toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ errorType: 'agent_thread_list_load_failed' }) + ) + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + expect(telemetry.trackAgentError).not.toHaveBeenCalled() + }) + it('does not refresh chat history once the panel closes while a picked chat loads', async () => { const threadListRoute = /\/api\/agent\/threads\?/ const pickedMessagesRoute = /\/th-picked\/messages/ From 58230c400df224543c983d9103e334b907b9d889 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:27:58 +0800 Subject: [PATCH 22/66] test(agent): build the thread-list fixture pages one way Each fixture page now comes from one helper that writes the pagination once. The pagination spec reads the cursor from the first page. --- .../fixtures/data/agent/agentThreadList.ts | 42 ++++++++++--------- .../agent/agentChatHistoryPagination.spec.ts | 3 +- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/browser_tests/fixtures/data/agent/agentThreadList.ts b/browser_tests/fixtures/data/agent/agentThreadList.ts index dc7def692c9..c839a2f4b02 100644 --- a/browser_tests/fixtures/data/agent/agentThreadList.ts +++ b/browser_tests/fixtures/data/agent/agentThreadList.ts @@ -5,12 +5,19 @@ import type { const LISTED_AT = '2026-10-01T00:00:00Z' -export const SECOND_THREAD_PAGE_CURSOR = 'thread-page-2' - -export function emptyAgentThreadList(): AgentThreadListResponse { +function agentThreadPage( + threads: AgentThreadSummary[], + nextCursor?: string +): AgentThreadListResponse { return { - threads: [], - pagination: { has_more: false, limit: 100, offset: 0, total: 0 } + threads, + pagination: { + has_more: nextCursor !== undefined, + ...(nextCursor !== undefined && { next_cursor: nextCursor }), + limit: 100, + offset: 0, + total: 0 + } } } @@ -28,20 +35,15 @@ function agentThreadSummary(id: string, title: string): AgentThreadSummary { } } -export const firstAgentThreadPage: AgentThreadListResponse = { - threads: [agentThreadSummary('thread-first-page', 'Chat on the first page')], - pagination: { - has_more: true, - next_cursor: SECOND_THREAD_PAGE_CURSOR, - limit: 100, - offset: 0, - total: 0 - } +export function emptyAgentThreadList(): AgentThreadListResponse { + return agentThreadPage([]) } -export const secondAgentThreadPage: AgentThreadListResponse = { - threads: [ - agentThreadSummary('thread-second-page', 'Chat on the second page') - ], - pagination: { has_more: false, limit: 100, offset: 0, total: 0 } -} +export const firstAgentThreadPage = agentThreadPage( + [agentThreadSummary('thread-first-page', 'Chat on the first page')], + 'thread-page-2' +) + +export const secondAgentThreadPage = agentThreadPage([ + agentThreadSummary('thread-second-page', 'Chat on the second page') +]) diff --git a/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts b/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts index 0f1fdf4e10a..d45eadb11a3 100644 --- a/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts +++ b/browser_tests/tests/agent/agentChatHistoryPagination.spec.ts @@ -8,7 +8,6 @@ import { } from '@e2e/fixtures/agentPanelFixture' import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' import { - SECOND_THREAD_PAGE_CURSOR, firstAgentThreadPage, secondAgentThreadPage } from '@e2e/fixtures/data/agent/agentThreadList' @@ -26,7 +25,7 @@ test.describe( const after = new URL(route.request().url()).searchParams.get('after') return route.fulfill( jsonRoute( - after === SECOND_THREAD_PAGE_CURSOR + after === firstAgentThreadPage.pagination.next_cursor ? secondAgentThreadPage : firstAgentThreadPage ) From 5b13bbb4f61bfd110e1c7b5b7278b15d50007a22 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:28:13 +0800 Subject: [PATCH 23/66] test(agent): drop comments above the helpers this PR changed Removes the comment blocks above startTurn, driveThroughDocReset and driveThroughToolCallDone. No code changes. --- .../agentCanvasBlanksDuringRunTurn.spec.ts | 18 ------------------ .../agentCanvasLagsToolCallCompletion.spec.ts | 9 --------- .../tests/agent/agentReplyDrafts.spec.ts | 3 --- 3 files changed, 30 deletions(-) diff --git a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts index 7db75b1c10b..afc852253f7 100644 --- a/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts +++ b/browser_tests/tests/agent/agentCanvasBlanksDuringRunTurn.spec.ts @@ -167,24 +167,6 @@ async function expectNodeSurvivedReplacement(page: Page): Promise { ).toBeVisible() } -/** - * Drives a plain "run the workflow" turn up through a mid-turn `doc_reset` - * whose post-reset resubscribes have their catch-up withheld per - * `dropCatchUpAfterReset`, and asserts the canvas keeps its two nodes the - * moment the reset lands. The host doc gains `RESET_LINEAGE_NODE_ID` right - * after the reset, so only a delivered catch-up can put a third node on the - * canvas. Shared by the permanent-drop run (`driveRunTurnThroughRun`) and - * the transient one-off-drop recovery proof - * (`driveRunTurnThroughTransientCatchUpDrop`) below -- they differ only in - * how many of the resubscribes that follow the reset get their catch-up - * withheld. - * - * `dropCatchUpAfterReset` is asked, for each `doc_subscribe` the mock - * receives AFTER the reset, whether that resubscribe (1-indexed, in receipt - * order) should have its catch-up withheld. The subscribe sent before the - * reset (the initial workflow-picker subscribe) always gets its catch-up -- - * matching the baseline "two nodes visible" assertion below. - */ async function driveThroughDocReset( page: Page, dropCatchUpAfterReset: (resubscribeCountAfterReset: number) => boolean diff --git a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts index a291e0e61e4..0669bf4a98e 100644 --- a/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts +++ b/browser_tests/tests/agent/agentCanvasLagsToolCallCompletion.spec.ts @@ -110,15 +110,6 @@ function subscribeStateVectorOf(raw: Buffer | string): string | null { return state_vector_b64 } -/** - * Drives one "add a note to the canvas" turn through to the agent reporting - * it done -- the tool call's own completion AND the turn's "Worked for Xs" - * summary, matching the bug report's "every working affordance" -- while the - * doc host has ALREADY recorded the `add_node` op authoritatively - * (`host.apply` below) but its broadcast `doc_update` is deliberately held - * back. Callers decide when (if ever) to release it via the returned - * `sendDelayedDocUpdate`. - */ async function driveThroughToolCallDone( page: Page, order: diff --git a/browser_tests/tests/agent/agentReplyDrafts.spec.ts b/browser_tests/tests/agent/agentReplyDrafts.spec.ts index 4deb5eb105b..b17e0de1d35 100644 --- a/browser_tests/tests/agent/agentReplyDrafts.spec.ts +++ b/browser_tests/tests/agent/agentReplyDrafts.spec.ts @@ -55,9 +55,6 @@ interface Turn { send: (frame: AgentWsEvent | HostFrame) => void } -// Boots the agent panel on a fresh canvas and sends one user message, answering -// the document subscription the way the host does, so every frame after it is -// the agent's. async function startTurn(page: Page, prompt: string): Promise { const host = new HostDoc(WORKFLOW_ID, SEED, CATALOG) let socket: WebSocketRoute | null = null From 9c83f4be2c29b6b6f8d927647b0886ef9e58b39c Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:30:02 +0800 Subject: [PATCH 24/66] test(agent): drop the aborted-request test the stale table covers It stays green with the abort or the signal removed, and the closed-panel failure row of the stale-refresh table already catches the one mutation it catches. --- .../extensions/agent/AgentPanelRoot.test.ts | 28 ------------------- 1 file changed, 28 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index c542596876d..b918f82a8d5 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5575,34 +5575,6 @@ describe('AgentPanelRoot history', () => { } ) - it('does not report the history request it aborts when the panel closes', async () => { - const threadListRoute = /\/api\/agent\/threads\?/ - respondToFetch({}, () => json(200, [])) - respondToFetch( - threadListRoute, - (_input, init) => - new Promise((_resolve, reject) => { - init?.signal?.addEventListener('abort', () => - reject(init.signal?.reason) - ) - }) - ) - const panel = renderWithSelectedTarget() - await vi.waitFor(() => - expect(fetchRequests(threadListRoute)).toHaveLength(1) - ) - - panel.unmount() - await setImmediate() - - expect(reportError).not.toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ errorType: 'agent_thread_list_load_failed' }) - ) - expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() - expect(telemetry.trackAgentError).not.toHaveBeenCalled() - }) - it('does not refresh chat history once the panel closes while a picked chat loads', async () => { const threadListRoute = /\/api\/agent\/threads\?/ const pickedMessagesRoute = /\/th-picked\/messages/ From 1dfcd46e56b9ef443720f0e7c01dcc809b3ca24a Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:30:16 +0800 Subject: [PATCH 25/66] test(agent): share the setup of the chat history tests The history tests now share one thread-list route, the catch-all fetch answer and openHistory at the describe level. Drops the total filler from the paging overrides and an assertion that repeated the overlay check. --- .../extensions/agent/AgentPanelRoot.test.ts | 75 ++++++------------- 1 file changed, 23 insertions(+), 52 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index b918f82a8d5..062921d437d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -4935,10 +4935,24 @@ describe('AgentPanelRoot canvas draft on send', () => { }) describe('AgentPanelRoot history', () => { + const threadListRoute = /\/api\/agent\/threads\?/ + beforeEach(() => { ws.clear() + respondToFetch({}, () => json(200, [])) }) + async function openHistory(): Promise { + await userEvent.click( + await screen.findByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await screen.findByRole('heading', { + name: i18n.global.t('agent.history') + }) + } + async function renderWithActiveThread(): Promise { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) @@ -5233,17 +5247,6 @@ describe('AgentPanelRoot history', () => { useAgentConversationStore().setThreadId('th-active') } - async function openHistory(): Promise { - await userEvent.click( - await screen.findByRole('button', { - name: i18n.global.t('agent.showChatHistory') - }) - ) - await screen.findByRole('heading', { - name: i18n.global.t('agent.history') - }) - } - it('shows the first user message while the server title is empty', async () => { stubActiveThread('') renderWithSelectedTarget() @@ -5303,8 +5306,7 @@ describe('AgentPanelRoot history', () => { }) it('keeps the loaded chat list and reports a non-retryable failure when a refresh ends before its last page', async () => { - respondToFetch({}, () => json(200, [])) - respondToFetch(/\/api\/agent\/threads\?/, () => + respondToFetch(threadListRoute, () => json( 200, agentThreadList([ @@ -5321,7 +5323,7 @@ describe('AgentPanelRoot history', () => { await vi.waitFor(() => expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) ) - respondToFetch(/\/api\/agent\/threads\?/, () => + respondToFetch(threadListRoute, () => json( 200, agentThreadList( @@ -5332,16 +5334,12 @@ describe('AgentPanelRoot history', () => { last_message_at: '2026-07-07T11:00:00Z' }) ], - { has_more: true, total: 2 } + { has_more: true } ) ) ) - await userEvent.click( - await screen.findByRole('button', { - name: i18n.global.t('agent.showChatHistory') - }) - ) + await openHistory() await vi.waitFor(() => expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) @@ -5380,18 +5378,10 @@ describe('AgentPanelRoot history', () => { it.for(staleRefreshOutcomes)( 'ignores an older history refresh that ends with $outcome after a newer one', async ({ staleResponse }) => { - const threadListRoute = /\/api\/agent\/threads\?/ let resolveStale!: (response: Response) => void const staleList = new Promise((resolve) => { resolveStale = resolve }) - const openHistory = async () => - userEvent.click( - await screen.findByRole('button', { - name: i18n.global.t('agent.showChatHistory') - }) - ) - respondToFetch({}, () => json(200, [])) respondToFetch(threadListRoute, () => json( 200, @@ -5446,18 +5436,10 @@ describe('AgentPanelRoot history', () => { ) it('applies an older history refresh that succeeds after a newer one fails', async () => { - const threadListRoute = /\/api\/agent\/threads\?/ let resolveOlder!: (response: Response) => void const olderList = new Promise((resolve) => { resolveOlder = resolve }) - const openHistory = async () => - userEvent.click( - await screen.findByRole('button', { - name: i18n.global.t('agent.showChatHistory') - }) - ) - respondToFetch({}, () => json(200, [])) respondToFetch(threadListRoute, () => json( 200, @@ -5513,13 +5495,11 @@ describe('AgentPanelRoot history', () => { it.for(staleRefreshOutcomes)( 'ignores a closed panel history refresh that ends with $outcome after the panel reopens', async ({ staleResponse }) => { - const threadListRoute = /\/api\/agent\/threads\?/ const secondPageRoute = /\/api\/agent\/threads\?.*after=page-2/ let resolveStale!: (response: Response) => void const staleSecondPage = new Promise((resolve) => { resolveStale = resolve }) - respondToFetch({}, () => json(200, [])) respondToFetch(threadListRoute, () => json( 200, @@ -5531,7 +5511,7 @@ describe('AgentPanelRoot history', () => { last_message_at: '2026-07-07T08:00:00Z' }) ], - { has_more: true, next_cursor: 'page-2', total: 2 } + { has_more: true, next_cursor: 'page-2' } ) ) ) @@ -5541,11 +5521,9 @@ describe('AgentPanelRoot history', () => { expect(fetchRequests(secondPageRoute)).toHaveLength(1) ) closedPanel.unmount() - const [, secondPageInit] = - vi - .mocked(fetch) - .mock.calls.find(([input]) => secondPageRoute.test(String(input))) ?? - [] + const secondPageInit = vi + .mocked(fetch) + .mock.calls.find(([input]) => secondPageRoute.test(String(input)))?.[1] expect(secondPageInit?.signal?.aborted).toBe(true) respondToFetch(threadListRoute, () => json( @@ -5571,18 +5549,15 @@ describe('AgentPanelRoot history', () => { expect(history.sessions.map(({ id }) => id)).toEqual(['th-new']) expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() - expect(telemetry.trackAgentError).not.toHaveBeenCalled() } ) it('does not refresh chat history once the panel closes while a picked chat loads', async () => { - const threadListRoute = /\/api\/agent\/threads\?/ const pickedMessagesRoute = /\/th-picked\/messages/ let resolveMessages!: (response: Response) => void const pickedMessages = new Promise((resolve) => { resolveMessages = resolve }) - respondToFetch({}, () => json(200, [])) respondToFetch(threadListRoute, () => json( 200, @@ -5597,11 +5572,7 @@ describe('AgentPanelRoot history', () => { ) respondToFetch(pickedMessagesRoute, () => pickedMessages, { times: 1 }) const panel = renderWithSelectedTarget() - await userEvent.click( - await screen.findByRole('button', { - name: i18n.global.t('agent.showChatHistory') - }) - ) + await openHistory() await userEvent.click( await screen.findByRole('button', { name: 'Picked chat' }) ) From d5689bed6a706672b8d08bc72e53a12b9143eb3f Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:30:29 +0800 Subject: [PATCH 26/66] refactor(agent): name the paging stop reason PaginationStop becomes the exported PaginationStopReason, since it types the public reason field of AgentThreadListIncompleteError, and listAllPages returns it as stopReason. --- .../agent/services/agent/agentRestClient.ts | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/workbench/extensions/agent/services/agent/agentRestClient.ts b/src/workbench/extensions/agent/services/agent/agentRestClient.ts index 429d0809dad..ebb2c483d71 100644 --- a/src/workbench/extensions/agent/services/agent/agentRestClient.ts +++ b/src/workbench/extensions/agent/services/agent/agentRestClient.ts @@ -168,12 +168,12 @@ export class AgentResponseUnreadableError extends Error { } } -type PaginationStop = 'missing_cursor' | 'repeated_cursor' +export type PaginationStopReason = 'missing_cursor' | 'repeated_cursor' export class AgentThreadListIncompleteError extends Error { - readonly reason: PaginationStop + readonly reason: PaginationStopReason - constructor(reason: PaginationStop) { + constructor(reason: PaginationStopReason) { super('Agent thread list ended before its last page') this.name = 'AgentThreadListIncompleteError' this.reason = reason @@ -586,7 +586,7 @@ export function createAgentRestClient() { schema: z.ZodType, itemsOf: (page: Page) => Item[], signal?: AbortSignal - ): Promise<{ items: Item[]; stop?: PaginationStop }> { + ): Promise<{ items: Item[]; stopReason?: PaginationStopReason }> { const items: Item[] = [] let cursor: string | undefined const seenCursors = new Set() @@ -601,8 +601,9 @@ export function createAgentRestClient() { items.push(...itemsOf(page)) if (!page.pagination.has_more) return { items } const nextCursor = page.pagination.next_cursor - if (!nextCursor) return { items, stop: 'missing_cursor' } - if (seenCursors.has(nextCursor)) return { items, stop: 'repeated_cursor' } + if (!nextCursor) return { items, stopReason: 'missing_cursor' } + if (seenCursors.has(nextCursor)) + return { items, stopReason: 'repeated_cursor' } seenCursors.add(nextCursor) cursor = nextCursor } @@ -647,14 +648,14 @@ export function createAgentRestClient() { async function listThreads( options: { signal?: AbortSignal } = {} ): Promise { - const { items, stop } = await listAllPages( + const { items, stopReason } = await listAllPages( 'list_threads', '/agent/threads', zAgentThreads, (page) => page.threads, options.signal ) - if (stop) throw new AgentThreadListIncompleteError(stop) + if (stopReason) throw new AgentThreadListIncompleteError(stopReason) return items } @@ -679,13 +680,13 @@ export function createAgentRestClient() { } async function listCloudWorkflows(): Promise { - const { items, stop } = await listAllPages( + const { items, stopReason } = await listAllPages( 'list_cloud_workflows', '/workflows', zCloudWorkflowIndex, (page) => page.data ) - return { entries: items, complete: stop === undefined } + return { entries: items, complete: stopReason === undefined } } async function getCloudWorkflow( From e27509c00fcc949f4fe12620eb3e3b1758ed6daa Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:30:41 +0800 Subject: [PATCH 27/66] refactor(agent): pass rest.listThreads through directly The session's listThreads only forwarded its arguments to the REST client, which does not depend on this. --- .../extensions/agent/composables/agent/useAgentSession.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index 7894182af9b..89337b68ef3 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -1597,9 +1597,7 @@ export function useAgentSession(deps: AgentSessionDeps) { pendingThreadSource.value = source ?? null } - function listThreads(options?: { signal?: AbortSignal }) { - return rest.listThreads(options) - } + const listThreads = rest.listThreads async function loadThread( threadId: string, From 6d8a4509e12183299e603544f95d2d654d3f5030 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:45:45 +0800 Subject: [PATCH 28/66] test(agent): match the thread-list URL one way in panel tests The panel tests matched the thread-list request with both an isThreadListUrl helper and a route regex. They now share one module-level regex, for respondToFetch routes and for the hand-written fetch fakes. --- .../extensions/agent/AgentPanelRoot.test.ts | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 062921d437d..b0cbff584cb 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -500,9 +500,7 @@ function agentThread({ } } -function isThreadListUrl(url: string): boolean { - return url.split('?')[0].endsWith('/api/agent/threads') -} +const threadListRoute = /\/api\/agent\/threads\?/ function agentThreadList( threads: AgentThreadSummary[] = [], @@ -1925,7 +1923,7 @@ describe('AgentPanelRoot standing credits-exhausted paywall', () => { async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (isThreadListUrl(url)) return json(200, agentThreadList()) + if (threadListRoute.test(url)) return json(200, agentThreadList()) messageBodies.push(JSON.parse(String(init?.body))) return json(202, { thread_id: 'th-1', message_id: 'm-1' }) } @@ -4876,7 +4874,7 @@ describe('AgentPanelRoot canvas draft on send', () => { async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (isThreadListUrl(url)) return json(200, agentThreadList()) + if (threadListRoute.test(url)) return json(200, agentThreadList()) messageBodies.push(JSON.parse(String(init?.body))) return json(202, { thread_id: 'th-1', message_id: 'm-1' }) } @@ -4915,7 +4913,7 @@ describe('AgentPanelRoot canvas draft on send', () => { async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input) - if (isThreadListUrl(url)) return json(200, agentThreadList()) + if (threadListRoute.test(url)) return json(200, agentThreadList()) messageBodies.push(JSON.parse(String(init?.body))) return json(202, { thread_id: 'th-1', message_id: 'm-1' }) } @@ -4935,8 +4933,6 @@ describe('AgentPanelRoot canvas draft on send', () => { }) describe('AgentPanelRoot history', () => { - const threadListRoute = /\/api\/agent\/threads\?/ - beforeEach(() => { ws.clear() respondToFetch({}, () => json(200, [])) @@ -4956,7 +4952,7 @@ describe('AgentPanelRoot history', () => { async function renderWithActiveThread(): Promise { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - return isThreadListUrl(url) + return threadListRoute.test(url) ? new Response( JSON.stringify( agentThreadList([ @@ -5173,7 +5169,7 @@ describe('AgentPanelRoot history', () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (isThreadListUrl(url)) { + if (threadListRoute.test(url)) { return new Response( JSON.stringify( agentThreadList([ @@ -5218,7 +5214,7 @@ describe('AgentPanelRoot history', () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (isThreadListUrl(url)) + if (threadListRoute.test(url)) return json( 200, agentThreadList([ @@ -5593,7 +5589,7 @@ describe('AgentPanelRoot history', () => { it('marks the restored thread as the current session', async () => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - return isThreadListUrl(url) + return threadListRoute.test(url) ? new Response(JSON.stringify(agentThreadList()), { status: 200, headers: { 'Content-Type': 'application/json' } @@ -5623,7 +5619,7 @@ describe('AgentPanelRoot transcript copy', () => { async (loaded) => { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - return isThreadListUrl(url) + return threadListRoute.test(url) ? new Response( JSON.stringify( agentThreadList([ From 182a61b6e233c928fe088561370424984866fb7b Mon Sep 17 00:00:00 2001 From: Christian Byrne Date: Thu, 15 Oct 2026 23:13:21 +0800 Subject: [PATCH 29/66] fix(agent): follow active workflow chat (#18402) Squash of Comfy-Org/ComfyUI_frontend#18402 applied on top of #20827, kept as Christian's work: - 632b80b104 fix(agent): follow active workflow chat - e72d41cd70 fix(agent): react to resolved workflow IDs - bbc697dcc5 test(agent): cover delayed workflow ID resolution - 61865477da fix(agent): arm workflow-chat following on activation only - 3e14ec378a test(agent): pin tab-activation chat following in the harness - c7e0648c26 fix(agent): retire a pending workflow follow when a chat is started Conflict resolution: refreshHistory keeps the thread summaries only when the paginated list from #20827 is complete, in the same branch that replaces Chat history. --- .../agentTabActivationFollowsChat.spec.ts | 257 +++++++++++++++ .../extensions/agent/AgentPanelRoot.test.ts | 312 ++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 86 ++++- 3 files changed, 654 insertions(+), 1 deletion(-) create mode 100644 browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts diff --git a/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts b/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts new file mode 100644 index 00000000000..6e275f906f9 --- /dev/null +++ b/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts @@ -0,0 +1,257 @@ +import { expect } from '@playwright/test' + +import type { + AgentMessage, + AgentThreadListResponse, + WorkflowListResponse +} from '@comfyorg/ingest-types' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } +import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' + +import { + agentTest as test, + bootAgentApp +} from '@e2e/fixtures/agentPanelFixture' +import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { Topbar } from '@e2e/fixtures/components/Topbar' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' + +/** + * PM-1257 / PM-1270: activating a workflow tab has to bring up that workflow's + * chat, and a chat the user picked by hand has to survive the thread-list + * refresh that the pick itself triggers. + */ +const PORTRAIT_WORKFLOW_ID = 'f0e1d2c3-4b5a-4968-8776-5a4b3c2d1e0f' +const LANDSCAPE_WORKFLOW_ID = 'b2c3d4e5-6f70-4812-9a3b-4c5d6e7f8a9b' +const PORTRAIT_THREAD_ID = 'c4a7e2d1-5b3f-4e6a-9c8d-1f2a3b4c5d6e' +const LANDSCAPE_THREAD_ID = 'e1f2a3b4-6c5d-4e7f-8a9b-0c1d2e3f4a5b' +const UNBOUND_THREAD_ID = 'a1b2c3d4-7e8f-4901-8b2c-3d4e5f6a7b8c' +const PORTRAIT_NAME = 'Portrait Study' +const LANDSCAPE_NAME = 'Landscape Study' +const PORTRAIT_REQUEST = 'Tidy up the portrait study' +const LANDSCAPE_REQUEST = 'Widen the landscape study' +const UNBOUND_REQUEST = 'What does a KSampler do?' +const AT = '2026-09-22T10:00:00Z' + +const EMPTY_WORKFLOW: ComfyWorkflowJSON = { + last_node_id: 0, + last_link_id: 0, + nodes: [], + links: [], + groups: [], + config: {}, + extra: {}, + version: 0.4 +} + +const savedFiles: UserDataFullInfo[] = [PORTRAIT_NAME, LANDSCAPE_NAME].map( + (name) => ({ + path: `${name}.json`, + modified: Date.parse(AT), + size: JSON.stringify(EMPTY_WORKFLOW).length + }) +) + +function thread( + id: string, + title: string, + preview: string, + workflowId: string +): AgentThreadListResponse['threads'][number] { + return { + id, + title, + preview, + workflow_id: workflowId, + status: 'active', + message_count: 1, + created_at: AT, + updated_at: AT, + last_message_at: AT + } +} + +function transcript( + threadId: string, + workflowId: string, + text: string +): AgentMessage[] { + return [ + { + id: `${threadId}-user`, + thread_id: threadId, + turn_id: `${threadId}-turn`, + seq: 1, + role: 'user', + status: 'complete', + workflow_id: workflowId, + content: { text } + } + ] +} + +const TRANSCRIPTS: Record = { + [PORTRAIT_THREAD_ID]: transcript( + PORTRAIT_THREAD_ID, + PORTRAIT_WORKFLOW_ID, + PORTRAIT_REQUEST + ), + [LANDSCAPE_THREAD_ID]: transcript( + LANDSCAPE_THREAD_ID, + LANDSCAPE_WORKFLOW_ID, + LANDSCAPE_REQUEST + ), + [UNBOUND_THREAD_ID]: transcript(UNBOUND_THREAD_ID, '', UNBOUND_REQUEST) +} + +const cloudWorkflows: WorkflowListResponse = { + data: [ + { id: PORTRAIT_WORKFLOW_ID, name: PORTRAIT_NAME }, + { id: LANDSCAPE_WORKFLOW_ID, name: LANDSCAPE_NAME } + ].map(({ id, name }) => ({ + id, + name, + created_at: AT, + updated_at: AT, + created_by: 'test-user-e2e', + latest_version: 1 + })), + pagination: { offset: 0, limit: 100, total: 2, has_more: false } +} + +const threads: AgentThreadListResponse = { + threads: [ + thread( + PORTRAIT_THREAD_ID, + 'Portrait chat', + PORTRAIT_REQUEST, + PORTRAIT_WORKFLOW_ID + ), + thread( + LANDSCAPE_THREAD_ID, + 'Landscape chat', + LANDSCAPE_REQUEST, + LANDSCAPE_WORKFLOW_ID + ), + thread(UNBOUND_THREAD_ID, 'Unbound chat', UNBOUND_REQUEST, '') + ], + pagination: { offset: 0, limit: 100, total: 3, has_more: false } +} + +test.describe( + 'Agent chat follows the active workflow tab', + { tag: ['@cloud', '@agent'] }, + () => { + test('brings up the tab’s chat on activation and keeps a hand-picked chat', async ({ + page, + agentFlagEnabled + }) => { + // Every history pick refreshes the thread list, and that refresh is what + // used to re-assert the active tab's chat. Counting the refreshes gives + // the "it stayed" assertion something real to wait for. + let threadListReads = 0 + await page.routeWebSocket(/\/ws/, (ws) => { + ws.send( + JSON.stringify({ + type: 'status', + data: { status: { exec_info: { queue_remaining: 0 } } } + }) + ) + }) + + await bootAgentApp(page, agentFlagEnabled, { + beforeNavigate: async (page) => { + await page.route('**/api/agent/threads', (route) => { + threadListReads += 1 + return route.fulfill(jsonRoute(threads)) + }) + await page.route('**/api/agent/threads/*/messages', (route) => { + if (route.request().method() !== 'GET') return route.fallback() + const threadId = new URL(route.request().url()).pathname.split( + '/' + )[4] + return route.fulfill(jsonRoute(TRANSCRIPTS[threadId] ?? [])) + }) + await page.route('**/api/workflows?*', (route) => + route.fulfill(jsonRoute(cloudWorkflows)) + ) + await page.route('**/api/userdata?*', (route) => { + const dir = new URL(route.request().url()).searchParams.get('dir') + if (dir !== 'workflows') return route.fallback() + return route.fulfill(jsonRoute(savedFiles)) + }) + await page.route('**/api/userdata/*', (route) => { + const request = route.request() + const path = decodeURIComponent( + new URL(request.url()).pathname.split('/userdata/')[1] + ) + if ( + request.method() !== 'GET' || + !path.startsWith('workflows/') || + !savedFiles.some((file) => path === `workflows/${file.path}`) + ) + return route.fallback() + return route.fulfill(jsonRoute(EMPTY_WORKFLOW)) + }) + } + }) + + const topbar = new Topbar(page) + const agentPanel = new AgentPanel(page) + const panel = await agentPanel.open() + const transcriptBubbles = panel.getByTestId('user-message-bubble') + const historyButton = panel.getByRole('button', { + name: enMessages.agent.showChatHistory + }) + const chatRow = (title: string) => + panel.getByRole('button', { name: title, exact: true }) + + async function openChat(title: string, request: string): Promise { + await historyButton.click() + await expect(chatRow(title)).toBeEnabled() + await chatRow(title).click() + await expect(transcriptBubbles).toHaveText([request]) + } + + await test.step('each chat opens a tab for the workflow it is bound to', async () => { + await openChat('Portrait chat', PORTRAIT_REQUEST) + await expect(topbar.getWorkflowTab(PORTRAIT_NAME)).toBeVisible() + await openChat('Landscape chat', LANDSCAPE_REQUEST) + await expect( + topbar.getWorkflowTab(LANDSCAPE_NAME).and(topbar.getActiveTab()) + ).toBeVisible() + }) + + await test.step('activating the portrait tab brings up the portrait chat', async () => { + await topbar.getWorkflowTab(PORTRAIT_NAME).click() + await expect( + topbar.getWorkflowTab(PORTRAIT_NAME).and(topbar.getActiveTab()) + ).toBeVisible() + await expect(transcriptBubbles).toHaveText([PORTRAIT_REQUEST]) + }) + + await test.step('a hand-picked chat with no workflow of its own survives the refresh', async () => { + const readsBeforePick = threadListReads + await openChat('Unbound chat', UNBOUND_REQUEST) + await expect + .poll(() => threadListReads, { message: 'thread list refreshed' }) + .toBeGreaterThan(readsBeforePick) + // "It stayed" needs a window. The regression puts the tab's chat back + // shortly after that refresh lands, so asserting the unbound chat is + // on screen proves nothing on its own -- it holds just as well a + // moment before the flip. + await expect( + expect(transcriptBubbles).toHaveText([PORTRAIT_REQUEST], { + timeout: 3000 + }) + ).rejects.toThrow() + await expect(transcriptBubbles).toHaveText([UNBOUND_REQUEST]) + await expect( + topbar.getWorkflowTab(PORTRAIT_NAME).and(topbar.getActiveTab()) + ).toBeVisible() + }) + }) + } +) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index b0cbff584cb..149d59334aa 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5209,6 +5209,318 @@ describe('AgentPanelRoot history', () => { }) }) + it('switches to the chat bound to the active workflow tab', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + + const loadedThreads: string[] = [] + let resolveWorkflows!: (response: Response) => void + const workflowsResponse = new Promise((resolve) => { + resolveWorkflows = resolve + }) + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/api/agent/threads')) + return json( + 200, + agentThreadList([ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-second' + }) + ]) + ) + if (url.includes('/api/workflows')) return workflowsResponse + const match = url.match(/\/api\/agent\/threads\/([^/]+)\/messages$/) + if (match) { + loadedThreads.push(match[1]) + return json(200, []) + } + return json(200, { data: [], pagination: { has_more: false } }) + }) + + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(2) + ) + // A mount is not an activation. The panel remounts on every minimize and + // restore, and adopting the tab's older chat there would throw away the + // chat the user had open. + expect(useAgentConversationStore().threadId).toBeNull() + + // Activated while the cloud ids are still in flight, so the follow has + // nothing to match on yet. + workflowStore.activeWorkflow = second + await nextTick() + expect(useAgentConversationStore().threadId).toBeNull() + + resolveWorkflows( + json(200, { + data: [ + { id: 'wf-first', name: 'first' }, + { id: 'wf-second', name: 'second' } + ], + pagination: { offset: 0, limit: 100, total: 2, has_more: false } + }) + ) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + + workflowStore.activeWorkflow = first + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-first') + ) + expect(loadedThreads).toEqual(['th-second', 'th-first']) + }) + + describe('following the active workflow tab', () => { + /** + * Two tabs whose cloud ids are listed, and a thread list the caller + * chooses. Records every thread whose messages were fetched so a test can + * assert that a chat was *not* re-loaded. + */ + function stubWorkflowBoundHistory(threads: AgentThreadSummary[]): { + loadedThreads: string[] + listCalls: () => number + } { + const loadedThreads: string[] = [] + let listCalls = 0 + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/api/agent/threads')) { + listCalls += 1 + return json(200, agentThreadList(threads)) + } + if (url.includes('/api/workflows')) + return json(200, { + data: [ + { id: 'wf-first', name: 'first' }, + { id: 'wf-second', name: 'second' } + ], + pagination: { offset: 0, limit: 100, total: 2, has_more: false } + }) + const match = url.match(/\/api\/agent\/threads\/([^/]+)\/messages$/) + if (match) { + loadedThreads.push(match[1]) + return json(200, [ + { + id: `${match[1]}-user`, + thread_id: match[1], + seq: 1, + role: 'user', + status: 'complete', + turn_id: `${match[1]}-turn`, + content: { text: `Prompt in ${match[1]}` } + } + ] satisfies AgentMessages) + } + return json(200, { data: [], pagination: { has_more: false } }) + }) + return { loadedThreads, listCalls: () => listCalls } + } + + async function settle(): Promise { + for (let i = 0; i < 5; i++) await nextTick() + } + + /** + * How long an armed follow is given to land. Pinned by the positive + * control below, so the test that asserts a follow does *not* land is + * waiting a proven-sufficient window rather than an arbitrary one. + */ + const FOLLOW_LANDS_WITHIN_MS = 1000 + + function userPrompts(): string[] { + return useAgentConversationStore().entries.flatMap((entry) => + entry.role === 'user' ? [entry.text] : [] + ) + } + + it('keeps the current chat when the active tab has no matching thread', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }) + ]) + + renderWithSelectedTarget() + workflowStore.activeWorkflow = first + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-first') + ) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-first']) + ) + + workflowStore.activeWorkflow = second + await settle() + + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(userPrompts()).toEqual(['Prompt in th-first']) + expect(loadedThreads).toEqual(['th-first']) + }) + + it('does not pull a manually selected chat back to the active tab', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + const { loadedThreads, listCalls } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-other', + title: 'Other chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-second' + }) + ]) + + renderWithSelectedTarget() + workflowStore.activeWorkflow = first + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-first') + ) + const callsBeforeSelect = listCalls() + + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click(await screen.findByText('Other chat')) + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-other') + ) + // The selection's own refreshHistory is what used to re-assert the tab's + // thread, so the assertion has to wait for that refresh to land. + await vi.waitFor(() => + expect(listCalls()).toBeGreaterThan(callsBeforeSelect) + ) + await settle() + + expect(useAgentConversationStore().threadId).toBe('th-other') + expect(loadedThreads).toEqual(['th-first', 'th-other']) + }) + + /** + * Arms a follow that cannot be satisfied yet: the active tab is switched + * to a workflow whose chat exists, while the cloud id listing that would + * identify it is still in flight. Returns the resolver for that listing + * and the threads whose transcripts were fetched. + */ + async function armFollowOnPendingWorkflowIds(): Promise<{ + resolveWorkflows: () => void + loadedThreads: string[] + }> { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + + const loadedThreads: string[] = [] + let settleWorkflows!: (response: Response) => void + const workflowsResponse = new Promise((resolve) => { + settleWorkflows = resolve + }) + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/api/agent/threads')) + return json( + 200, + agentThreadList([ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }) + ]) + ) + if (url.includes('/api/workflows')) return workflowsResponse + const match = url.match(/\/api\/agent\/threads\/([^/]+)\/messages$/) + if (match) { + loadedThreads.push(match[1]) + return json(200, []) + } + return json(200, { data: [], pagination: { has_more: false } }) + }) + + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + workflowStore.activeWorkflow = first + await nextTick() + expect(useAgentConversationStore().threadId).toBeNull() + + return { + loadedThreads, + resolveWorkflows: () => + settleWorkflows( + json(200, { + data: [{ id: 'wf-first', name: 'first' }], + pagination: { offset: 0, limit: 100, total: 1, has_more: false } + }) + ) + } + } + + // The positive control for the test below: it fixes how long an armed + // follow takes to land once the ids arrive, so the negative case's window + // is not a guess. + it('lands the tab chat once the tab cloud ids resolve', async () => { + const { resolveWorkflows, loadedThreads } = + await armFollowOnPendingWorkflowIds() + + resolveWorkflows() + + await vi.waitFor( + () => expect(useAgentConversationStore().threadId).toBe('th-first'), + { timeout: FOLLOW_LANDS_WITHIN_MS } + ) + expect(loadedThreads).toEqual(['th-first']) + }) + + it('does not land the tab chat on a chat the user just started', async () => { + const { resolveWorkflows, loadedThreads } = + await armFollowOnPendingWorkflowIds() + + await userEvent.click( + screen.getByRole('button', { name: i18n.global.t('agent.newChat') }) + ) + resolveWorkflows() + + await expect( + vi.waitFor( + () => expect(useAgentConversationStore().threadId).not.toBeNull(), + { timeout: FOLLOW_LANDS_WITHIN_MS } + ) + ).rejects.toThrow() + expect(loadedThreads).toEqual([]) + }) + }) + describe('history row title for the active chat', () => { function stubActiveThread(serverTitle: string): void { vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 60422f88aa9..7968d650e4d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1418,6 +1418,9 @@ let historyRefreshGeneration = 0 let appliedHistoryRefreshGeneration = 0 const historyRefreshAbort = new AbortController() +// Raw server summaries, kept so an activated workflow tab can resolve its chat. +const threadSummaries = ref([]) + async function refreshHistory(): Promise { const { signal } = historyRefreshAbort if (signal.aborted) return @@ -1426,6 +1429,7 @@ async function refreshHistory(): Promise { const threads = await listThreads({ signal }) if (signal.aborted || generation < appliedHistoryRefreshGeneration) return appliedHistoryRefreshGeneration = generation + threadSummaries.value = threads history.replaceAll(threads.map(toChatSession)) } catch (error) { if (signal.aborted || generation !== historyRefreshGeneration) return @@ -1476,7 +1480,21 @@ const historyGroups = computed(() => { ) }) -async function onSelectHistory( +/** + * Whether the panel still owes the active tab its chat. Only an activation + * arms it: a mount does not, because the panel is remounted every time it is + * minimized and restored, and adopting the tab's older chat there would + * discard the chat the user had open. A temporary tab does not arm it either + * -- it has no cloud chat to follow, and the id it gets later comes from this + * panel saving it, which binds the open chat rather than navigating away. + * + * It outlives the activation because both the summary list and the tab's cloud + * id can resolve afterwards, and it is retired the moment the follow is + * satisfied or the user picks a chat themselves. + */ +const followOwed = ref(false) + +async function selectThread( id: string, isCurrent: () => boolean ): Promise { @@ -1494,6 +1512,68 @@ async function onSelectHistory( return opened } +/** + * A chat the user picked outranks the one the active tab points at, so it + * retires the pending follow. Without that, this call's own `refreshHistory()` + * handed the follow a fresh summary list and the tab's thread was selected + * back on top of the user's choice. + */ +async function onSelectHistory( + id: string, + isCurrent: () => boolean +): Promise { + followOwed.value = false + return selectThread(id, isCurrent) +} + +const activeWorkflowId = computed(() => { + const workflow = workflowStore.activeWorkflow + return workflow ? cloudIdFor(workflow) : undefined +}) + +function followActiveWorkflowChat(): void { + if (!followOwed.value) return + // Pointing the composer at a workflow binds the chat the user is in to that + // workflow. It is not navigation to that workflow's other chats, so a cloud + // id that first appears while the selection is running must not replace the + // open chat. + if (workflowSelecting.value) { + followOwed.value = false + return + } + const workflowId = activeWorkflowId.value + if (workflowId === undefined) return + const matchingThread = threadSummaries.value.find( + (thread) => thread.workflow_id === workflowId + ) + if (matchingThread === undefined) return + followOwed.value = false + if (matchingThread.id === threadId.value) return + // Following the active tab carries no navigation intent to invalidate; + // loadThread's own generation guard already drops a superseded load. + void selectThread(matchingThread.id, () => true) +} + +watch( + () => workflowStore.activeWorkflow, + (workflow) => { + followOwed.value = workflow !== null && !workflow.isTemporary + followActiveWorkflowChat() + } +) + +// Late arrivals only: the active tab's cloud id and the summary list can both +// resolve after the activation that armed the follow. A refresh with nothing +// owed is inert, which is what stops `selectThread`'s own refresh from +// re-asserting the tab's chat over a chat the user picked. +watch([activeWorkflowId, threadSummaries], () => followActiveWorkflowChat()) + +// A selection started after the activation retires the follow for the same +// reason: the user is binding the chat they are in, not asking for another. +watch(workflowSelecting, (selecting) => { + if (selecting) followOwed.value = false +}) + function buildTranscriptMarkdown(entries: ConversationEntry[]): string { return entries .map((entry) => { @@ -1650,6 +1730,10 @@ function onDeleteHistory(id: string): void { } function onNewChat(source?: 'new_chat_button' | 'history_delete'): void { + // Starting a chat retires the follow for the same reason a history pick + // does: a follow still waiting on a cloud id or a summary list would land + // the tab's older thread on top of the chat the user just opened. + followOwed.value = false composerStore.invalidateSubmission() cancelWorkflowSelection() canvasStore.stopNodePicking() From 9811c7c86d931963ddf8e9dec2b1150dde3e633a Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:24:07 +0800 Subject: [PATCH 30/66] test(agent): match the paged thread list in the tab-follow tests The thread list request now carries a page query, so the #18402 tests' exact path match never answered it and the follow had no summaries. --- src/workbench/extensions/agent/AgentPanelRoot.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 149d59334aa..49be8241f1c 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5221,7 +5221,7 @@ describe('AgentPanelRoot history', () => { }) vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) + if (threadListRoute.test(url)) return json( 200, agentThreadList([ @@ -5299,7 +5299,7 @@ describe('AgentPanelRoot history', () => { let listCalls = 0 vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) { + if (threadListRoute.test(url)) { listCalls += 1 return json(200, agentThreadList(threads)) } @@ -5445,7 +5445,7 @@ describe('AgentPanelRoot history', () => { }) vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { const url = String(input) - if (url.endsWith('/api/agent/threads')) + if (threadListRoute.test(url)) return json( 200, agentThreadList([ From 11164eaf085c95a010324ff9e2041b1395dafa3d Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:46:10 +0800 Subject: [PATCH 31/66] fix(agent): don't follow a tab the panel opens itself Picking a chat in Chat history opens that chat's tab, and that tab change armed the tab follow, which then replaced the picked chat with the tab's other chat. Show target, agent tab activation, approval "Open workflow", reference chips and tab link cards had the same problem. Tab changes the panel makes now go through navigateFromPanel, and the follow is armed only for a tab the panel isn't opening. A tab the user activates while the panel opens a different one still arms it. --- .../extensions/agent/AgentPanelRoot.test.ts | 115 +++++++++++++++++- .../extensions/agent/AgentPanelRoot.vue | 49 ++++++-- .../components/agent/message/TabLinkCard.vue | 12 +- .../agent/useAgentWorkflowSelection.ts | 5 +- .../stores/agent/agentPanelStore.test.ts | 38 ++++++ .../agent/stores/agent/agentPanelStore.ts | 28 +++++ 6 files changed, 225 insertions(+), 22 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 49be8241f1c..4c841b211e9 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5287,11 +5287,20 @@ describe('AgentPanelRoot history', () => { describe('following the active workflow tab', () => { /** - * Two tabs whose cloud ids are listed, and a thread list the caller + * Three tabs whose cloud ids are listed, and a thread list the caller * chooses. Records every thread whose messages were fetched so a test can - * assert that a chat was *not* re-loaded. + * assert that a chat was *not* re-loaded. A transcript can name the + * workflow of its user row, or be answered by the caller. */ - function stubWorkflowBoundHistory(threads: AgentThreadSummary[]): { + function stubWorkflowBoundHistory( + threads: AgentThreadSummary[], + transcripts: Partial< + Record< + string, + { workflowId?: string; response?: () => Promise } + > + > = {} + ): { loadedThreads: string[] listCalls: () => number } { @@ -5307,13 +5316,16 @@ describe('AgentPanelRoot history', () => { return json(200, { data: [ { id: 'wf-first', name: 'first' }, - { id: 'wf-second', name: 'second' } + { id: 'wf-second', name: 'second' }, + { id: 'wf-third', name: 'third' } ], - pagination: { offset: 0, limit: 100, total: 2, has_more: false } + pagination: { offset: 0, limit: 100, total: 3, has_more: false } }) const match = url.match(/\/api\/agent\/threads\/([^/]+)\/messages$/) if (match) { loadedThreads.push(match[1]) + const transcript = transcripts[match[1]] + if (transcript?.response) return transcript.response() return json(200, [ { id: `${match[1]}-user`, @@ -5322,6 +5334,7 @@ describe('AgentPanelRoot history', () => { role: 'user', status: 'complete', turn_id: `${match[1]}-turn`, + workflow_id: transcript?.workflowId, content: { text: `Prompt in ${match[1]}` } } ] satisfies AgentMessages) @@ -5519,6 +5532,98 @@ describe('AgentPanelRoot history', () => { ).rejects.toThrow() expect(loadedThreads).toEqual([]) }) + + it('keeps a chat picked in Chat history when restoring it opens its tab', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-newest', + title: 'Newest chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }), + agentThread({ + id: 'th-picked', + title: 'Picked chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-second' + }) + ], + { 'th-picked': { workflowId: 'wf-second' } } + ) + + renderWithSelectedTarget() + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click(await screen.findByText('Picked chat')) + await vi.waitFor(() => + expect(workflowStore.activeWorkflow?.path).toBe(second.path) + ) + + await expect( + vi.waitFor(() => expect(loadedThreads).toContain('th-newest'), { + timeout: FOLLOW_LANDS_WITHIN_MS + }) + ).rejects.toThrow() + expect(useAgentConversationStore().threadId).toBe('th-picked') + expect(loadedThreads).toEqual(['th-picked']) + }) + + it('keeps the open chat when Show target opens its tab', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-newest', + title: 'Newest chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-open', + title: 'Open chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-first' + }) + ], + { 'th-open': { workflowId: 'wf-first' } } + ) + renderWithSelectedTarget() + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click(await screen.findByText('Open chat')) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-open']) + ) + workflowStore.activeWorkflow = second + + await userEvent.click( + await screen.findByRole('button', { + name: 'Show target workflow: first' + }) + ) + await vi.waitFor(() => + expect(workflowStore.activeWorkflow?.path).toBe(first.path) + ) + + await expect( + vi.waitFor(() => expect(loadedThreads).toContain('th-newest'), { + timeout: FOLLOW_LANDS_WITHIN_MS + }) + ).rejects.toThrow() + expect(useAgentConversationStore().threadId).toBe('th-open') + }) }) describe('history row title for the active chat', () => { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 7968d650e4d..c91e99a1c8c 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1128,7 +1128,7 @@ async function onNavigateToReferenceWorkflow( ]) target = storedWorkflowFor(workflowId) } - if (target === null || !(await workflowService.openWorkflow(target))) { + if (target === null || !(await openFromPanel(target))) { warnWorkflowUnavailable() return } @@ -1138,6 +1138,21 @@ async function onNavigateToReferenceWorkflow( } } +function openFromPanel( + workflow: ComfyWorkflow, + ...options: [{ isCurrent: () => boolean }?] +): Promise { + return agentPanelStore.navigateFromPanel(workflow, () => + workflowService.openWorkflow(workflow, ...options) + ) +} + +function closeFromPanel(workflow: ComfyWorkflow): Promise { + return agentPanelStore.navigateFromPanel(null, () => + workflowService.closeWorkflow(workflow, { warnIfUnsaved: false }) + ) +} + async function onShowTarget( isNavigationCurrent: () => boolean = () => true, warnOpenFailed: () => void = warnWorkflowUnavailable @@ -1147,7 +1162,7 @@ async function onShowTarget( const isCurrent = () => isNavigationCurrent() && selectedTarget.value === target try { - const opened = await workflowService.openWorkflow(target, { isCurrent }) + const opened = await openFromPanel(target, { isCurrent }) if (!isCurrent()) return false if (!opened) warnOpenFailed() return opened @@ -1208,7 +1223,7 @@ async function activateExistingAgentTab( previousWorkflowId: string | null, stale: () => boolean ): Promise { - const opened = await workflowService.openWorkflow(bound) + const opened = await openFromPanel(bound) if (stale()) return false if (!opened) { warnWorkflowUnavailable() @@ -1247,11 +1262,11 @@ async function createAndActivateAgentTab( try { opened = await workflowService.openWorkflow(tab) } catch (error) { - await workflowService.closeWorkflow(tab, { warnIfUnsaved: false }) + await closeFromPanel(tab) throw error } if (stale() || !opened) { - await workflowService.closeWorkflow(tab, { warnIfUnsaved: false }) + await closeFromPanel(tab) if (!stale()) { warnWorkflowUnavailable() trackWorkflowOpenFailure('toast') @@ -1554,19 +1569,27 @@ function followActiveWorkflowChat(): void { void selectThread(matchingThread.id, () => true) } +// Synchronous, so a tab the panel is opening itself is still recognised as +// such when it becomes active. watch( () => workflowStore.activeWorkflow, (workflow) => { - followOwed.value = workflow !== null && !workflow.isTemporary - followActiveWorkflowChat() - } + followOwed.value = + workflow !== null && + !workflow.isTemporary && + !agentPanelStore.isPanelNavigation(workflow) + }, + { flush: 'sync' } ) -// Late arrivals only: the active tab's cloud id and the summary list can both -// resolve after the activation that armed the follow. A refresh with nothing -// owed is inert, which is what stops `selectThread`'s own refresh from -// re-asserting the tab's chat over a chat the user picked. -watch([activeWorkflowId, threadSummaries], () => followActiveWorkflowChat()) +// The active tab's cloud id and the summary list can both resolve after the +// activation that armed the follow. A refresh with nothing owed is inert, +// which is what stops `selectThread`'s own refresh from re-asserting the tab's +// chat over a chat the user picked. +watch( + [() => workflowStore.activeWorkflow, activeWorkflowId, threadSummaries], + () => followActiveWorkflowChat() +) // A selection started after the activation retires the follow for the same // reason: the user is binding the chat they are in, not asking for another. diff --git a/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue b/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue index f3b7d060ab8..8bb668d9e32 100644 --- a/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue +++ b/src/workbench/extensions/agent/components/agent/message/TabLinkCard.vue @@ -27,7 +27,8 @@ const workflowStore = useWorkflowStore() const workflowService = useWorkflowService() const bindingStore = useAgentWorkflowTabBindingStore() const toast = useToast() -const { enabled: agentEnabled } = storeToRefs(useAgentPanelStore()) +const panelStore = useAgentPanelStore() +const { enabled: agentEnabled } = storeToRefs(panelStore) const targetNavigation = useAgentTargetNavigation() const tab = computed(() => { @@ -63,10 +64,15 @@ useEventListener( async function open(): Promise { const target = tab.value if (!target) return - if (locatorId === undefined) await workflowService.openWorkflow(target) + if (locatorId === undefined) + await panelStore.navigateFromPanel(target, () => + workflowService.openWorkflow(target) + ) else { try { - await targetNavigation.navigate({ workflowId, locatorId }) + await panelStore.navigateFromPanel(target, () => + targetNavigation.navigate({ workflowId, locatorId }) + ) } catch (error) { if (!(error instanceof AgentTargetNavigationError)) reportError(error, { diff --git a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts index ea356acb7b6..ef8fccdc843 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowSelection.ts @@ -298,7 +298,10 @@ export function useAgentWorkflowSelection({ warnRestoreFailed() return false } - const opened = await workflowService.openWorkflow(target, { isCurrent }) + const restored = target + const opened = await panelStore.navigateFromPanel(restored, () => + workflowService.openWorkflow(restored, { isCurrent }) + ) if (!isCurrent()) return false if (!opened) { panelStore.setWorkflowTarget(null) diff --git a/src/workbench/extensions/agent/stores/agent/agentPanelStore.test.ts b/src/workbench/extensions/agent/stores/agent/agentPanelStore.test.ts index d7e71bcde9c..c84a8332cc8 100644 --- a/src/workbench/extensions/agent/stores/agent/agentPanelStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentPanelStore.test.ts @@ -1,7 +1,9 @@ +import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, describe, expect, it, vi } from 'vitest' import { nextTick } from 'vue' import { useTelemetry } from '@/platform/telemetry' +import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { api } from '@/scripts/api' vi.mock(import('@/platform/telemetry')) @@ -603,3 +605,39 @@ describe('agentPanelStore width', () => { expect(getAgentPanelOpen()).toBe(false) }) }) + +describe('agentPanelStore panel navigation', () => { + const destination = fromPartial({ path: 'workflows/a.json' }) + const other = fromPartial({ path: 'workflows/b.json' }) + + it('claims only its destination while the panel opens a tab', async () => { + const store = useAgentPanelStore() + let finish!: () => void + const opening = store.navigateFromPanel( + destination, + () => new Promise((resolve) => (finish = resolve)) + ) + + expect(store.isPanelNavigation(destination)).toBe(true) + expect(store.isPanelNavigation(other)).toBe(false) + + finish() + await opening + expect(store.isPanelNavigation(destination)).toBe(false) + }) + + it('claims every tab while the panel closes one, until the close fails', async () => { + const store = useAgentPanelStore() + let fail!: (error: Error) => void + const closing = store.navigateFromPanel( + null, + () => new Promise((_resolve, reject) => (fail = reject)) + ) + + expect(store.isPanelNavigation(other)).toBe(true) + + fail(new Error('close failed')) + await expect(closing).rejects.toThrow('close failed') + expect(store.isPanelNavigation(other)).toBe(false) + }) +}) diff --git a/src/workbench/extensions/agent/stores/agent/agentPanelStore.ts b/src/workbench/extensions/agent/stores/agent/agentPanelStore.ts index 7dd274b8728..725412d227d 100644 --- a/src/workbench/extensions/agent/stores/agent/agentPanelStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentPanelStore.ts @@ -114,6 +114,32 @@ export const useAgentPanelStore = defineStore('agentPanel', () => { targetTracking.value = { mode: 'restoring' } } + const panelDestinations: (ComfyWorkflow | null)[] = [] + + /** + * Runs a tab change the panel makes itself. `null` stands for whichever tab + * a close activates. + */ + async function navigateFromPanel( + destination: ComfyWorkflow | null, + navigate: () => Promise + ): Promise { + const entry = destination && toRaw(destination) + panelDestinations.push(entry) + try { + return await navigate() + } finally { + panelDestinations.splice(panelDestinations.indexOf(entry), 1) + } + } + + /** Whether `workflow` is being activated by the panel rather than the user. */ + function isPanelNavigation(workflow: ComfyWorkflow): boolean { + return panelDestinations.some( + (destination) => destination === null || destination === toRaw(workflow) + ) + } + function interruptHistorySelection(): void { if ( view.value.screen === 'history' && @@ -405,6 +431,8 @@ export const useAgentPanelStore = defineStore('agentPanel', () => { markWorkflowTargetUnavailable, canRestoreWorkflow, beginWorkflowRestoration, + navigateFromPanel, + isPanelNavigation, setWorkflowTarget, toggle, close, From 1b092b71d2ca06c9b823bb83825e9e6ec57b2057 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:49:18 +0800 Subject: [PATCH 32/66] fix(agent): keep the user on the tab a followed chat opened for A chat's listed workflow (the server's thread pointer) can differ from the workflow of its latest user message. Following tab B to such a chat restored the chat's older workflow, so the user was moved back to tab A. A chat opened by the tab follow now restores the tab it was opened for. Chat history picks still restore the transcript's latest workflow. --- .../extensions/agent/AgentPanelRoot.test.ts | 28 +++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 25 +++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 4c841b211e9..b5a4f510e94 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5624,6 +5624,34 @@ describe('AgentPanelRoot history', () => { ).rejects.toThrow() expect(useAgentConversationStore().threadId).toBe('th-open') }) + + it('keeps the user on the activated tab when the followed chat last ran on another', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ], + { 'th-second': { workflowId: 'wf-first' } } + ) + + renderWithSelectedTarget() + workflowStore.activeWorkflow = second + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-second']) + ) + await settle() + + expect(workflowStore.activeWorkflow.path).toBe(second.path) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(useAgentConversationStore().threadId).toBe('th-second') + }) }) describe('history row title for the active chat', () => { diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index c91e99a1c8c..b213936cf92 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -849,7 +849,7 @@ const { initialize: agentPanelStore.initializeTargetTracking, current: targetWorkflowTurnContext, adopted: onWorkflowAdopted, - restored: onWorkflowRestored, + restored: restoreChatWorkflow, prepare: async () => { try { await refreshCloudWorkflowIds() @@ -1508,6 +1508,7 @@ const historyGroups = computed(() => { * satisfied or the user picks a chat themselves. */ const followOwed = ref(false) +let followedChat: { threadId: string; workflowId: string } | null = null async function selectThread( id: string, @@ -1538,6 +1539,7 @@ async function onSelectHistory( isCurrent: () => boolean ): Promise { followOwed.value = false + followedChat = null return selectThread(id, isCurrent) } @@ -1564,9 +1566,28 @@ function followActiveWorkflowChat(): void { if (matchingThread === undefined) return followOwed.value = false if (matchingThread.id === threadId.value) return + void openFollowedChat(matchingThread.id, workflowId) +} + +// The chat was opened for the tab the user is on, so that tab is its +// workflow, even when its transcript last ran on another one. +function restoreChatWorkflow( + workflowId: string | undefined, + isCurrent: () => boolean +): Promise { + const followed = + followedChat?.threadId === conversationStore.threadId + ? followedChat.workflowId + : undefined + return onWorkflowRestored(followed ?? workflowId, isCurrent) +} + +async function openFollowedChat(id: string, workflowId: string): Promise { + followedChat = { threadId: id, workflowId } // Following the active tab carries no navigation intent to invalidate; // loadThread's own generation guard already drops a superseded load. - void selectThread(matchingThread.id, () => true) + await selectThread(id, () => true) + if (followedChat?.threadId === id) followedChat = null } // Synchronous, so a tab the panel is opening itself is still recognised as From 96a53bea502dd79ffd8a3fbed32423ddc58d36a3 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Thu, 15 Oct 2026 23:54:50 +0800 Subject: [PATCH 33/66] fix(agent): follow the tab's newest chat only when nothing is drafted - The follow opens the active tab's newest chat by last message, then last update, then creation time, as Chat history orders it, and skips chats deleted locally. It used to take the first chat in server order. - A draft (text that isn't only whitespace, an attachment or a node reference) holds the follow back: chat, draft and target stay, and the existing mismatch notice shows. Clearing or sending the draft later does not switch. - A whitespace-only draft is not a draft. The follow switches and clears it, so it is not carried into the other chat. - A chat that was never sent keeps moving its target to the visible tab instead of switching chats (PM-1256). --- .../extensions/agent/AgentPanelRoot.test.ts | 152 ++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 34 +++- .../stores/agent/agentComposerStore.test.ts | 36 +++++ .../agent/stores/agent/agentComposerStore.ts | 8 + 4 files changed, 222 insertions(+), 8 deletions(-) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index b5a4f510e94..66d04570493 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5533,6 +5533,158 @@ describe('AgentPanelRoot history', () => { expect(loadedThreads).toEqual([]) }) + it("opens the newest of the tab's chats that is not deleted", async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-older', + title: 'Older chat', + last_message_at: '2026-09-22T08:00:00Z', + workflow_id: 'wf-second' + }), + agentThread({ + id: 'th-newer', + title: 'Newer chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }), + agentThread({ + id: 'th-deleted', + title: 'Deleted chat', + last_message_at: '2026-09-22T11:00:00Z', + workflow_id: 'wf-second' + }) + ]) + useAgentChatHistoryStore().remove('th-deleted') + + renderWithSelectedTarget() + workflowStore.activeWorkflow = second + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-newer') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(loadedThreads).toEqual(['th-newer']) + }) + + it('keeps the chat, draft and target when the composer has a draft', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + const composer = useAgentComposerStore() + composer.setText('make it blue') + + workflowStore.activeWorkflow = second + + await expect( + vi.waitFor(() => expect(loadedThreads).toContain('th-second'), { + timeout: FOLLOW_LANDS_WITHIN_MS + }) + ).rejects.toThrow() + expect(composer.draft).toBe('make it blue') + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + expect(screen.getByRole('note')).toHaveTextContent( + i18n.global.t('agent.viewingDifferentWorkflow') + ) + + // Clearing the draft later does not switch either. + composer.setText('') + await settle() + expect(loadedThreads).toEqual([]) + }) + + it('switches past a whitespace-only draft and clears it', async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + stubWorkflowBoundHistory([ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + renderWithSelectedTarget() + const composer = useAgentComposerStore() + composer.setText(' \n ') + + workflowStore.activeWorkflow = second + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(composer.draft).toBe('') + }) + + it('moves the target of a chat that was never sent instead of switching', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + + workflowStore.activeWorkflow = second + + await expect( + vi.waitFor(() => expect(loadedThreads).toContain('th-second'), { + timeout: FOLLOW_LANDS_WITHIN_MS + }) + ).rejects.toThrow() + expect(useAgentConversationStore().threadId).toBeNull() + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + }) + + it('does not follow a temporary tab, including one the agent created', async () => { + const first = addTab('workflows/first.json') + const scratch = addTab('workflows/second.json', { isTemporary: true }) + workflowStore.activeWorkflow = first + useAgentWorkflowTabBindingStore().bind('wf-second', scratch.path) + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + + workflowStore.activeWorkflow = scratch + + await expect( + vi.waitFor(() => expect(loadedThreads).toContain('th-second'), { + timeout: FOLLOW_LANDS_WITHIN_MS + }) + ).rejects.toThrow() + expect(useAgentConversationStore().threadId).toBeNull() + }) + it('keeps a chat picked in Chat history when restoring it opens its tab', async () => { const first = addTab('workflows/first.json') const second = addTab('workflows/second.json') diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index b213936cf92..8b7afb6c658 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -3,6 +3,7 @@ import './agentPanel.css' import type { GetFeaturesResponse } from '@comfyorg/ingest-types' import { useClipboard } from '@vueuse/core' +import { maxBy } from 'es-toolkit' import { storeToRefs } from 'pinia' import { computed, @@ -1548,25 +1549,40 @@ const activeWorkflowId = computed(() => { return workflow ? cloudIdFor(workflow) : undefined }) +function latestChatFor(workflowId: string): string | undefined { + const onWorkflow = new Set( + threadSummaries.value.flatMap((thread) => + thread.workflow_id === workflowId ? [thread.id] : [] + ) + ) + return maxBy( + history.sessions.filter(({ id }) => onWorkflow.has(id)), + ({ updatedAt }) => updatedAt + )?.id +} + function followActiveWorkflowChat(): void { if (!followOwed.value) return // Pointing the composer at a workflow binds the chat the user is in to that // workflow. It is not navigation to that workflow's other chats, so a cloud // id that first appears while the selection is running must not replace the - // open chat. - if (workflowSelecting.value) { + // open chat. A draft is written for the open chat, and a chat that was + // never sent moves its target to the visible tab instead. + if ( + workflowSelecting.value || + composerStore.hasDraft || + agentPanelStore.followsVisibleWorkflow + ) { followOwed.value = false return } const workflowId = activeWorkflowId.value if (workflowId === undefined) return - const matchingThread = threadSummaries.value.find( - (thread) => thread.workflow_id === workflowId - ) - if (matchingThread === undefined) return + const latest = latestChatFor(workflowId) + if (latest === undefined) return followOwed.value = false - if (matchingThread.id === threadId.value) return - void openFollowedChat(matchingThread.id, workflowId) + if (latest === threadId.value) return + void openFollowedChat(latest, workflowId) } // The chat was opened for the tab the user is on, so that tab is its @@ -1584,6 +1600,8 @@ function restoreChatWorkflow( async function openFollowedChat(id: string, workflowId: string): Promise { followedChat = { threadId: id, workflowId } + if (composerStore.prompt.references.length === 0 && !composerStore.hasDraft) + composerStore.setText('') // Following the active tab carries no navigation intent to invalidate; // loadThread's own generation guard already drops a superseded load. await selectThread(id, () => true) diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts index b4dc8d8e8bf..97be962fcee 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.test.ts @@ -317,6 +317,42 @@ describe('composer draft reset (PM-1331)', () => { }) }) +describe('composer draft presence', () => { + type ComposerStore = ReturnType + + it.for([ + { draft: 'empty', fill: () => {}, expected: false }, + { + draft: 'whitespace only', + fill: (store: ComposerStore) => store.setText(' \n '), + expected: false + }, + { + draft: 'text', + fill: (store: ComposerStore) => store.setText('make it blue'), + expected: true + }, + { + draft: 'an attachment', + fill: (store: ComposerStore) => + store.addAttachment({ id: 'a-1', name: 'cat.png', ref: 'cat.png' }), + expected: true + }, + { + draft: 'a node reference', + fill: (store: ComposerStore) => { + store.setNodeScope('workflow-A') + store.setNodes([{ id: '1', title: 'KSampler' }]) + }, + expected: true + } + ])('reports $draft as a draft: $expected', ({ fill, expected }) => { + const store = useAgentComposerStore() + fill(store) + expect(store.hasDraft).toBe(expected) + }) +}) + describe('composer prompt origin (PM-1474 F11)', () => { it('starts out typed and stays typed while the user writes', () => { const store = useAgentComposerStore() diff --git a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts index f1f1b603b4a..81c8a0ed0b8 100644 --- a/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentComposerStore.ts @@ -72,6 +72,13 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { item.kind === 'node' ? [item.node] : [] ) ) + /** Text that isn't only whitespace, an attachment, or a node reference. */ + const hasDraft = computed( + () => + draft.value.trim() !== '' || + attachments.value.length > 0 || + nodes.value.length > 0 + ) const nodeScope = ref(null) let skillScope: string | null = null const promptEpoch = ref(0) @@ -552,6 +559,7 @@ export const useAgentComposerStore = defineStore('agentComposer', () => { workflowReferences, prompt, nodes, + hasDraft, nodeScope, promptEpoch, promptOrigin, From 6899a8a44c319a17fdba0ea4dba71b0d2feeb423 Mon Sep 17 00:00:00 2001 From: ryan-di Date: Fri, 16 Oct 2026 00:02:07 +0800 Subject: [PATCH 34/66] fix(agent): keep the open chat when a followed chat fails to open The follow replaced the open chat before the other chat's messages loaded, so a failed load left an empty chat the user never asked for. Now a failed follow reopens the chat the user had, with its target, and the panel shows "Couldn't open the chat for {workflow}." with Retry above the composer. The notice goes away when the user changes tabs, picks or starts a chat, or retries. A follow superseded by a newer activation or a chat pick is dropped without that rollback. --- src/locales/en/main.json | 1 + .../extensions/agent/AgentPanelRoot.test.ts | 119 ++++++++++++++++++ .../extensions/agent/AgentPanelRoot.vue | 84 +++++++++++-- 3 files changed, 197 insertions(+), 7 deletions(-) diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 70e260988cf..694d8837f63 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -5663,6 +5663,7 @@ "showTarget": "Show target", "targetWorkflowUnavailable": "The target workflow is no longer available.", "targetWorkflowOpenFailed": "Couldn’t open the target workflow.", + "followedChatOpenFailed": "Couldn’t open the chat for {workflowName}.", "showTargetWorkflow": "Show target workflow: {workflowName}", "runApproval": { "lead": "This tool wants to run the workflow:", diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index 66d04570493..7dcf18db1ca 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5685,6 +5685,125 @@ describe('AgentPanelRoot history', () => { expect(useAgentConversationStore().threadId).toBeNull() }) + it('lands the chat of the last activated tab when activations overlap', async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const third = addTab('workflows/third.json') + let answerSecond!: () => void + const { loadedThreads, listCalls } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-second' + }), + agentThread({ + id: 'th-third', + title: 'Third chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-third' + }) + ], + { + 'th-second': { + response: () => + new Promise((resolve) => { + answerSecond = () => resolve(json(200, [])) + }) + } + } + ) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(2) + ) + + workflowStore.activeWorkflow = second + await vi.waitFor(() => expect(loadedThreads).toEqual(['th-second'])) + workflowStore.activeWorkflow = third + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-third']) + ) + const listsBeforeLateAnswer = listCalls() + answerSecond() + // The superseded open refreshes the list once it has given up. + await vi.waitFor(() => + expect(listCalls()).toBeGreaterThan(listsBeforeLateAnswer) + ) + await settle() + + expect(useAgentConversationStore().threadId).toBe('th-third') + expect(userPrompts()).toEqual(['Prompt in th-third']) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(third.path) + expect(loadedThreads).toEqual(['th-second', 'th-third']) + }) + + it('keeps the open chat when the followed chat fails to open, and retries', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + let secondAttempts = 0 + stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ], + { + 'th-first': { workflowId: 'wf-first' }, + 'th-second': { + response: async () => + ++secondAttempts === 1 + ? json(500, { error: 'unavailable' }) + : json(200, []) + } + } + ) + renderWithSelectedTarget() + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click(await screen.findByText('First chat')) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-first']) + ) + + workflowStore.activeWorkflow = second + + const failure = i18n.global.t('agent.followedChatOpenFailed', { + workflowName: 'second' + }) + expect(await screen.findByRole('status')).toHaveTextContent(failure) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-first']) + ) + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + expect(workflowStore.activeWorkflow.path).toBe(second.path) + + await userEvent.click( + screen.getByRole('button', { name: i18n.global.t('g.retry') }) + ) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(screen.queryByText(failure)).toBeNull() + }) + it('keeps a chat picked in Chat history when restoring it opens its tab', async () => { const first = addTab('workflows/first.json') const second = addTab('workflows/second.json') diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 8b7afb6c658..39c7481c01b 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -13,6 +13,7 @@ import { onMounted, provide, ref, + shallowRef, watch } from 'vue' import { useI18n } from 'vue-i18n' @@ -63,6 +64,7 @@ import { useExecutionErrorStore } from '@/stores/executionErrorStore' import { useWorkflowTabActivityStore } from '@/stores/workflowTabActivityStore' import { useSidebarTabStore } from '@/stores/workspace/sidebarTabStore' import { isLGraphNode } from '@/utils/litegraphUtil' +import Button from '@/components/ui/button/Button.vue' import { useToast } from '@/components/ui/toast/toastStore' import { toOwningGraphId, toRootGraphId } from '@/types/graphScopeId' import type { RootGraphId } from '@/types/graphScopeId' @@ -1510,6 +1512,11 @@ const historyGroups = computed(() => { */ const followOwed = ref(false) let followedChat: { threadId: string; workflowId: string } | null = null +let chatNavigation = 0 +const followFailure = shallowRef<{ + workflowId: string + workflowName: string +} | null>(null) async function selectThread( id: string, @@ -1541,6 +1548,8 @@ async function onSelectHistory( ): Promise { followOwed.value = false followedChat = null + followFailure.value = null + ++chatNavigation return selectThread(id, isCurrent) } @@ -1576,13 +1585,17 @@ function followActiveWorkflowChat(): void { followOwed.value = false return } + const workflow = workflowStore.activeWorkflow const workflowId = activeWorkflowId.value - if (workflowId === undefined) return + if (workflow === null || workflowId === undefined) return const latest = latestChatFor(workflowId) if (latest === undefined) return followOwed.value = false if (latest === threadId.value) return - void openFollowedChat(latest, workflowId) + void openFollowedChat(latest, { + workflowId, + workflowName: workflow.filename + }) } // The chat was opened for the tab the user is on, so that tab is its @@ -1598,21 +1611,50 @@ function restoreChatWorkflow( return onWorkflowRestored(followed ?? workflowId, isCurrent) } -async function openFollowedChat(id: string, workflowId: string): Promise { - followedChat = { threadId: id, workflowId } +async function openFollowedChat( + id: string, + followed: { workflowId: string; workflowName: string } +): Promise { + const navigation = ++chatNavigation + const isCurrent = () => navigation === chatNavigation + const kept = { + threadId: threadId.value, + targetTracking: agentPanelStore.targetTracking + } + followFailure.value = null + followedChat = { threadId: id, workflowId: followed.workflowId } if (composerStore.prompt.references.length === 0 && !composerStore.hasDraft) composerStore.setText('') - // Following the active tab carries no navigation intent to invalidate; - // loadThread's own generation guard already drops a superseded load. - await selectThread(id, () => true) + const opened = await selectThread(id, isCurrent) if (followedChat?.threadId === id) followedChat = null + if (opened || !isCurrent()) return + // The user did not ask for this chat, so a failed open goes back to the + // chat they had, with its target, instead of leaving a broken one open. + followFailure.value = followed + agentPanelStore.targetTracking = kept.targetTracking + if (kept.threadId === null) newChat() + else await loadThread(kept.threadId, isCurrent) } +function onRetryFollow(): void { + const failed = followFailure.value + followFailure.value = null + if (failed === null) return + const latest = latestChatFor(failed.workflowId) + if (latest !== undefined && latest !== threadId.value) + void openFollowedChat(latest, failed) +} + +onBeforeUnmount(() => { + ++chatNavigation +}) + // Synchronous, so a tab the panel is opening itself is still recognised as // such when it becomes active. watch( () => workflowStore.activeWorkflow, (workflow) => { + followFailure.value = null followOwed.value = workflow !== null && !workflow.isTemporary && @@ -1796,6 +1838,8 @@ function onNewChat(source?: 'new_chat_button' | 'history_delete'): void { // does: a follow still waiting on a cloud id or a summary list would land // the tab's older thread on top of the chat the user just opened. followOwed.value = false + followFailure.value = null + ++chatNavigation composerStore.invalidateSubmission() cancelWorkflowSelection() canvasStore.stopNodePicking() @@ -2182,6 +2226,32 @@ async function onPanelDrop(event: DragEvent): Promise {