diff --git a/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts b/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts new file mode 100644 index 00000000000..b3e1355454a --- /dev/null +++ b/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts @@ -0,0 +1,293 @@ +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' +// A workflow can carry any number of chats -- `workflow_id` is optional on +// thread creation and never made unique -- and any of them can be archived. +// These two are the portrait tab's other chats: one archived and the most +// recently active of the three, one still active and the least recent. +const ARCHIVED_PORTRAIT_THREAD_ID = 'd5b8f3e2-6c4a-4f7b-8d9e-2a3b4c5d6e7f' +const STALE_PORTRAIT_THREAD_ID = 'f6c9a4d3-7d5b-4a8c-9e0f-3b4c5d6e7f80' +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 ARCHIVED_PORTRAIT_REQUEST = 'Crop the portrait study square' +const STALE_PORTRAIT_REQUEST = 'Start the portrait study' +const AT = '2026-09-22T10:00:00Z' +const LATER = '2026-09-22T12:00:00Z' +const EARLIER = '2026-09-22T08: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, + { + status = 'active', + at = AT + }: { status?: 'active' | 'archived'; at?: string } = {} +): AgentThreadListResponse['threads'][number] { + return { + id, + title, + preview, + workflow_id: workflowId, + status, + 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), + [ARCHIVED_PORTRAIT_THREAD_ID]: transcript( + ARCHIVED_PORTRAIT_THREAD_ID, + PORTRAIT_WORKFLOW_ID, + ARCHIVED_PORTRAIT_REQUEST + ), + [STALE_PORTRAIT_THREAD_ID]: transcript( + STALE_PORTRAIT_THREAD_ID, + PORTRAIT_WORKFLOW_ID, + STALE_PORTRAIT_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 } +} + +// The portrait tab's three chats are listed so that every cheaper rule picks +// the wrong one: the archived chat is first and the most recently active of +// the three, and the stale chat is the first one still active. Only "the most +// recently active chat that is not archived" lands on 'Portrait chat'. +const threads: AgentThreadListResponse = { + threads: [ + thread( + ARCHIVED_PORTRAIT_THREAD_ID, + 'Archived portrait chat', + ARCHIVED_PORTRAIT_REQUEST, + PORTRAIT_WORKFLOW_ID, + { status: 'archived', at: LATER } + ), + thread( + STALE_PORTRAIT_THREAD_ID, + 'Stale portrait chat', + STALE_PORTRAIT_REQUEST, + PORTRAIT_WORKFLOW_ID, + { at: EARLIER } + ), + 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: 5, 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() + }) + + // Three chats are bound to this workflow, so this also pins which one a + // tab opens: not the archived one even though it is listed first and was + // worked in most recently, and not the stale one. + await test.step('activating the portrait tab brings up its most recent live 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) + 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 f0b8ae2c05f..e4ad2f45aa5 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -5387,6 +5387,432 @@ 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, init?: RequestInit) => { + const url = String(input) + if (init?.method === 'POST' && url.includes('/messages')) + return json(202, ack('wf-second')) + 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([]) + }) + + // `workflow_id` is not unique across threads and a thread can be archived, + // so "the chat for this tab" is a rule rather than the first row that + // matches. Both cases below list the wrong answer first, so picking by + // list order fails them. + it('opens the tab chat that is still active, not an archived one', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-first-archived', + title: 'Archived chat', + last_message_at: '2026-09-22T12:00:00Z', + status: 'archived', + workflow_id: 'wf-first' + }), + 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'), + { timeout: FOLLOW_LANDS_WITHIN_MS } + ) + expect(loadedThreads).toEqual(['th-first']) + }) + + it('opens the most recently active chat when the tab has several', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-first-stale', + title: 'Stale chat', + last_message_at: '2026-09-22T08:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-first-recent', + title: 'Recent chat', + last_message_at: '2026-09-22T11:00:00Z', + workflow_id: 'wf-first' + }) + ]) + + renderWithSelectedTarget() + workflowStore.activeWorkflow = first + + await vi.waitFor( + () => + expect(useAgentConversationStore().threadId).toBe('th-first-recent'), + { timeout: FOLLOW_LANDS_WITHIN_MS } + ) + expect(loadedThreads).toEqual(['th-first-recent']) + }) + + // Retargeting the agent mid-turn is already refused by `canSelectTarget`. + // Activating a tab reaches the same place by a different door, so looking + // at another tab while a turn streams must not move the chat -- and must + // not stop following once the turn is over. + it('does not move the chat while a turn is streaming', 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() + await sendFromComposer('keep working on this one') + + workflowStore.activeWorkflow = first + + await expect( + vi.waitFor(() => expect(loadedThreads).not.toEqual([]), { + timeout: FOLLOW_LANDS_WITHIN_MS + }) + ).rejects.toThrow() + expect(useAgentConversationStore().threadId).toBe('th-1') + + dispatchApiEvent('agent_message_done', { + message_id: 'm-1', + thread_id: 'th-1' + }) + await screen.findByRole('button', { name: 'Send' }) + + workflowStore.activeWorkflow = second + await nextTick() + workflowStore.activeWorkflow = first + + await vi.waitFor( + () => expect(useAgentConversationStore().threadId).toBe('th-first'), + { timeout: FOLLOW_LANDS_WITHIN_MS } + ) + expect(loadedThreads).toEqual(['th-first']) + }) + }) + 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 fee648170dd..9e8f8fc80ff 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -1488,9 +1488,12 @@ function toChatSession(thread: AgentThreadSummary): ChatSession { } } +const threadSummaries = ref([]) + async function refreshHistory(): Promise { try { - history.replaceAll((await listThreads()).map(toChatSession)) + threadSummaries.value = await listThreads() + history.replaceAll(threadSummaries.value.map(toChatSession)) } catch (error) { reportError(error, { surface: 'agent', @@ -1545,7 +1548,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 { @@ -1563,6 +1580,117 @@ 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 +}) + +/** + * Whether the session is between turns. Every other thing that moves the + * agent's workflow context is gated on this -- `canSelectTarget` above is + * built from the same two refs -- so the follow is gated on it too. Without + * that, looking at another tab mid-turn would call `loadThread`, which stashes + * the running turn and clears the binding, and the panel would navigate away + * from the conversation the agent is streaming into. + */ +const sessionIdle = computed(() => !isSending.value && status.value === 'idle') + +/** + * When a thread was last worked in. `last_message_at` is empty on a thread + * with no activity yet, so creation time stands in and the ordering stays + * total. Parsed rather than compared as text because the ordering has to hold + * for any RFC3339 the server emits, not only the UTC form it emits today. + */ +function threadActivityAt(thread: AgentThreadSummary): number { + const stamp = Date.parse(thread.last_message_at || thread.created_at) + return Number.isNaN(stamp) ? 0 : stamp +} + +/** + * The chat a workflow tab opens. Nothing makes `workflow_id` unique across + * threads -- it is optional on thread creation and a user can start any number + * of chats about one workflow -- so this needs a rule of its own rather than + * whichever row the page happens to list first. Archived chats are not + * candidates, and the most recently active of what remains wins: that is the + * chat the user last worked in, and mid-stream it is the one the agent is + * writing into. + */ +function threadForWorkflow(workflowId: string): AgentThreadSummary | undefined { + return threadSummaries.value.reduce( + (best, thread) => + thread.workflow_id === workflowId && + thread.status === 'active' && + (best === undefined || threadActivityAt(thread) > threadActivityAt(best)) + ? thread + : best, + 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 + } + // A turn that starts after the activation retires the follow for the same + // reason arming refuses one: the cloud id and the summary list can resolve + // mid-turn, and landing the follow then would move the chat out from under + // the running turn. + if (!sessionIdle.value) { + followOwed.value = false + return + } + const workflowId = activeWorkflowId.value + if (workflowId === undefined) return + const matchingThread = threadForWorkflow(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 && sessionIdle.value + 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) => { @@ -1722,6 +1850,10 @@ function onDeleteHistory(id: string): void { function onNewChat(source?: 'new_chat_button' | 'history_delete'): void { provisionalTitle.value = undefined + // 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()