diff --git a/browser_tests/fixtures/agentConversationFixture.ts b/browser_tests/fixtures/agentConversationFixture.ts index a951e2f4ca7..4846e881c11 100644 --- a/browser_tests/fixtures/agentConversationFixture.ts +++ b/browser_tests/fixtures/agentConversationFixture.ts @@ -55,7 +55,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 { mockEmptyAgentThreadList } from '@e2e/fixtures/utils/agentThreadList' import type { TabSwitchLens, WorkspaceStore } from '@e2e/types/globals' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' @@ -714,9 +714,7 @@ export class AgentConversationHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute(emptyAgentThreadList())) - ) + await mockEmptyAgentThreadList(page) await page.route('**/api/agent/threads/*/messages', (route) => { const request = route.request() if (request.method() === 'POST') { @@ -917,9 +915,6 @@ export class AgentConversationHarness { const before = new Set(await this.graphNodeIds()) await this.page.mouse.dblclick(position.x, position.y, { delay: 5 }) const dialog = this.page.getByRole('search') - // Scoped by accessible name: the seed workflow already has nodes on the - // canvas, and a widget-select trigger (e.g. LoadImage's) is also - // role="combobox", so an unnamed query resolves to more than one match. const input = dialog.getByRole('combobox', { name: enMessages.g.addNode }) await input.waitFor({ state: 'visible' }) await input.fill('Note') @@ -940,7 +935,12 @@ export class AgentConversationHarness { return Boolean(ghostNode?.flags.ghost) }) - await this.page.mouse.click(position.x, position.y) + const canvasBounds = await this.comfyPage.canvas.boundingBox() + if (!canvasBounds) throw new Error('Canvas bounding box not available') + await this.comfyPage.canvasOps.click({ + x: position.x - canvasBounds.x, + y: position.y - canvasBounds.y + }) const after = await this.graphNodeIds() const [added] = after.filter((id) => !before.has(id)) if (!added) throw new Error('the search box add produced no node') diff --git a/browser_tests/fixtures/agentTabActivationFixture.ts b/browser_tests/fixtures/agentTabActivationFixture.ts new file mode 100644 index 00000000000..0b14a28b882 --- /dev/null +++ b/browser_tests/fixtures/agentTabActivationFixture.ts @@ -0,0 +1,114 @@ +import { expect } from '@playwright/test' +import type { Page } from '@playwright/test' + +import { agentTest, bootAgentApp } from '@e2e/fixtures/agentPanelFixture' +import { AGENT_SOCKET_URL } from '@e2e/fixtures/agentSocket' +import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { Topbar } from '@e2e/fixtures/components/Topbar' +import { agentComposerRunMode } from '@e2e/fixtures/data/agent/agentComposerPerformance' +import { + tabActivationChats, + tabActivationTranscriptReads +} from '@e2e/fixtures/data/agent/tabActivationChats' +import { AgentWorkflowChatsMock } from '@e2e/fixtures/helpers/agentWorkflowChats' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { nextFrame } from '@e2e/fixtures/utils/timing' + +class TabActivationChats { + readonly panel: AgentPanel + readonly topbar: Topbar + readonly transcriptReads: string[] = [] + + constructor(private readonly page: Page) { + this.panel = new AgentPanel(page) + this.topbar = new Topbar(page) + } + + private async refreshAfter(action: () => Promise): Promise { + const [response] = await Promise.all([ + this.page.waitForResponse( + (response) => + new URL(response.url()).pathname === '/api/agent/threads' && + response.request().method() === 'GET' + ), + action() + ]) + expect(await response.finished()).toBeNull() + await nextFrame(this.page) + } + + async openChatFromHistory(title: string): Promise { + await this.refreshAfter(() => this.panel.historyButton.click()) + await this.refreshAfter(() => + this.panel.root.getByRole('button', { name: title, exact: true }).click() + ) + await this.waitForFollowToSettle() + } + + async activateWorkflow(name: string): Promise { + await this.topbar.getWorkflowTab(name).click() + await this.waitForFollowToSettle() + } + + async waitForFollowToSettle(): Promise { + await nextFrame(this.page) + await expect( + this.panel.root.getByTestId('agent-panel-footer') + ).not.toHaveAttribute('inert') + } +} + +export const tabActivationTest = agentTest.extend<{ + tabChats: TabActivationChats +}>({ + tabChats: async ({ page, agentFlagEnabled }, use) => { + const chats = new AgentWorkflowChatsMock(tabActivationChats) + const tabChats = new TabActivationChats(page) + const unexpectedMutations: string[] = [] + await page.route( + (url) => url.pathname.startsWith('/api/'), + (route) => { + if (route.request().method() !== 'GET') + unexpectedMutations.push( + `${route.request().method()} ${new URL(route.request().url()).pathname}` + ) + return route.fulfill({ status: 404, json: {} }) + } + ) + await page.routeWebSocket(AGENT_SOCKET_URL, () => {}) + 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 chats.route(page) + await page.route('**/api/agent/threads/*/messages', (route) => { + if (route.request().method() === 'GET') + tabChats.transcriptReads.push( + new URL(route.request().url()).pathname.split('/')[4] + ) + return route.fallback() + }) + await page.route('**/api/agent/run-mode', (route) => + route.fulfill(jsonRoute(agentComposerRunMode)) + ) + await page.route('**/api/experiment/models', (route) => + route.fulfill(jsonRoute([])) + ) + await page.route('**/api/internal/cloud_analytics', (route) => + route.fulfill({ status: 204 }) + ) + } + }) + await tabChats.panel.open() + await use(tabChats) + await tabChats.waitForFollowToSettle() + expect(tabChats.transcriptReads).toEqual(tabActivationTranscriptReads) + expect(unexpectedMutations).toEqual([]) + } +}) diff --git a/browser_tests/fixtures/agentTabChatTransitionsFixture.ts b/browser_tests/fixtures/agentTabChatTransitionsFixture.ts new file mode 100644 index 00000000000..487aa7e3451 --- /dev/null +++ b/browser_tests/fixtures/agentTabChatTransitionsFixture.ts @@ -0,0 +1,321 @@ +import type { + AgentMessage, + AgentPostMessageRequest, + AgentRunMode, + AgentSkillListResponse +} from '@comfyorg/ingest-types' +import { zAgentPostMessageRequest } from '@comfyorg/ingest-types/zod' +import { expect } from '@playwright/test' +import type { Page, Route, WebSocketRoute } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } +import type { + AgentTurnAccepted, + AgentWsEvent +} from '@/workbench/extensions/agent/schemas/agentApiSchema' + +import { agentTest, bootAgentApp } from '@e2e/fixtures/agentPanelFixture' +import { AGENT_SOCKET_URL } from '@e2e/fixtures/agentSocket' +import { AgentPanel } from '@e2e/fixtures/components/AgentPanel' +import { Topbar } from '@e2e/fixtures/components/Topbar' +import { + agentThreadSummary, + agentUserTranscript +} from '@e2e/fixtures/data/agent/agentThreadList' +import { AgentWorkflowChatsMock } from '@e2e/fixtures/helpers/agentWorkflowChats' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' +import { nextFrame } from '@e2e/fixtures/utils/timing' + +const WORKFLOWS = [ + { name: 'Portrait', id: 'af1dcab5-b7e9-47ac-b1cf-c6fd1f803a31' }, + { name: 'Landscape', id: 'b98ed2f5-089b-46e8-b650-9d8c387bb15b' }, + { name: 'Still Life', id: 'c23d77bf-68dc-45e3-b8bf-8f142d570e31' } +] +const THREADS = [ + 'e43232b2-1f56-4f7f-a905-a808dce1b811', + 'fbd667e5-137e-4a8a-ab28-c3b6101d85dc', + 'a89fc2bf-3fdd-4d61-9305-e316fa079323' +] +const SKILL_NAME = 'tab-preservation' +const SKILLS: AgentSkillListResponse = { + skills: [ + { + id: 'tab-preservation-skill', + name: SKILL_NAME, + description: 'A fixture skill for testing draft retention.', + body: 'Reply briefly; do not run workflows.', + body_hash: 'a'.repeat(64), + created_at: '2026-10-16T00:00:00Z', + updated_at: '2026-10-16T00:00:00Z' + } + ] +} + +function deferred() { + let resolve!: () => void + const promise = new Promise((settle) => { + resolve = settle + }) + return { promise, resolve } +} + +class TabChatTransitions { + readonly panel: AgentPanel + readonly topbar: Topbar + readonly workflows = WORKFLOWS + readonly threads = THREADS + readonly skillName = SKILL_NAME + readonly posted: { threadId: string; body: AgentPostMessageRequest }[] = [] + readonly unexpectedMutations: string[] = [] + private agentSocket: WebSocketRoute | undefined + private held: + | { + threadId: string + status: number + started: boolean + entered: ReturnType + release: ReturnType + settled: ReturnType + } + | undefined + private readonly transcripts: Record = + Object.fromEntries( + WORKFLOWS.map(({ name, id }, index) => [ + THREADS[index], + agentUserTranscript(THREADS[index], id, `${name} existing request`) + ]) + ) + + constructor(private readonly page: Page) { + this.panel = new AgentPanel(page) + this.topbar = new Topbar(page) + } + + async install(): Promise { + await this.page.route( + (url) => url.pathname.startsWith('/api/'), + (route) => { + if (route.request().method() !== 'GET') + this.unexpectedMutations.push( + `${route.request().method()} ${new URL(route.request().url()).pathname}` + ) + return route.fulfill({ status: 404, json: {} }) + } + ) + await this.page.routeWebSocket(AGENT_SOCKET_URL, (socket) => { + this.agentSocket = socket + }) + await this.page.routeWebSocket(/\/ws(?:\?|$)/, (socket) => { + socket.send( + JSON.stringify({ + type: 'status', + data: { + sid: 'tab-chats', + status: { exec_info: { queue_remaining: 0 } } + } + }) + ) + }) + } + + async routeChats(): Promise { + const chats = new AgentWorkflowChatsMock({ + workflows: WORKFLOWS.map((workflow) => ({ + ...workflow, + content: { + last_node_id: 0, + last_link_id: 0, + nodes: [], + links: [], + groups: [], + config: {}, + extra: {}, + version: 0.4 + } + })), + threads: WORKFLOWS.map(({ name, id }, index) => + agentThreadSummary(THREADS[index], `${name} chat`, { + workflow_id: id, + preview: `${name} existing request` + }) + ), + transcripts: this.transcripts + }) + await chats.route(this.page) + const runMode: AgentRunMode = { mode: 'ask_approval', credit_limit: null } + await this.page.route('**/api/agent/run-mode', (route) => + route.fulfill(jsonRoute(runMode)) + ) + await this.page.route('**/api/experiment/models', (route) => + route.fulfill(jsonRoute([])) + ) + await this.page.route('**/api/agent/skills', (route) => + route.fulfill(jsonRoute(SKILLS)) + ) + await this.page.route('**/api/internal/cloud_analytics', (route) => + route.fulfill({ status: 204 }) + ) + await this.page.route('**/api/agent/threads/*/messages', (route) => + this.handleMessages(route) + ) + } + + private async handleMessages(route: Route): Promise { + const request = route.request() + const threadId = new URL(request.url()).pathname.split('/')[4] + if (request.method() === 'POST') return this.acceptMessage(route, threadId) + if (request.method() !== 'GET') return route.fallback() + await this.readMessages(route, threadId) + } + + private async acceptMessage(route: Route, threadId: string): Promise { + const body = zAgentPostMessageRequest.parse(route.request().postDataJSON()) + this.posted.push({ threadId, body }) + const messageId = `${threadId}-accepted-${this.posted.length}` + this.transcripts[threadId] = [ + ...this.transcripts[threadId], + { + id: messageId, + thread_id: threadId, + turn_id: messageId, + role: 'assistant', + status: 'streaming', + seq: this.transcripts[threadId].length + 1, + workflow_id: body.workflow_id, + content: { text: '' } + } + ] + const accepted: AgentTurnAccepted = { + message_id: messageId, + thread_id: threadId, + workflow_id: body.workflow_id + } + await route.fulfill({ ...jsonRoute(accepted), status: 202 }) + } + + private async readMessages(route: Route, threadId: string): Promise { + const held = this.held?.threadId === threadId ? this.held : undefined + if (held) { + held.started = true + held.entered.resolve() + } + await held?.release.promise + try { + await route.fulfill( + held && held.status >= 400 + ? { status: held.status, json: { error: 'Transcript unavailable' } } + : jsonRoute(this.transcripts[threadId] ?? []) + ) + if (held) await (await route.request().response())?.finished() + } finally { + held?.settled.resolve() + } + } + + async openChat(index: number): Promise { + await this.panel.openChatFromHistory(`${WORKFLOWS[index].name} chat`) + await expect(this.panel.userMessageBubbles).toHaveText([ + `${WORKFLOWS[index].name} existing request` + ]) + } + + tab(index: number) { + return this.topbar.getWorkflowTab(WORKFLOWS[index].name) + } + + opening(index: number) { + return this.panel.root.getByRole('status', { + name: `Opening chat for ${WORKFLOWS[index].name}…`, + exact: true + }) + } + + working(index: number) { + return this.tab(index).getByRole('img', { + name: enMessages.g.agentWorking, + exact: true + }) + } + + updated(index: number) { + return this.tab(index).getByRole('img', { + name: enMessages.g.agentModified, + exact: true + }) + } + + holdMessages(index: number, status = 200) { + const held = { + threadId: THREADS[index], + status, + started: false, + entered: deferred(), + release: deferred(), + settled: deferred() + } + this.held = held + return { + entered: held.entered.promise, + release: async () => { + held.release.resolve() + await held.settled.promise + if (this.held === held) this.held = undefined + await nextFrame(this.page) + } + } + } + + complete(index: number): void { + const threadId = THREADS[index] + const assistant = this.transcripts[threadId].findLast( + (message) => message.role === 'assistant' + ) + if (!assistant || !this.agentSocket) + throw new Error('No accepted turn and connected fixture agent socket') + assistant.status = 'complete' + const event: AgentWsEvent = { + type: 'agent_message_done', + data: { message_id: assistant.id, thread_id: threadId } + } + this.agentSocket.send(JSON.stringify(event)) + } + + async dispose(): Promise { + const held = this.held + held?.release.resolve() + if (held?.started) await held.settled.promise + } +} + +export const tabChatTransitionsTest = agentTest.extend<{ + tabChats: TabChatTransitions +}>({ + tabChats: async ({ page, agentFlagEnabled }, use) => { + const fixture = new TabChatTransitions(page) + await fixture.install() + try { + await bootAgentApp(page, agentFlagEnabled, { + features: { + posthog_config: { + advanced_disable_flags: true, + bootstrap: { + featureFlags: { + 'agent-in-app-experience': true, + 'agent-skill-packs': true + } + } + } + }, + beforeNavigate: () => fixture.routeChats() + }) + await fixture.panel.open() + await fixture.openChat(1) + await fixture.openChat(2) + await fixture.openChat(0) + await use(fixture) + expect(fixture.unexpectedMutations).toEqual([]) + } finally { + await fixture.dispose() + } + } +}) diff --git a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts index 8b94787c072..b5c85939c08 100644 --- a/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts +++ b/browser_tests/fixtures/agentTwoSessionCrdtFixture.ts @@ -30,7 +30,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 { mockEmptyAgentThreadList } from '@e2e/fixtures/utils/agentThreadList' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' const SOCKET_SID = 'b6f0a2c1-8e34-4d21-9c07-2a1b3c4d5e60' @@ -299,9 +299,7 @@ export class AgentTwoSessionCrdtHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute(emptyAgentThreadList())) - ) + await mockEmptyAgentThreadList(page) await page.route('**/api/agent/threads/*/messages', (route) => { const request = route.request() if (request.method() === 'POST') { diff --git a/browser_tests/fixtures/components/AgentPanel.ts b/browser_tests/fixtures/components/AgentPanel.ts index 1f1348cdbb6..18fc4a05480 100644 --- a/browser_tests/fixtures/components/AgentPanel.ts +++ b/browser_tests/fixtures/components/AgentPanel.ts @@ -37,6 +37,7 @@ export class AgentPanel { public readonly dockedPanel: Locator public readonly dockedPanelShell: Locator public readonly fileInput: Locator + public readonly historyButton: Locator public readonly nodeSelectionBanner: Locator public readonly openButton: Locator public readonly resizeHandle: Locator @@ -48,6 +49,7 @@ export class AgentPanel { public readonly stopButton: Locator public readonly suggestedPrompts: Locator private readonly toasts: ToastHelper + public readonly userMessageBubbles: Locator public readonly workflowPicker: Locator public readonly workflowSwitch: Locator public readonly workSummary: Locator @@ -88,6 +90,9 @@ export class AgentPanel { this.dockedPanel = page.getByTestId('docked-agent-panel') this.dockedPanelShell = page.getByTestId('docked-agent-panel-shell') this.fileInput = this.root.getByTestId('agent-file-input') + this.historyButton = this.root.getByRole('button', { + name: enMessages.agent.showChatHistory + }) this.nodeSelectionBanner = page.getByTestId('node-selection-mode-banner') this.openButton = page.getByRole('button', { name: enMessages.agent.entryButton, @@ -126,6 +131,14 @@ export class AgentPanel { this.workSummary = this.root.getByRole('button', { name: new RegExp(`^${escapeRegExp(enMessages.agent.worked)}`) }) + this.userMessageBubbles = this.root.getByTestId('user-message-bubble') + } + + async openChatFromHistory(title: string): Promise { + await this.historyButton.click() + const row = this.root.getByRole('button', { name: title, exact: true }) + await expect(row).toBeEnabled() + await row.click() } async scrollAssetsToEnd(): Promise { diff --git a/browser_tests/fixtures/data/agent/agentThreadList.ts b/browser_tests/fixtures/data/agent/agentThreadList.ts index c839a2f4b02..3c54ffdb36b 100644 --- a/browser_tests/fixtures/data/agent/agentThreadList.ts +++ b/browser_tests/fixtures/data/agent/agentThreadList.ts @@ -1,11 +1,12 @@ import type { + AgentMessage, AgentThreadListResponse, AgentThreadSummary } from '@comfyorg/ingest-types' const LISTED_AT = '2026-10-01T00:00:00Z' -function agentThreadPage( +export function agentThreadPage( threads: AgentThreadSummary[], nextCursor?: string ): AgentThreadListResponse { @@ -21,7 +22,11 @@ function agentThreadPage( } } -function agentThreadSummary(id: string, title: string): AgentThreadSummary { +export function agentThreadSummary( + id: string, + title: string, + overrides: Partial = {} +): AgentThreadSummary { return { id, title, @@ -31,10 +36,30 @@ function agentThreadSummary(id: string, title: string): AgentThreadSummary { created_at: LISTED_AT, updated_at: LISTED_AT, last_message_at: LISTED_AT, - workflow_id: '' + workflow_id: '', + ...overrides } } +export function agentUserTranscript( + 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 } + } + ] +} + export function emptyAgentThreadList(): AgentThreadListResponse { return agentThreadPage([]) } diff --git a/browser_tests/fixtures/data/agent/tabActivationChats.ts b/browser_tests/fixtures/data/agent/tabActivationChats.ts new file mode 100644 index 00000000000..806d4624578 --- /dev/null +++ b/browser_tests/fixtures/data/agent/tabActivationChats.ts @@ -0,0 +1,83 @@ +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' + +import { + agentThreadSummary, + agentUserTranscript +} from '@e2e/fixtures/data/agent/agentThreadList' + +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' + +export const PORTRAIT_NAME = 'Portrait Study' +export const LANDSCAPE_NAME = 'Landscape Study' +export const PORTRAIT_REQUEST = 'Tidy up the portrait study' +export const LANDSCAPE_REQUEST = 'Widen the landscape study' +export const UNBOUND_REQUEST = 'What does a KSampler do?' +export const LANDSCAPE_DRAFT = 'Now add a sunset' + +export const tabActivationTranscriptReads = [ + PORTRAIT_THREAD_ID, + LANDSCAPE_THREAD_ID, + PORTRAIT_THREAD_ID, + UNBOUND_THREAD_ID, + LANDSCAPE_THREAD_ID +] + +const EMPTY_WORKFLOW: ComfyWorkflowJSON = { + last_node_id: 0, + last_link_id: 0, + nodes: [], + links: [], + groups: [], + config: {}, + extra: {}, + version: 0.4 +} + +export const tabActivationChats = { + workflows: [ + { + id: PORTRAIT_WORKFLOW_ID, + name: PORTRAIT_NAME, + content: EMPTY_WORKFLOW + }, + { + id: LANDSCAPE_WORKFLOW_ID, + name: LANDSCAPE_NAME, + content: EMPTY_WORKFLOW + } + ], + threads: [ + agentThreadSummary(PORTRAIT_THREAD_ID, 'Portrait chat', { + preview: PORTRAIT_REQUEST, + workflow_id: PORTRAIT_WORKFLOW_ID + }), + agentThreadSummary(LANDSCAPE_THREAD_ID, 'Landscape chat', { + preview: LANDSCAPE_REQUEST, + workflow_id: LANDSCAPE_WORKFLOW_ID + }), + agentThreadSummary(UNBOUND_THREAD_ID, 'Unbound chat', { + preview: UNBOUND_REQUEST + }) + ], + transcripts: { + [PORTRAIT_THREAD_ID]: agentUserTranscript( + PORTRAIT_THREAD_ID, + PORTRAIT_WORKFLOW_ID, + PORTRAIT_REQUEST + ), + [LANDSCAPE_THREAD_ID]: agentUserTranscript( + LANDSCAPE_THREAD_ID, + LANDSCAPE_WORKFLOW_ID, + LANDSCAPE_REQUEST + ), + [UNBOUND_THREAD_ID]: agentUserTranscript( + UNBOUND_THREAD_ID, + '', + UNBOUND_REQUEST + ) + } +} diff --git a/browser_tests/fixtures/helpers/agentWorkflowChats.ts b/browser_tests/fixtures/helpers/agentWorkflowChats.ts new file mode 100644 index 00000000000..330c126e9a5 --- /dev/null +++ b/browser_tests/fixtures/helpers/agentWorkflowChats.ts @@ -0,0 +1,95 @@ +import type { Page } from '@playwright/test' + +import type { + AgentMessage, + AgentThreadSummary, + WorkflowListResponse +} from '@comfyorg/ingest-types' + +import type { UserDataFullInfo } from '@/platform/remote/comfyui/types' +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' + +import { agentThreadPage } from '@e2e/fixtures/data/agent/agentThreadList' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' + +const SAVED_AT = '2026-09-22T10:00:00Z' + +interface SavedCloudWorkflow { + id: string + name: string + content: ComfyWorkflowJSON +} + +/** Serves saved cloud workflows, the chat list and each chat's transcript. */ +export class AgentWorkflowChatsMock { + private listReads = 0 + + constructor( + private readonly chats: { + workflows: SavedCloudWorkflow[] + threads: AgentThreadSummary[] + transcripts: Record + } + ) {} + + get threadListReads(): number { + return this.listReads + } + + async route(page: Page): Promise { + const { workflows, threads, transcripts } = this.chats + const savedFiles: UserDataFullInfo[] = workflows.map( + ({ name, content }) => ({ + path: `${name}.json`, + modified: Date.parse(SAVED_AT), + size: JSON.stringify(content).length + }) + ) + const cloudWorkflows: WorkflowListResponse = { + data: workflows.map(({ id, name }) => ({ + id, + name, + created_at: SAVED_AT, + updated_at: SAVED_AT, + created_by: 'test-user-e2e', + latest_version: 1 + })), + pagination: { + offset: 0, + limit: 100, + total: workflows.length, + has_more: false + } + } + + await page.route('**/api/agent/threads?*', (route) => { + this.listReads += 1 + return route.fulfill(jsonRoute(agentThreadPage(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( + (url) => + url.pathname.endsWith('/api/userdata') && + url.searchParams.get('dir') === 'workflows', + (route) => route.fulfill(jsonRoute(savedFiles)) + ) + for (const { name, content } of workflows) + await page.route( + (url) => + decodeURIComponent(url.pathname).endsWith( + `/api/userdata/workflows/${name}.json` + ), + (route) => + route.request().method() === 'GET' + ? route.fulfill(jsonRoute(content)) + : route.fallback() + ) + } +} diff --git a/browser_tests/fixtures/load3dAgentFixture.ts b/browser_tests/fixtures/load3dAgentFixture.ts index 6f5d5b3b3d9..af1b82620ed 100644 --- a/browser_tests/fixtures/load3dAgentFixture.ts +++ b/browser_tests/fixtures/load3dAgentFixture.ts @@ -16,7 +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 { mockEmptyAgentThreadList } from '@e2e/fixtures/utils/agentThreadList' import { TestIds } from '@e2e/fixtures/selectors' import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' import { assetPath } from '@e2e/fixtures/utils/paths' @@ -271,9 +271,7 @@ class Load3dAgentHarness { private async mockAgentApi(): Promise { const { page } = this - await page.route('**/api/agent/threads?*', (route) => - route.fulfill(jsonRoute(emptyAgentThreadList())) - ) + await mockEmptyAgentThreadList(page) await page.route('**/api/agent/threads/*/messages', (route) => route.fulfill(jsonRoute([])) ) diff --git a/browser_tests/fixtures/utils/agentThreadList.ts b/browser_tests/fixtures/utils/agentThreadList.ts new file mode 100644 index 00000000000..2e89c477b96 --- /dev/null +++ b/browser_tests/fixtures/utils/agentThreadList.ts @@ -0,0 +1,10 @@ +import type { Page } from '@playwright/test' + +import { emptyAgentThreadList } from '@e2e/fixtures/data/agent/agentThreadList' +import { jsonRoute } from '@e2e/fixtures/utils/jsonRoute' + +export async function mockEmptyAgentThreadList(page: Page): Promise { + await page.route('**/api/agent/threads?*', (route) => + route.fulfill(jsonRoute(emptyAgentThreadList())) + ) +} diff --git a/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts b/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts new file mode 100644 index 00000000000..c8205417651 --- /dev/null +++ b/browser_tests/tests/agent/agentTabActivationFollowsChat.spec.ts @@ -0,0 +1,94 @@ +import { expect } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } + +import { tabActivationTest as test } from '@e2e/fixtures/agentTabActivationFixture' +import { + LANDSCAPE_DRAFT, + LANDSCAPE_NAME, + LANDSCAPE_REQUEST, + PORTRAIT_NAME, + PORTRAIT_REQUEST, + UNBOUND_REQUEST +} from '@e2e/fixtures/data/agent/tabActivationChats' + +test.describe( + 'Agent chat follows the active workflow tab', + { tag: ['@cloud', '@agent'] }, + () => { + test('brings up the tab’s chat on activation unless a chat is picked or drafted', async ({ + tabChats + }) => { + await test.step('each chat opens a tab for the workflow it is bound to', async () => { + await tabChats.openChatFromHistory('Portrait chat') + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + PORTRAIT_REQUEST + ]) + await expect( + tabChats.topbar.getWorkflowTab(PORTRAIT_NAME) + ).toBeVisible() + await tabChats.openChatFromHistory('Landscape chat') + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + LANDSCAPE_REQUEST + ]) + await expect( + tabChats.topbar + .getWorkflowTab(LANDSCAPE_NAME) + .and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + }) + + await test.step('activating the portrait tab brings up the portrait chat', async () => { + await tabChats.activateWorkflow(PORTRAIT_NAME) + await expect( + tabChats.topbar + .getWorkflowTab(PORTRAIT_NAME) + .and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + PORTRAIT_REQUEST + ]) + }) + + await test.step('a hand-picked chat with no workflow of its own survives the refresh', async () => { + await tabChats.openChatFromHistory('Unbound chat') + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + UNBOUND_REQUEST + ]) + await expect( + tabChats.topbar + .getWorkflowTab(PORTRAIT_NAME) + .and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + }) + + await test.step('a draft keeps the open chat when another tab is activated', async () => { + await tabChats.openChatFromHistory('Landscape chat') + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + LANDSCAPE_REQUEST + ]) + await expect( + tabChats.topbar + .getWorkflowTab(LANDSCAPE_NAME) + .and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + await tabChats.panel.composer.fill(LANDSCAPE_DRAFT) + + await tabChats.activateWorkflow(PORTRAIT_NAME) + + await expect( + tabChats.topbar + .getWorkflowTab(PORTRAIT_NAME) + .and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + await expect(tabChats.panel.root.getByRole('note')).toContainText( + enMessages.agent.viewingDifferentWorkflow + ) + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + LANDSCAPE_REQUEST + ]) + await expect(tabChats.panel.composer).toHaveText(LANDSCAPE_DRAFT) + }) + }) + } +) diff --git a/browser_tests/tests/agent/agentTabChatTransitions.spec.ts b/browser_tests/tests/agent/agentTabChatTransitions.spec.ts new file mode 100644 index 00000000000..e41279aa8b4 --- /dev/null +++ b/browser_tests/tests/agent/agentTabChatTransitions.spec.ts @@ -0,0 +1,149 @@ +import { expect } from '@playwright/test' + +import enMessages from '@/locales/en/main.json' with { type: 'json' } + +import { tabChatTransitionsTest as test } from '@e2e/fixtures/agentTabChatTransitionsFixture' + +test.describe( + 'Workflow tab chat transitions', + { tag: ['@cloud', '@agent'] }, + () => { + for (const status of [200, 500]) { + test(`late B messages ${status} cannot take over after returning to A`, async ({ + tabChats + }) => { + const pending = tabChats.holdMessages(1, status) + + await tabChats.tab(1).click() + await pending.entered + await expect(tabChats.opening(1)).toBeVisible() + await expect(tabChats.panel.sendButton).toBeDisabled() + await tabChats.tab(0).click() + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + 'Portrait existing request' + ]) + await expect(tabChats.opening(1)).toHaveCount(0) + + await pending.release() + + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + 'Portrait existing request' + ]) + await expect( + tabChats.tab(0).and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + await expect(tabChats.panel.workflowPicker).toContainText('Portrait') + await expect(tabChats.panel.composer).toBeEditable() + await expect( + tabChats.panel.root.getByRole('button', { + name: 'Retry', + exact: true + }) + ).toHaveCount(0) + }) + } + + test('Send routes an A-pinned draft to A while B is selected', async ({ + tabChats + }) => { + await tabChats.panel.composer.fill('Draft addressed to Portrait') + await tabChats.tab(1).click() + await expect(tabChats.panel.root.getByRole('note')).toContainText( + enMessages.agent.viewingDifferentWorkflow + ) + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + 'Portrait existing request' + ]) + + await tabChats.panel.sendButton.click() + + await expect.poll(() => tabChats.posted).toHaveLength(1) + expect(tabChats.posted[0]).toMatchObject({ + threadId: tabChats.threads[0], + body: { + content: 'Draft addressed to Portrait', + workflow_id: tabChats.workflows[0].id + } + }) + expect(tabChats.posted[0].body.workflow_id).not.toBe( + tabChats.workflows[1].id + ) + await expect( + tabChats.tab(1).and(tabChats.topbar.getActiveTab()) + ).toBeVisible() + await expect(tabChats.working(0)).toBeVisible() + }) + + test('a skill-only draft survives B activation without retargeting A', async ({ + page, + tabChats + }) => { + await tabChats.panel.composer.fill('/') + await page + .getByRole('menuitem', { name: tabChats.skillName, exact: true }) + .click() + await expect(tabChats.panel.composer).toHaveText(`/${tabChats.skillName}`) + await expect( + tabChats.panel.composer.getByTestId('skill-reference') + ).toHaveCount(1) + + await tabChats.tab(1).click() + + await expect(tabChats.panel.composer).toHaveText(`/${tabChats.skillName}`) + await expect( + tabChats.panel.composer.getByTestId('skill-reference') + ).toHaveCount(1) + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + 'Portrait existing request' + ]) + await expect(tabChats.panel.workflowPicker).toContainText('Portrait') + await expect(tabChats.panel.root.getByRole('note')).toContainText( + enMessages.agent.viewingDifferentWorkflow + ) + expect(tabChats.posted).toEqual([]) + }) + + test('independent background completions clear only their own visible tab indicators', async ({ + tabChats + }) => { + await tabChats.panel.composer.fill('A turn') + await tabChats.panel.sendButton.click() + await expect(tabChats.working(0)).toBeVisible() + const pending = tabChats.holdMessages(1) + + await tabChats.tab(1).click() + await pending.entered + await expect(tabChats.opening(1)).toBeVisible() + await expect(tabChats.working(0)).toBeVisible() + await pending.release() + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + 'Landscape existing request' + ]) + await expect(tabChats.working(0)).toBeVisible() + await tabChats.panel.composer.fill('B turn') + await tabChats.panel.sendButton.click() + await expect(tabChats.working(1)).toBeVisible() + await tabChats.tab(2).click() + await expect(tabChats.panel.userMessageBubbles).toHaveText([ + 'Still Life existing request' + ]) + await expect(tabChats.working(0)).toBeVisible() + await expect(tabChats.working(1)).toBeVisible() + + tabChats.complete(0) + + await expect(tabChats.working(0)).toHaveCount(0) + await expect(tabChats.updated(0)).toBeVisible() + await expect(tabChats.working(1)).toBeVisible() + await expect(tabChats.updated(1)).toHaveCount(0) + + tabChats.complete(1) + + await expect(tabChats.working(1)).toHaveCount(0) + await expect(tabChats.updated(1)).toBeVisible() + await expect(tabChats.updated(0)).toBeVisible() + await expect(tabChats.panel.workflowPicker).toContainText('Still Life') + expect(tabChats.posted).toHaveLength(2) + }) + } +) diff --git a/docs/architecture/domains/boundaries.json b/docs/architecture/domains/boundaries.json index 87a224a89cb..057e7c274be 100644 --- a/docs/architecture/domains/boundaries.json +++ b/docs/architecture/domains/boundaries.json @@ -179,6 +179,7 @@ "src/workbench/extensions/agent/AgentPanelRoot.vue", "src/workbench/extensions/agent/composables/agent/useAgentTargetNavigation.ts", "src/workbench/extensions/agent/composables/useAgentDockMount.test.ts", + "src/workbench/extensions/agent/AgentPanelRoot.tabActivity.test.ts", "src/workbench/extensions/agent/composables/useAgentDockMount.ts", "src/workbench/extensions/agent/crdt/agentCrdtProjection.frameDelta.test.ts", "src/workbench/extensions/agent/crdt/agentCrdtProjection.integration.test.ts", diff --git a/docs/architecture/domains/records/agent.domain.json b/docs/architecture/domains/records/agent.domain.json index a7d2ea9a8a4..0d05aca8e88 100644 --- a/docs/architecture/domains/records/agent.domain.json +++ b/docs/architecture/domains/records/agent.domain.json @@ -151,6 +151,10 @@ "path": "src/workbench/extensions/agent/composables/useAgentDockMount.test.ts", "role": "integration" }, + { + "path": "src/workbench/extensions/agent/AgentPanelRoot.tabActivity.test.ts", + "role": "integration" + }, { "path": "src/workbench/extensions/agent/composables/useAgentDockMount.ts", "role": "integration" @@ -846,6 +850,7 @@ "name": "Panel root and conversation views render replies, paywall, history, and onboarding", "checks": [ "src/workbench/extensions/agent/AgentPanelRoot.test.ts", + "src/workbench/extensions/agent/AgentPanelRoot.tabActivity.test.ts", "src/workbench/extensions/agent/components/agent/AgentPanel.test.ts", "src/workbench/extensions/agent/components/agent/ConversationView.test.ts", "src/workbench/extensions/agent/components/agent/message/AgentMessage.test.ts", diff --git a/src/components/sidebar/tabs/BaseWorkflowsSidebarTab.vue b/src/components/sidebar/tabs/BaseWorkflowsSidebarTab.vue index 4f51866d633..aaee080eae6 100644 --- a/src/components/sidebar/tabs/BaseWorkflowsSidebarTab.vue +++ b/src/components/sidebar/tabs/BaseWorkflowsSidebarTab.vue @@ -238,8 +238,9 @@ const dummyExpandedKeys = ref>({}) const handleCloseWorkflow = async (workflow?: ComfyWorkflow) => { if (workflow) { - await workflowService.closeWorkflow(workflow, { - warnIfUnsaved: !workspaceStore.shiftDown + await workflowService.closeWorkflows([workflow], { + warnIfUnsaved: !workspaceStore.shiftDown, + initiator: 'user' }) } } @@ -342,7 +343,7 @@ const renderTreeNode = ( e: MouseEvent ) { if (this.leaf && workflow) { - await workflowService.openWorkflow(workflow) + await workflowService.openWorkflow(workflow, { initiator: 'user' }) } else { toggleNodeOnEvent(e, this) } diff --git a/src/components/topbar/WorkflowOverflowMenu.test.ts b/src/components/topbar/WorkflowOverflowMenu.test.ts index 165e38787da..5e737d1d3f2 100644 --- a/src/components/topbar/WorkflowOverflowMenu.test.ts +++ b/src/components/topbar/WorkflowOverflowMenu.test.ts @@ -64,5 +64,5 @@ it('marks the agent target separately from the active overflow workflow', async ).toBeNull() await user.click(targetItem) - expect(openWorkflow).toHaveBeenCalledWith(target) + expect(openWorkflow).toHaveBeenCalledWith(target, { initiator: 'user' }) }) diff --git a/src/components/topbar/WorkflowOverflowMenu.vue b/src/components/topbar/WorkflowOverflowMenu.vue index 14f348662aa..df42a5449e0 100644 --- a/src/components/topbar/WorkflowOverflowMenu.vue +++ b/src/components/topbar/WorkflowOverflowMenu.vue @@ -46,7 +46,7 @@ const menuItems = computed(() => icon: props.activeWorkflow?.key === workflow.key ? 'pi pi-check' : undefined, command: () => { - void workflowService.openWorkflow(workflow) + void workflowService.openWorkflow(workflow, { initiator: 'user' }) } })) ) diff --git a/src/components/topbar/WorkflowTab.test.ts b/src/components/topbar/WorkflowTab.test.ts index 041c453b8b5..c699b7508ac 100644 --- a/src/components/topbar/WorkflowTab.test.ts +++ b/src/components/topbar/WorkflowTab.test.ts @@ -63,7 +63,8 @@ const statusAriaLabels: Record = { const agentAriaLabels = { agentWorking: 'Agent is working on this workflow', - agentModified: 'Agent updated this workflow' + agentModified: 'Agent updated this workflow', + agentNeedsApproval: 'Agent needs your approval' } const i18n = createI18n({ @@ -219,7 +220,9 @@ describe('WorkflowTab - agent activity indicators', () => { it('T-17 / PM-658 / FE-1289 renders the active workflow tab loading state', async () => { renderTab({ activeWorkflowKey: 'test-key' }) - useWorkflowTabActivityStore().setEditing('/workflows/test.json') + useWorkflowTabActivityStore().setAgentTurnTabs([ + { path: '/workflows/test.json', awaitingApproval: false } + ]) await nextTick() expect( @@ -230,7 +233,9 @@ describe('WorkflowTab - agent activity indicators', () => { it('the agent spinner wins over the unseen-changes dot', async () => { renderTab() const activity = useWorkflowTabActivityStore() - activity.setEditing('/workflows/test.json') + activity.setAgentTurnTabs([ + { path: '/workflows/test.json', awaitingApproval: false } + ]) activity.markModified('/workflows/test.json') await nextTick() @@ -240,6 +245,33 @@ describe('WorkflowTab - agent activity indicators', () => { expect(screen.queryByTestId('agent-modified-indicator')).toBeNull() }) + it('the needs-approval dot wins over the agent spinner', async () => { + renderTab() + const activity = useWorkflowTabActivityStore() + activity.setAgentTurnTabs([ + { path: '/workflows/test.json', awaitingApproval: true } + ]) + await nextTick() + + expect( + screen.getByRole('img', { name: agentAriaLabels.agentNeedsApproval }) + ).toBeVisible() + expect( + screen.queryByRole('img', { name: agentAriaLabels.agentWorking }) + ).toBeNull() + + activity.setAgentTurnTabs([ + { path: '/workflows/test.json', awaitingApproval: false } + ]) + await nextTick() + expect( + screen.queryByRole('img', { name: agentAriaLabels.agentNeedsApproval }) + ).toBeNull() + expect( + screen.getByRole('img', { name: agentAriaLabels.agentWorking }) + ).toBeVisible() + }) + it('shows the unseen-changes dot ahead of non-failed execution status', async () => { const workflowOption = makeWorkflowOption() vi.mocked(useExecutionStore().getWorkflowStatus).mockReturnValue('running') @@ -294,7 +326,9 @@ describe('WorkflowTab - close button', () => { it('keeps the close button hidden while an active status indicator shows', async () => { renderTab({ activeWorkflowKey: 'test-key' }) - useWorkflowTabActivityStore().setEditing('/workflows/test.json') + useWorkflowTabActivityStore().setAgentTurnTabs([ + { path: '/workflows/test.json', awaitingApproval: false } + ]) await nextTick() expect( @@ -306,14 +340,14 @@ describe('WorkflowTab - close button', () => { ) }) - it('delegates close to workflow service with the tab workflow', async () => { + it('delegates close to workflow service as a user action on the tab workflow', async () => { renderTab() const user = userEvent.setup() await user.click(screen.getByTestId('close-workflow-button')) - expect(useWorkflowService().closeWorkflow).toHaveBeenCalledWith( - expect.objectContaining({ key: 'test-key' }), - expect.anything() + expect(useWorkflowService().closeWorkflows).toHaveBeenCalledWith( + [expect.objectContaining({ key: 'test-key' })], + expect.objectContaining({ initiator: 'user' }) ) }) }) @@ -401,14 +435,16 @@ describe('WorkflowTab - Agent target', () => { panel.enabled = true panel.setWorkflowTarget(workflowOption.workflow) const activity = useWorkflowTabActivityStore() - activity.setEditing(workflowOption.workflow.path) + activity.setAgentTurnTabs([ + { path: workflowOption.workflow.path, awaitingApproval: false } + ]) await nextTick() expect(screen.getByRole('img', { name: targetLabel })).toBeVisible() expect( screen.getByRole('img', { name: agentAriaLabels.agentWorking }) ).toBeVisible() - activity.setEditing(null) + activity.setAgentTurnTabs([]) activity.markModified(workflowOption.workflow.path) await nextTick() expect(screen.getByRole('img', { name: targetLabel })).toBeVisible() @@ -419,9 +455,9 @@ describe('WorkflowTab - Agent target', () => { expect(screen.getByRole('img', { name: targetLabel })).toBeVisible() expect(screen.getByTestId('workflow-dirty-indicator')).toBeVisible() await userEvent.setup().click(screen.getByTestId('close-workflow-button')) - expect(useWorkflowService().closeWorkflow).toHaveBeenCalledWith( - workflowOption.workflow, - expect.anything() + expect(useWorkflowService().closeWorkflows).toHaveBeenCalledWith( + [workflowOption.workflow], + expect.objectContaining({ initiator: 'user' }) ) }) }) diff --git a/src/components/topbar/WorkflowTab.vue b/src/components/topbar/WorkflowTab.vue index 7fd9b36531c..56dc59e985a 100644 --- a/src/components/topbar/WorkflowTab.vue +++ b/src/components/topbar/WorkflowTab.vue @@ -47,8 +47,14 @@ ) " > + = { const tabActivity = useWorkflowTabActivityStore() -const isAgentEditing = computed( - () => tabActivity.editingTabPath === workflowOption.workflow.path +const isAgentAwaitingApproval = computed(() => + tabActivity.awaitingApprovalPaths.has(workflowOption.workflow.path) +) + +const isAgentEditing = computed(() => + tabActivity.editingPaths.has(workflowOption.workflow.path) ) // The active tab doesn't badge its own status - the user is already looking @@ -272,6 +282,7 @@ const workflowStatusLabel = computed(() => const hasStatusIndicator = computed( () => + isAgentAwaitingApproval.value || isAgentEditing.value || showUnseenAgentDot.value || workflowStatus.value !== undefined || @@ -282,6 +293,10 @@ const revealsCloseOnHover = computed( () => isActiveTab.value || !compact || !hasStatusIndicator.value ) +const closeButtonVisibility = computed(() => + isActiveTab.value && !hasStatusIndicator.value ? 'visible' : 'invisible' +) + const thumbnailUrl = computed(() => { return workflowThumbnail.getThumbnail(workflowOption.workflow.key) }) @@ -299,23 +314,12 @@ const handleClick = (event: Event) => { popoverRef.value?.togglePopover(event) } -const closeWorkflows = async (options: WorkflowOption[]) => { - for (const opt of options) { - if ( - !(await useWorkflowService().closeWorkflow(opt.workflow, { - warnIfUnsaved: !workspaceStore.shiftDown, - hint: t('sideToolbar.workflowTab.dirtyCloseHint') - })) - ) { - // User cancelled, or the replacement load failed - break - } - } -} - -const onCloseWorkflow = async (option: WorkflowOption) => { - await closeWorkflows([option]) -} +const onCloseWorkflow = (option: WorkflowOption) => + useWorkflowService().closeWorkflows([option.workflow], { + warnIfUnsaved: !workspaceStore.shiftDown, + hint: t('sideToolbar.workflowTab.dirtyCloseHint'), + initiator: 'user' + }) const commandStore = useCommandStore() const workflow = computed(() => workflowOption.workflow) diff --git a/src/components/topbar/WorkflowTabs.test.ts b/src/components/topbar/WorkflowTabs.test.ts index 0ad7eb5b45b..7431a52a32c 100644 --- a/src/components/topbar/WorkflowTabs.test.ts +++ b/src/components/topbar/WorkflowTabs.test.ts @@ -120,12 +120,20 @@ vi.mock(import('./WorkflowTab.vue'), () => ({ required: true } }, + emits: ['closeOthers'], render() { - return h( - TabsTrigger, - { value: this.workflowOption.workflow.path }, - () => this.workflowOption.workflow.filename - ) + return [ + h( + TabsTrigger, + { value: this.workflowOption.workflow.path }, + () => this.workflowOption.workflow.filename + ), + h( + 'button', + { type: 'button', onClick: () => this.$emit('closeOthers') }, + `Close tabs other than ${this.workflowOption.workflow.filename}` + ) + ] } }) })) @@ -560,7 +568,10 @@ describe('WorkflowTabs selection and overflow', () => { expect(useWorkflowService().openWorkflow).toHaveBeenCalledOnce() expect(useWorkflowService().openWorkflow).toHaveBeenCalledWith( - firstWorkflow + firstWorkflow, + { + initiator: 'user' + } ) expect(screen.getByRole('tab', { name: 'First workflow' })).toHaveAttribute( 'aria-selected', @@ -575,7 +586,10 @@ describe('WorkflowTabs selection and overflow', () => { expect(useWorkflowService().openWorkflow).toHaveBeenCalledOnce() expect(useWorkflowService().openWorkflow).toHaveBeenCalledWith( - secondWorkflow + secondWorkflow, + { + initiator: 'user' + } ) }) @@ -588,7 +602,10 @@ describe('WorkflowTabs selection and overflow', () => { expect(useWorkflowService().openWorkflow).toHaveBeenCalledOnce() expect(useWorkflowService().openWorkflow).toHaveBeenCalledWith( - secondWorkflow + secondWorkflow, + { + initiator: 'user' + } ) }) @@ -601,8 +618,31 @@ describe('WorkflowTabs selection and overflow', () => { expect(useWorkflowService().openWorkflow).toHaveBeenCalledOnce() expect(useWorkflowService().openWorkflow).toHaveBeenCalledWith( - firstWorkflow + firstWorkflow, + { + initiator: 'user' + } + ) + }) + + it('closes the other tabs as one user action', async () => { + const thirdWorkflow = await useWorkflowStore() + .createTemporary('Third workflow.json') + .load() + useWorkflowStore().attachWorkflow(thirdWorkflow, 2) + const { user } = renderComponent() + + await user.click( + screen.getByRole('button', { + name: 'Close tabs other than Second workflow' + }) + ) + + expect(useWorkflowService().closeWorkflows).toHaveBeenCalledExactlyOnceWith( + [thirdWorkflow, firstWorkflow], + { warnIfUnsaved: true, initiator: 'user' } ) + expect(useWorkflowService().closeWorkflow).not.toHaveBeenCalled() }) it('keeps the real workflow selected when another workflow fails to load', async () => { diff --git a/src/components/topbar/WorkflowTabs.vue b/src/components/topbar/WorkflowTabs.vue index f0910ff4dc5..030b94ccfb3 100644 --- a/src/components/topbar/WorkflowTabs.vue +++ b/src/components/topbar/WorkflowTabs.vue @@ -223,21 +223,14 @@ const options = computed(() => async function openWorkflowByPath(path: string | number) { const option = options.value.find(({ value }) => value === path) if (!option) return - await workflowService.openWorkflow(option.workflow) + await workflowService.openWorkflow(option.workflow, { initiator: 'user' }) } -const closeWorkflows = async (options: WorkflowOption[]) => { - for (const opt of options) { - if ( - !(await workflowService.closeWorkflow(opt.workflow, { - warnIfUnsaved: !workspaceStore.shiftDown - })) - ) { - // User cancelled, or the replacement load failed - break - } - } -} +const closeWorkflows = (options: WorkflowOption[]) => + workflowService.closeWorkflows( + options.map(({ workflow }) => workflow), + { warnIfUnsaved: !workspaceStore.shiftDown, initiator: 'user' } + ) const onCloseWorkflow = async (option: WorkflowOption) => { await closeWorkflows([option]) diff --git a/src/composables/useCoreCommands.ts b/src/composables/useCoreCommands.ts index af26eb96f26..8ea01520c1b 100644 --- a/src/composables/useCoreCommands.ts +++ b/src/composables/useCoreCommands.ts @@ -640,7 +640,7 @@ export function useCoreCommands(): ComfyCommand[] { label: 'Next Opened Workflow', versionAdded: '1.3.9', function: async () => { - await workflowService.loadNextOpenedWorkflow() + await workflowService.loadNextOpenedWorkflow({ initiator: 'user' }) } }, { @@ -649,7 +649,7 @@ export function useCoreCommands(): ComfyCommand[] { label: 'Previous Opened Workflow', versionAdded: '1.3.9', function: async () => { - await workflowService.loadPreviousOpenedWorkflow() + await workflowService.loadPreviousOpenedWorkflow({ initiator: 'user' }) } }, { @@ -877,7 +877,10 @@ export function useCoreCommands(): ComfyCommand[] { versionAdded: '1.7.3', function: async () => { if (workflowStore.activeWorkflow) - await workflowService.closeWorkflow(workflowStore.activeWorkflow) + await workflowService.closeWorkflows([workflowStore.activeWorkflow], { + warnIfUnsaved: true, + initiator: 'user' + }) } }, { diff --git a/src/composables/useWorkflowActionsMenu.test.ts b/src/composables/useWorkflowActionsMenu.test.ts index fed326e82b7..57ae36c3191 100644 --- a/src/composables/useWorkflowActionsMenu.test.ts +++ b/src/composables/useWorkflowActionsMenu.test.ts @@ -441,7 +441,8 @@ describe('useWorkflowActionsMenu', () => { await findItem(menuItems.value, 'g.rename').command?.() expect(useWorkflowService().openWorkflow).toHaveBeenCalledWith( - customWorkflow.value + customWorkflow.value, + { initiator: 'user' } ) expect(startRename).toHaveBeenCalled() }) @@ -468,7 +469,8 @@ describe('useWorkflowActionsMenu', () => { ).command?.() expect(useWorkflowService().openWorkflow).toHaveBeenCalledWith( - customWorkflow.value + customWorkflow.value, + { initiator: 'user' } ) expect( lazyDeployToComfyApiDialog.openDeployToComfyApiDialog diff --git a/src/composables/useWorkflowActionsMenu.ts b/src/composables/useWorkflowActionsMenu.ts index 79ed1c8dfbf..1558032238b 100644 --- a/src/composables/useWorkflowActionsMenu.ts +++ b/src/composables/useWorkflowActionsMenu.ts @@ -66,10 +66,9 @@ export function useWorkflowActionsMenu( () => workflow?.value ?? workflowStore.activeWorkflow ) - /** Switch to the target workflow tab if it's not already active */ const ensureWorkflowActive = async (wf: ComfyWorkflow | null) => { if (!wf || wf === workflowStore.activeWorkflow) return true - return await workflowService.openWorkflow(wf) + return await workflowService.openWorkflow(wf, { initiator: 'user' }) } const menuItems = computed(() => { diff --git a/src/extensions/core/agentPanel.historyIdentity.test.ts b/src/extensions/core/agentPanel.historyIdentity.test.ts index 8553c3c2d6c..73266d3486a 100644 --- a/src/extensions/core/agentPanel.historyIdentity.test.ts +++ b/src/extensions/core/agentPanel.historyIdentity.test.ts @@ -142,7 +142,11 @@ describe('AgentPanel history during account transitions', () => { const resetSocket = vi.spyOn(api, 'resetSocket') const history = useAgentChatHistoryStore() const onFailure = vi.fn() - let refreshPromise: Promise | undefined + let refreshPromise: + | ReturnType< + ReturnType['refreshHistory'] + > + | undefined let secondPageSignal: AbortSignal | null | undefined let resolveSecondPage!: (response: Response) => void const secondPage = new Promise((resolve) => { diff --git a/src/locales/en/main.json b/src/locales/en/main.json index b24a52af229..18f6c5df414 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -299,6 +299,7 @@ "cancelled": "Cancelled", "agentWorking": "Agent is working on this workflow", "agentModified": "Agent updated this workflow", + "agentNeedsApproval": "Agent needs your approval", "job": "Job", "asset": "{count} asset | {count} assets", "untitled": "Untitled", @@ -5802,6 +5803,10 @@ "showTarget": "Show target", "targetWorkflowUnavailable": "The target workflow is no longer available.", "targetWorkflowOpenFailed": "Couldn’t open the target workflow.", + "openingWorkflowChat": "Opening chat for {workflowName}…", + "openingChat": "Opening chat…", + "followedChatOpenFailed": "Couldn’t open the chat for {workflowName}.", + "retryFollowedChat": "Retry opening the chat for {workflowName}", "showTargetWorkflow": "Show target workflow: {workflowName}", "runApproval": { "lead": "This tool wants to run the workflow:", diff --git a/src/platform/workflow/core/services/__mocks__/workflowService.ts b/src/platform/workflow/core/services/__mocks__/workflowService.ts index 8ccfd612918..3829186149f 100644 --- a/src/platform/workflow/core/services/__mocks__/workflowService.ts +++ b/src/platform/workflow/core/services/__mocks__/workflowService.ts @@ -11,6 +11,7 @@ const workflowService: ReturnType = { reloadCurrentWorkflow: vi.fn(async () => {}), openWorkflow: vi.fn(async () => true), closeWorkflow: vi.fn(async () => true), + closeWorkflows: vi.fn(async () => {}), renameWorkflow: vi.fn(async () => {}), deleteWorkflow: vi.fn(async () => true), insertWorkflow: vi.fn(async () => {}), diff --git a/src/platform/workflow/core/services/workflowService.test.ts b/src/platform/workflow/core/services/workflowService.test.ts index e9d397257bc..d0c07dd55b1 100644 --- a/src/platform/workflow/core/services/workflowService.test.ts +++ b/src/platform/workflow/core/services/workflowService.test.ts @@ -1872,6 +1872,183 @@ describe('useWorkflowService', () => { }) }) + describe('user activations', () => { + function activateOnLoad(): void { + vi.mocked(app.loadGraphData).mockImplementation( + async (_data, _clean, _restore, workflow) => { + useWorkflowStore().activeWorkflow = workflow as LoadedComfyWorkflow + return true + } + ) + } + + it('reports a tab only when a user action activates it', async () => { + const workflowStore = useWorkflowStore() + const restored = createWorkflow(null, { + loadable: true, + path: 'workflows/restored.json' + }) + const clicked = createWorkflow(null, { + loadable: true, + path: 'workflows/clicked.json' + }) + activateOnLoad() + const activated = vi.fn() + workflowStore.onUserActivation(activated) + const service = useWorkflowService() + + await service.openWorkflow(restored) + await service.openWorkflow(clicked, { initiator: 'user' }) + + expect(workflowStore.activeWorkflow?.path).toBe(clicked.path) + expect(activated.mock.calls).toEqual([[clicked]]) + }) + + it('does not report a user activation whose load fails', async () => { + const workflowStore = useWorkflowStore() + const clicked = createWorkflow(null, { + loadable: true, + path: 'workflows/clicked.json' + }) + vi.mocked(app.loadGraphData).mockResolvedValueOnce(false) + const activated = vi.fn() + workflowStore.onUserActivation(activated) + + await expect( + useWorkflowService().openWorkflow(clicked, { initiator: 'user' }) + ).resolves.toBe(false) + + expect(activated).not.toHaveBeenCalled() + }) + + function openThreeTabs(): { + byName: (name: string) => ComfyWorkflow + activated: ReturnType + } { + const workflowStore = useWorkflowStore() + const names = ['first', 'second', 'third'] + const tabs = names.map((name, index) => { + const tab = createWorkflow(null, { + loadable: true, + path: `workflows/${name}.json` + }) + Object.defineProperty(tab, 'unload', { value: vi.fn() }) + workflowStore.attachWorkflow(tab, index) + return tab + }) + workflowStore.activeWorkflow = tabs[0] as LoadedComfyWorkflow + vi.spyOn(workflowStore, 'getMostRecentWorkflow').mockImplementation( + () => + workflowStore.openWorkflows.find( + (tab) => !workflowStore.isActive(tab) + ) ?? null + ) + activateOnLoad() + const activated = vi.fn() + workflowStore.onUserActivation(activated) + return { byName: (name) => tabs[names.indexOf(name)], activated } + } + + it.for([ + { closed: 'the active tab', closing: ['first'], left: 'second' }, + { + closed: 'several tabs', + closing: ['first', 'second'], + left: 'third' + } + ])( + 'reports once, for the tab left active, when a user closes $closed', + async ({ closing, left }) => { + const { byName, activated } = openThreeTabs() + + await useWorkflowService().closeWorkflows(closing.map(byName), { + warnIfUnsaved: false, + initiator: 'user' + }) + + expect(useWorkflowStore().activeWorkflow?.path).toBe(byName(left).path) + expect(activated.mock.calls).toEqual([[byName(left)]]) + } + ) + + it('does not report a tab something else activated while a close waited', async () => { + const { byName, activated } = openThreeTabs() + const dirty = byName('second') + Object.assign(dirty, { isModified: true }) + let answer!: (choice: boolean | null) => void + vi.mocked(useDialogService().confirm).mockReturnValueOnce( + new Promise((resolve) => (answer = resolve)) + ) + const closing = useWorkflowService().closeWorkflows([dirty], { + warnIfUnsaved: true, + initiator: 'user' + }) + await vi.waitFor(() => + expect(useDialogService().confirm).toHaveBeenCalled() + ) + + await useWorkflowService().openWorkflow(byName('third')) + answer(false) + await closing + + expect(useWorkflowStore().activeWorkflow?.path).toBe(byName('third').path) + expect(activated).not.toHaveBeenCalled() + }) + + it('does not report a replacement superseded while a later close waits', async () => { + const { byName, activated } = openThreeTabs() + const workflowStore = useWorkflowStore() + const third = byName('third') + Object.assign(third, { isModified: true }) + let answer!: (choice: boolean | null) => void + vi.mocked(useDialogService().confirm).mockReturnValueOnce( + new Promise((resolve) => (answer = resolve)) + ) + const service = useWorkflowService() + const closing = service.closeWorkflows([byName('first'), third], { + warnIfUnsaved: true, + initiator: 'user' + }) + await vi.waitFor(() => + expect(useDialogService().confirm).toHaveBeenCalled() + ) + expect(workflowStore.activeWorkflow?.path).toBe(byName('second').path) + expect(workflowStore.openWorkflows.map((tab) => tab.path)).toEqual([ + byName('second').path, + third.path + ]) + + await service.openWorkflow(third) + answer(null) + await closing + + expect(workflowStore.activeWorkflow?.path).toBe(third.path) + expect(activated).not.toHaveBeenCalled() + }) + + it('reports the tab an earlier close activated when a later close throws', async () => { + const { byName, activated } = openThreeTabs() + const failure = new Error('load failed') + vi.mocked(app.loadGraphData).mockImplementation( + async (_data, _clean, _restore, workflow) => { + const loading = workflow as ComfyWorkflow + if (loading.path === byName('third').path) throw failure + useWorkflowStore().activeWorkflow = loading as LoadedComfyWorkflow + return true + } + ) + + await expect( + useWorkflowService().closeWorkflows( + [byName('first'), byName('second')], + { warnIfUnsaved: false, initiator: 'user' } + ) + ).rejects.toBe(failure) + + expect(activated.mock.calls).toEqual([[byName('second')]]) + }) + }) + describe('openWorkflow deferred warnings', () => { let workflowStore: ReturnType diff --git a/src/platform/workflow/core/services/workflowService.ts b/src/platform/workflow/core/services/workflowService.ts index d128b9cfadc..9fdf13b8ef1 100644 --- a/src/platform/workflow/core/services/workflowService.ts +++ b/src/platform/workflow/core/services/workflowService.ts @@ -437,6 +437,7 @@ export const useWorkflowService = () => { force?: boolean navigationIntentId?: number isCurrent?: () => boolean + initiator?: 'user' } = {} ): Promise => { if (options.isCurrent?.() === false) return Promise.resolve(false) @@ -491,6 +492,8 @@ export const useWorkflowService = () => { showPendingWarnings(undefined, { silent: !loadFromRemote && !options.force }) + if (options.initiator === 'user') + workflowStore.reportUserActivation(workflow) return true } catch (error) { useSubgraphNavigationStore().endWorkflowNavigation(navigationIntentId) @@ -508,7 +511,11 @@ export const useWorkflowService = () => { */ const closeWorkflow = async ( workflow: ComfyWorkflow, - options: { warnIfUnsaved: boolean; hint?: string } = { + options: { + warnIfUnsaved: boolean + hint?: string + onReplacementOpened?: (workflow: ComfyWorkflow) => void + } = { warnIfUnsaved: true } ): Promise => { @@ -521,7 +528,6 @@ export const useWorkflowService = () => { hint: options.hint, denyLabel: t('sideToolbar.workflowTab.dirtyCloseAnyway') }) - // Cancel if (confirmed === null) return false if (confirmed) { @@ -530,7 +536,6 @@ export const useWorkflowService = () => { } } - // Captured once: a mid-close rename mutates workflow.path in place. const closingPath = workflow.path const closing = closingKey(workflow) closingWorkflowCounts.set( @@ -545,8 +550,6 @@ export const useWorkflowService = () => { wasActive || (pendingWorkflowLoad && workflowStore.isActive(workflow)) ) { - // Bounded drain: quiesce for the replacement decision without letting - // a hot enqueue stream starve the close. for (let spins = 0; spins < 16; spins++) { const observedOpenTail = workflowLoadTail await observedOpenTail @@ -554,7 +557,6 @@ export const useWorkflowService = () => { } } - // If this is the active workflow, load the most recent workflow from history if (workflowStore.isActive(workflow)) { const mostRecentWorkflow = workflowStore.getMostRecentWorkflow() let replacementWorkflow = @@ -572,16 +574,13 @@ export const useWorkflowService = () => { replacementWorkflow = candidate } } - // `=== false` on purpose: only an EXPLICIT failure report aborts - // the close (a real configure failure resolves false - the dialog - // path); a rejection still propagates as before. if (replacementWorkflow) { if (!(await openWorkflow(replacementWorkflow))) return false + options.onReplacementOpened?.(replacementWorkflow) } else { if ((await loadDefaultWorkflow()) === false) return false } } else if ( - // Read live, post-drain: the awaits above can change the answer. workflowStore.openWorkflows.length > 0 && workflowStore.openWorkflows.every((open) => closingWorkflowCounts.has(closingKey(open)) @@ -591,7 +590,6 @@ export const useWorkflowService = () => { } await workflowStore.closeWorkflow(workflow) - // Only after the close is real: a still-open tab keeps its draft. workflowDraftStore.removeDraft(closingPath) useNodeOutputStore().discardPreviewsForWorkflow(closingPath) return true @@ -873,17 +871,50 @@ export const useWorkflowService = () => { canvas._deserializeItems(items, options) } - const loadNextOpenedWorkflow = async () => { + /** Closes `workflows` in order, stopping at the first one that stays open. */ + const closeWorkflows = async ( + workflows: ComfyWorkflow[], + { + initiator, + ...options + }: { warnIfUnsaved: boolean; hint?: string; initiator?: 'user' } + ): Promise => { + const opened: { replacement?: ComfyWorkflow } = {} + const onReplacementOpened = (replacement: ComfyWorkflow) => { + opened.replacement = replacement + } + try { + for (const workflow of workflows) + if ( + !(await closeWorkflow(workflow, { ...options, onReplacementOpened })) + ) + break + } finally { + const { replacement } = opened + if ( + initiator === 'user' && + replacement !== undefined && + workflowStore.isActive(replacement) + ) + workflowStore.reportUserActivation(replacement) + } + } + + const loadNextOpenedWorkflow = async ( + options: { initiator?: 'user' } = {} + ) => { const nextWorkflow = workflowStore.openedWorkflowIndexShift(1) if (nextWorkflow) { - await openWorkflow(nextWorkflow) + await openWorkflow(nextWorkflow, options) } } - const loadPreviousOpenedWorkflow = async () => { + const loadPreviousOpenedWorkflow = async ( + options: { initiator?: 'user' } = {} + ) => { const previousWorkflow = workflowStore.openedWorkflowIndexShift(-1) if (previousWorkflow) { - await openWorkflow(previousWorkflow) + await openWorkflow(previousWorkflow, options) } } @@ -962,6 +993,7 @@ export const useWorkflowService = () => { reloadCurrentWorkflow, openWorkflow, closeWorkflow, + closeWorkflows, renameWorkflow, deleteWorkflow, insertWorkflow, diff --git a/src/platform/workflow/management/stores/workflowStore.ts b/src/platform/workflow/management/stores/workflowStore.ts index f7dce746ee2..59d6e07555f 100644 --- a/src/platform/workflow/management/stores/workflowStore.ts +++ b/src/platform/workflow/management/stores/workflowStore.ts @@ -482,6 +482,7 @@ export const useWorkflowStore = defineStore('workflow', () => { /** A filesystem operation is currently in progress (e.g. save, rename, delete) */ const isBusy = ref(false) const workflowRenamed = createEventHook() + const userActivation = createEventHook() const { moveWorkflowThumbnail, clearThumbnail } = useWorkflowThumbnail() const renameWorkflow = async (workflow: ComfyWorkflow, newPath: string) => { @@ -733,6 +734,9 @@ export const useWorkflowStore = defineStore('workflow', () => { createNewTemporary, renameWorkflow, onWorkflowRenamed: workflowRenamed.on, + onUserActivation: userActivation.on, + reportUserActivation: (workflow: ComfyWorkflow) => + void userActivation.trigger(workflow), deleteWorkflow, saveAs, saveWorkflow, diff --git a/src/renderer/extensions/linearMode/MobileDisplay.vue b/src/renderer/extensions/linearMode/MobileDisplay.vue index 3b272b87634..c353ca61985 100644 --- a/src/renderer/extensions/linearMode/MobileDisplay.vue +++ b/src/renderer/extensions/linearMode/MobileDisplay.vue @@ -89,7 +89,8 @@ const activeWorkflowPath = computed({ get: () => workflowStore.activeWorkflow?.path ?? '', set: (path: string) => { const workflow = workflowStore.getWorkflowByPath(path) - if (workflow) void workflowService.openWorkflow(workflow) + if (workflow) + void workflowService.openWorkflow(workflow, { initiator: 'user' }) } }) diff --git a/src/stores/subgraphNavigationStore.navigateToHash.test.ts b/src/stores/subgraphNavigationStore.navigateToHash.test.ts index 13ed17a35de..6f1e3281b5b 100644 --- a/src/stores/subgraphNavigationStore.navigateToHash.test.ts +++ b/src/stores/subgraphNavigationStore.navigateToHash.test.ts @@ -489,6 +489,22 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { expect(useWorkflowStore().activeSubgraph).toBe(subgraph) }) + it('opens the workflow of a restored page hash without calling it a user change', async () => { + const workflow = fromPartial({ + path: 'restored-workflow.json', + activeState: { id: ids.deletedSubgraph, definitions: { subgraphs: [] } } + }) + Object.assign(useWorkflowStore(), { openWorkflows: [workflow] }) + routeHashRef.value = `#${ids.deletedSubgraph}` + + await useSubgraphNavigationStore().updateHash() + + expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledExactlyOnceWith( + workflow, + { navigationIntentId: expect.any(Number) } + ) + }) + it('uses the emitted graph during a synchronous graph-change event', async () => { const subgraph = makeSubgraph(ids.validSubgraph) const navigationStore = useSubgraphNavigationStore() @@ -543,7 +559,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { }) expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledWith( targetWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) }) @@ -598,7 +614,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { expect(routeHashRef.value).toBe(`#${targetSubgraph.id}`) expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledWith( originalWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) }) @@ -696,7 +712,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { await vi.waitFor(() => expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledWith( routeWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) ) resolveFirstPush?.() @@ -748,7 +764,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { await vi.waitFor(() => expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledWith( firstWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) ) app.canvas.graph = secondRoot @@ -798,7 +814,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { await vi.waitFor(() => expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledWith( firstWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) ) routeHashRef.value = `#${secondId}` @@ -807,7 +823,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { await vi.waitFor(() => { expect(workflowServiceMocks.openWorkflow).toHaveBeenLastCalledWith( secondWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) expect(app.canvas.graph?.id).toBe(secondId) }) @@ -848,7 +864,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { await vi.waitFor(() => expect(workflowServiceMocks.openWorkflow).toHaveBeenCalledWith( firstWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) ) routeHashRef.value = `#${secondId}` @@ -860,7 +876,7 @@ describe('useSubgraphNavigationStore - navigateToHash validation', () => { await vi.waitFor(() => { expect(workflowServiceMocks.openWorkflow).toHaveBeenLastCalledWith( secondWorkflow, - { navigationIntentId: expect.any(Number) } + { navigationIntentId: expect.any(Number), initiator: 'user' } ) expect(app.canvas.graph?.id).toBe(secondId) }) diff --git a/src/stores/subgraphNavigationStore.ts b/src/stores/subgraphNavigationStore.ts index 88276a0221a..8d3ee8dfbb6 100644 --- a/src/stores/subgraphNavigationStore.ts +++ b/src/stores/subgraphNavigationStore.ts @@ -25,7 +25,7 @@ import { isNonNullish, isSubgraph } from '@/utils/typeGuardUtil' interface WorkflowServiceAccess { openWorkflow( workflow: ComfyWorkflow, - options: { navigationIntentId?: number } + options: { navigationIntentId?: number; initiator?: 'user' } ): Promise } @@ -232,7 +232,7 @@ export const useSubgraphNavigationStore = defineStore( type GraphNavigationIntent = { id: number hash: string - source: 'graph' | 'route' + source: 'graph' | 'route' | 'restore' } type NavigationIntent = | GraphNavigationIntent @@ -313,7 +313,11 @@ export const useSubgraphNavigationStore = defineStore( } } - async function navigateToHash(newHash: string, navigationId: number) { + async function navigateToHash( + newHash: string, + navigationId: number, + initiator?: 'user' + ) { const root = useApp().rootGraph const locatorId = newHash.slice(1) || root.id const canvas = canvasStore.getCanvas() @@ -331,22 +335,18 @@ export const useSubgraphNavigationStore = defineStore( }, newHash) } - //Search all open workflows for (const workflow of workflowStore.openWorkflows) { const { activeState } = workflow if (!activeState) continue const subgraphs = activeState.definitions?.subgraphs ?? [] for (const graph of [activeState, ...subgraphs]) { if (graph.id !== locatorId) continue - // This will trigger a navigation, which can break forward history. - // After openWorkflow resolves, app.rootGraph has been swapped, so we - // intentionally re-read app.rootGraph below instead of using the - // `root` captured at function entry. try { await withNavBlocked( () => useWorkflowService().openWorkflow(workflow, { - navigationIntentId: navigationId + navigationIntentId: navigationId, + initiator }), newHash ) @@ -435,7 +435,11 @@ export const useSubgraphNavigationStore = defineStore( } async function applyNavigationIntent(intent: GraphNavigationIntent) { - await navigateToHash(intent.hash, intent.id) + await navigateToHash( + intent.hash, + intent.id, + intent.source === 'route' ? 'user' : undefined + ) if (blockNavDepth > 0) return const deferredIntent = deferredNavigationIntent @@ -527,7 +531,7 @@ export const useSubgraphNavigationStore = defineStore( initialLoad = false if (!routeHash.value) return Promise.resolve() return applyNavigationIntent( - createNavigationIntent(routeHash.value, 'route') + createNavigationIntent(routeHash.value, 'restore') ).then(() => { const activeGraph = canvasStore.getCanvas().graph if (isSubgraph(activeGraph)) { diff --git a/src/stores/workflowTabActivityStore.test.ts b/src/stores/workflowTabActivityStore.test.ts index e05180af13c..e05cfd37d3c 100644 --- a/src/stores/workflowTabActivityStore.test.ts +++ b/src/stores/workflowTabActivityStore.test.ts @@ -3,14 +3,23 @@ import { describe, expect, it } from 'vitest' import { useWorkflowTabActivityStore } from './workflowTabActivityStore' describe('useWorkflowTabActivityStore', () => { - it('tracks and clears the tab being edited', () => { + it('spins every tab with a running turn and marks the ones awaiting approval', () => { const store = useWorkflowTabActivityStore() - store.setEditing('workflows/a.json') - expect(store.editingTabPath).toBe('workflows/a.json') + store.setAgentTurnTabs([ + { path: 'workflows/a.json', awaitingApproval: true }, + { path: 'workflows/b.json', awaitingApproval: false } + ]) - store.setEditing(null) - expect(store.editingTabPath).toBeNull() + expect([...store.editingPaths]).toEqual([ + 'workflows/a.json', + 'workflows/b.json' + ]) + expect([...store.awaitingApprovalPaths]).toEqual(['workflows/a.json']) + + store.setAgentTurnTabs([]) + expect(store.editingPaths.size).toBe(0) + expect(store.awaitingApprovalPaths.size).toBe(0) }) it('toggles the tab-creation flag', () => { @@ -38,25 +47,14 @@ describe('useWorkflowTabActivityStore', () => { expect(store.unseenModifiedPaths.size).toBe(1) }) - it('prunes state for tabs that are no longer open', () => { + it('prunes unseen dots for tabs that are no longer open', () => { const store = useWorkflowTabActivityStore() - store.setEditing('workflows/closed.json') store.markModified('workflows/closed.json') store.markModified('workflows/open.json') store.pruneClosed(['workflows/open.json']) - expect(store.editingTabPath).toBeNull() expect(store.unseenModifiedPaths.has('workflows/closed.json')).toBe(false) expect(store.unseenModifiedPaths.has('workflows/open.json')).toBe(true) }) - - it('keeps the editing path when its tab stays open', () => { - const store = useWorkflowTabActivityStore() - store.setEditing('workflows/open.json') - - store.pruneClosed(['workflows/open.json']) - - expect(store.editingTabPath).toBe('workflows/open.json') - }) }) diff --git a/src/stores/workflowTabActivityStore.ts b/src/stores/workflowTabActivityStore.ts index 45a1703b6f4..2b07a529d3d 100644 --- a/src/stores/workflowTabActivityStore.ts +++ b/src/stores/workflowTabActivityStore.ts @@ -1,5 +1,10 @@ import { defineStore } from 'pinia' -import { ref } from 'vue' +import { computed, ref, shallowRef } from 'vue' + +export interface AgentTurnTab { + path: string + awaitingApproval: boolean +} /** * Cross-feature workflow-tab activity, keyed by tab path. Feature extensions @@ -9,11 +14,24 @@ import { ref } from 'vue' export const useWorkflowTabActivityStore = defineStore( 'workflowTabActivity', () => { - const editingTabPath = ref(null) + const agentTurnTabs = shallowRef([]) const creatingTab = ref(false) const unseenModifiedPaths = ref>(new Set()) - function setEditing(path: string | null): void { - editingTabPath.value = path + + const editingPaths = computed( + () => new Set(agentTurnTabs.value.map(({ path }) => path)) + ) + const awaitingApprovalPaths = computed( + () => + new Set( + agentTurnTabs.value.flatMap(({ path, awaitingApproval }) => + awaitingApproval ? [path] : [] + ) + ) + ) + + function setAgentTurnTabs(tabs: readonly AgentTurnTab[]): void { + agentTurnTabs.value = tabs } function setCreating(creating: boolean): void { @@ -30,23 +48,22 @@ export const useWorkflowTabActivityStore = defineStore( function pruneClosed(openPaths: string[]): void { const open = new Set(openPaths) - if (editingTabPath.value !== null && !open.has(editingTabPath.value)) - editingTabPath.value = null for (const path of unseenModifiedPaths.value) if (!open.has(path)) unseenModifiedPaths.value.delete(path) } function clearAgentActivity(): void { - editingTabPath.value = null + agentTurnTabs.value = [] creatingTab.value = false unseenModifiedPaths.value.clear() } return { - editingTabPath, + editingPaths, + awaitingApprovalPaths, creatingTab, unseenModifiedPaths, - setEditing, + setAgentTurnTabs, setCreating, markModified, markSeen, diff --git a/src/workbench/extensions/agent/AgentPanelRoot.tabActivity.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.tabActivity.test.ts new file mode 100644 index 00000000000..13602c96eec --- /dev/null +++ b/src/workbench/extensions/agent/AgentPanelRoot.tabActivity.test.ts @@ -0,0 +1,765 @@ +import { fetchRequests, respondToFetch } from '@comfyorg/test-utils/fetch' +import { fromPartial } from '@total-typescript/shoehorn' + +import type { + AgentThreadListResponse, + AgentThreadSummary +} from '@comfyorg/ingest-types' +import type { User } from 'firebase/auth' +import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { computed, nextTick, ref } from 'vue' + +vi.mock(import('firebase/auth')) + +import { i18n } from '@/i18n' +import { useCurrentUser } from '@/composables/auth/useCurrentUser' +import { useBillingContext } from '@/composables/billing/useBillingContext' +import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' +import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' +import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore' +import type { LoadedComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore' +import type { ComfyWorkflowJSON } from '@/platform/workflow/validation/schemas/workflowSchema' +import { useBillingCapabilities } from '@/platform/workspace/composables/useBillingCapabilities' +import { useWorkspaceUI } from '@/platform/workspace/composables/useWorkspaceUI' +import { api } from '@/scripts/api' +import { useAuthStore } from '@/stores/authStore' +import { useWorkflowTabActivityStore } from '@/stores/workflowTabActivityStore' +import { getFilenameDetails } from '@/utils/formatUtil' +import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils' + +import AgentPanelRoot from './AgentPanelRoot.vue' +import { setupInlinePromptEditorDom } from './components/agent/composer/inlinePromptEditorTestSetup' +import { createFakeAgentSocket } from './crdt/__fixtures__/agentSocket' +import type { AgentMessages } from './schemas/agentApiSchema' +import { zAgentMessages } from './schemas/agentApiSchema' +import { createAgentEventSource } from './services/agent/agentEventSource' +import { resolveAgentIdentity } from './services/agent/agentIdentity' +import type { AgentIdentityState } from './services/agent/agentIdentity' +import { registerWorkflowTabActivityTracker } from './services/agent/workflowTabActivityTracker' +import { useAgentChatHistoryStore } from './stores/agent/agentChatHistoryStore' +import { useAgentConsentStore } from './stores/agent/agentConsentStore' +import { useAgentConversationStore } from './stores/agent/agentConversationStore' +import { useAgentPanelStore } from './stores/agent/agentPanelStore' +import { useAgentWorkflowTabBindingStore } from './stores/agent/agentWorkflowTabBindingStore' + +setupInlinePromptEditorDom() + +vi.mock(import('@/scripts/api')) + +vi.mock(import('@/scripts/app'), () => { + const graph = { + nodes: [], + _nodes: [], + _nodes_by_id: {}, + subgraphs: new Map(), + serialize: () => ({ version: 0.4, nodes: [] }) + } + return { + app: { + graph, + rootGraph: graph, + isGraphReady: false, + canvas: undefined, + ui: { autoQueueEnabled: false } + } + } +}) + +vi.mock(import('./composables/agent/useAgentConsent'), () => ({ + useAgentConsent: () => ({ + withConsent: async (_trigger: unknown, onAccept: () => void) => onAccept() + }) +})) +vi.mock(import('@/composables/canvas/useFocusNode'), () => ({ + useFocusNode: () => ({ focusNodeInstance: vi.fn() }) +})) +vi.mock( + import('@/platform/cloud/subscription/composables/useAccountPreconditionDialog'), + () => ({ useAccountPreconditionDialog: () => ({ open: vi.fn() }) }) +) +vi.mock(import('@/platform/distribution/types'), () => ({ isCloud: true })) +vi.mock(import('@/platform/telemetry')) +vi.mock(import('@/platform/telemetry/reportError')) +vi.mock(import('@/composables/auth/useCurrentUser')) +vi.mock(import('@/platform/workflow/core/services/workflowService')) +vi.mock(import('@/composables/billing/useBillingContext'), { spy: true }) +vi.mock(import('@/platform/workspace/composables/useBillingCapabilities'), { + spy: true +}) +vi.mock(import('@/platform/workspace/composables/useWorkspaceUI'), { + spy: true +}) +vi.mock(import('./services/agent/agentEventSource'), { spy: true }) +vi.mock(import('./services/agent/agentIdentity'), { spy: true }) + +const runningTab = 'workflows/current.json' +const otherTab = 'workflows/other.json' + +let agentSocket: ReturnType +let workflowStore: ReturnType +let stopTracker: () => void +let transcripts: Partial> = {} +let acks: { message_id: string; workflow_id?: string }[] = [] + +function json(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json' } + }) +} + +const threadMessagesUrl = /\/threads\/([^/]+)\/messages/ + +function threadTranscript(input: RequestInfo | URL): Response { + const [, thread = ''] = threadMessagesUrl.exec(String(input)) ?? [] + return json(200, transcripts[thread] ?? []) +} + +function agentThread(id: string, title: string): AgentThreadSummary { + return { + created_at: '2026-10-15T10:00:00Z', + id, + last_message_at: '2026-10-15T10:00:00Z', + message_count: 0, + preview: '', + status: 'active', + title, + updated_at: '2026-10-15T10:00:00Z', + workflow_id: '' + } +} + +const threadList = { + threads: [ + agentThread('th-1', 'Running chat'), + agentThread('th-2', 'Other chat') + ], + pagination: { has_more: false, limit: 2, offset: 0, total: 2 } +} satisfies AgentThreadListResponse + +function addTab( + path: string, + overrides: Partial = {} +): LoadedComfyWorkflow { + const slash = path.lastIndexOf('/') + const { filename, suffix } = getFilenameDetails(path.slice(slash + 1)) + const tab = createMockLoadedWorkflow({ + instanceId: path, + path, + directory: path.slice(0, slash), + filename, + suffix, + isTemporary: false, + isModified: false, + activeState: null, + ...overrides + }) + tab.load = vi.fn(async () => tab) + tab.unload = vi.fn() + tab.rename = vi.fn(async (newPath: string) => { + const renamed = getFilenameDetails( + newPath.slice(newPath.lastIndexOf('/') + 1) + ) + Object.assign(tab, { path: newPath, ...renamed }) + return tab + }) + workflowStore.attachWorkflow(tab, workflowStore.openWorkflows.length) + workflowStore.openWorkflowsInBackground({ right: [tab.path] }) + return tab +} + +function addBoundTab(path: string, workflowId: string): LoadedComfyWorkflow { + const tab = addTab(path, { + activeState: fromPartial({ id: workflowId }) + }) + useAgentWorkflowTabBindingStore().bind(workflowId, tab.path) + return tab +} + +function renderPanel() { + const active = workflowStore.activeWorkflow + useAgentPanelStore().setWorkflowTarget( + active ? fromPartial(active) : null + ) + return render(AgentPanelRoot, { global: { plugins: [i18n] } }) +} + +async function send(text: string): Promise { + await userEvent.click(screen.getByRole('textbox')) + await userEvent.paste(text) + await userEvent.click(screen.getByRole('button', { name: 'Send' })) + await screen.findByRole('button', { name: 'Stop' }) +} + +async function openChat(title: string, threadId: string): Promise { + await userEvent.click( + screen.getByRole('button', { name: i18n.global.t('agent.showChatHistory') }) + ) + await userEvent.click(await screen.findByRole('button', { name: title })) + await vi.waitFor(() => + expect(useAgentChatHistoryStore().activeId).toBe(threadId) + ) +} + +function emitRunApproval(): void { + agentSocket.receive('agent_ask', { + thread_id: 'th-1', + message_id: 'm-1', + ask_id: 'm-1:call-1', + kind: 'run_approval', + prompt: 'Run it?', + options: [ + { id: 'run', label: 'Run' }, + { id: 'cancel', label: 'Cancel' } + ], + min_selections: 1, + max_selections: 1, + allow_other: false + }) +} + +function emitDone(): void { + agentSocket.receive('agent_message_done', { + message_id: 'm-1', + thread_id: 'th-1' + }) +} + +function userRow(threadId: string, workflowId?: string) { + return { + id: `u-${threadId}`, + thread_id: threadId, + seq: 1, + role: 'user', + status: 'complete', + turn_id: `turn-${threadId}`, + content: { text: 'make it blue' }, + ...(workflowId === undefined ? {} : { workflow_id: workflowId }) + } +} + +function liveOtherThread(workflowId?: string): AgentMessages { + return zAgentMessages.parse([ + userRow('th-2', workflowId), + { + id: 'm-2', + thread_id: 'th-2', + seq: 2, + role: 'assistant', + status: 'streaming', + turn_id: 'turn-th-2', + content: { text: '' } + } + ]) +} + +function tabActivity() { + return useWorkflowTabActivityStore() +} + +beforeEach(() => { + vi.useRealTimers() + vi.mocked(api.fetchApi).mockImplementation((route, options) => + fetch(route.startsWith('/api') ? route : `/api${route}`, options) + ) + api.socket = fromPartial({ readyState: 1, send: vi.fn() }) + agentSocket = createFakeAgentSocket() + vi.mocked(createAgentEventSource).mockReturnValue(agentSocket.socket) + vi.mocked(resolveAgentIdentity).mockReturnValue({ + state: ref({ status: 'resolved', userId: 'account-a' }), + reset: vi.fn(), + stop: () => {} + }) + useAuthStore().currentUser = fromPartial({ uid: 'account-a' }) + vi.spyOn(useAuthStore(), 'getUserAuthHeader').mockResolvedValue({ + Authorization: 'Bearer id-token' + }) + localStorage.clear() + localStorage.setItem('Comfy.AgentPanel.onboarded', 'true') + transcripts = {} + acks = [] + useCurrentUser().isLoggedIn = computed(() => true) + useCurrentUser().resolvedUserInfo = computed(() => ({ id: 'account-a' })) + Object.assign(useAgentConsentStore(), { accepted: true }) + vi.mocked(useWorkspaceUI).mockReturnValue( + fromPartial({ workspaceRole: computed(() => 'owner' as const) }) + ) + vi.mocked(useBillingContext).mockReturnValue( + fromPartial({ + subscription: computed(() => + fromPartial({ hasFunds: true, agentHasFunds: true }) + ), + tier: computed(() => 'STANDARD' as const), + type: computed(() => 'legacy' as const), + billingStatus: computed(() => 'paid' as const), + canAccessSubscriptionFeatures: computed(() => true), + fetchStatus: vi.fn(async () => {}) + }) + ) + vi.mocked(useBillingCapabilities).mockReturnValue( + fromPartial({ + canTopUp: computed(() => true), + canSubscribeSelfServe: computed(() => true), + isReady: computed(() => true), + hasResolvedCapabilities: computed(() => true), + snapshotAuthoritative: computed(() => true) + }) + ) + workflowStore = useWorkflowStore() + vi.mocked(workflowStore.syncWorkflows).mockResolvedValue(undefined) + vi.mocked(useWorkflowService()).openWorkflow.mockImplementation( + async (tab, options) => { + workflowStore.activeWorkflow = await tab.load() + if (options?.initiator === 'user') workflowStore.reportUserActivation(tab) + return true + } + ) + vi.mocked(useWorkflowService()).closeWorkflow.mockImplementation( + async (tab) => { + await workflowStore.closeWorkflow(tab) + return true + } + ) + vi.mocked(fetch).mockImplementation(async () => json(200, {})) + respondToFetch(/\/assets/, () => + json(200, { assets: [], total: 0, has_more: false }) + ) + respondToFetch(/\/agent\/threads/, () => json(200, threadList)) + respondToFetch(threadMessagesUrl, threadTranscript) + respondToFetch({ method: 'POST', url: /\/messages/ }, () => + json(202, { + thread_id: 'th-1', + ...(acks.shift() ?? { message_id: 'm-1', workflow_id: 'wf-42' }) + }) + ) + respondToFetch(/\/asks\//, () => json(200, { status: 'answered' })) + workflowStore.activeWorkflow = addBoundTab(runningTab, 'wf-42') + stopTracker = registerWorkflowTabActivityTracker(ref(true)) +}) + +afterEach(() => { + stopTracker() +}) + +describe('AgentPanelRoot tab activity across chats', () => { + it('keeps A and B spinning independently after following their chats to C', async () => { + const other = addBoundTab(otherTab, 'wf-other') + const thirdTab = 'workflows/third.json' + const third = addBoundTab(thirdTab, 'wf-third') + respondToFetch(/\/workflows(?:\?|$)/, () => + json(200, { + data: [ + { id: 'wf-42', name: 'current' }, + { id: 'wf-other', name: 'other' }, + { id: 'wf-third', name: 'third' } + ], + pagination: { offset: 0, limit: 100, total: 3, has_more: false } + }) + ) + respondToFetch(/\/agent\/threads(?:\?|$)/, () => + json(200, { + ...threadList, + threads: [ + { ...agentThread('th-1', 'Running chat'), workflow_id: 'wf-42' }, + { ...agentThread('th-2', 'Other chat'), workflow_id: 'wf-other' }, + { ...agentThread('th-3', 'Third chat'), workflow_id: 'wf-third' } + ], + pagination: { has_more: false, limit: 3, offset: 0, total: 3 } + }) + ) + let answerOther!: () => void + const otherTranscript = new Promise((resolve) => { + answerOther = () => resolve(json(200, liveOtherThread('wf-42'))) + }) + respondToFetch('/api/agent/threads/th-2/messages', () => otherTranscript) + renderPanel() + await send('add an upscaler') + + await useWorkflowService().openWorkflow(other, { initiator: 'user' }) + + expect(screen.getByTestId('agent-panel-footer')).toHaveAttribute('inert') + expect( + await screen.findByRole('status', { name: 'Opening chat for other…' }) + ).toBeVisible() + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + expect(useAgentConversationStore().threadId).toBe('th-1') + + answerOther() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().activeId).toBe('th-2') + ) + + expect( + screen.queryByRole('status', { name: 'Opening chat for other…' }) + ).toBeNull() + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(otherTab) + expect([...tabActivity().editingPaths]).toEqual([otherTab, runningTab]) + expect([...tabActivity().unseenModifiedPaths]).toEqual([]) + + await useWorkflowService().openWorkflow(third, { initiator: 'user' }) + await vi.waitFor(() => + expect(useAgentChatHistoryStore().activeId).toBe('th-3') + ) + + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(thirdTab) + expect(useAgentConversationStore().threadId).toBe('th-3') + expect(tabActivity().editingPaths).toEqual(new Set([runningTab, otherTab])) + expect([...tabActivity().unseenModifiedPaths]).toEqual([]) + + emitDone() + await nextTick() + + expect([...tabActivity().editingPaths]).toEqual([otherTab]) + expect([...tabActivity().unseenModifiedPaths]).toEqual([runningTab]) + expect(useAgentConversationStore().threadId).toBe('th-3') + + agentSocket.receive('agent_message_done', { + message_id: 'm-2', + thread_id: 'th-2' + }) + await nextTick() + + expect([...tabActivity().editingPaths]).toEqual([]) + expect(tabActivity().unseenModifiedPaths).toEqual( + new Set([runningTab, otherTab]) + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(thirdTab) + expect(useAgentConversationStore().threadId).toBe('th-3') + }) + + it('keeps the spinner on the tab while its chat runs in the background', async () => { + renderPanel() + await send('add an upscaler') + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + + await openChat('Other chat', 'th-2') + + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + expect(tabActivity().unseenModifiedPaths.has(runningTab)).toBe(false) + }) + + it.for([ + { + chat: 'open', + selectChat: () => {}, + frame: 'done', + message: { message_id: 'm-1', thread_id: 'th-1' }, + modified: true + }, + { + chat: 'open', + selectChat: () => {}, + frame: 'malformed done', + message: { message_id: 'm-1' }, + modified: false + }, + { + chat: 'background', + selectChat: () => openChat('Other chat', 'th-2'), + frame: 'done', + message: { message_id: 'm-1', thread_id: 'th-1' }, + modified: true + }, + { + chat: 'background', + selectChat: () => openChat('Other chat', 'th-2'), + frame: 'malformed done', + message: { message_id: 'm-1' }, + modified: false + } + ])( + 'stops the spinner when the $chat chat gets a $frame frame', + async ({ selectChat, message, modified }) => { + renderPanel() + await send('add an upscaler') + await selectChat() + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + + agentSocket.receive('agent_message_done', message) + await nextTick() + + expect(tabActivity().editingPaths.size).toBe(0) + expect(tabActivity().unseenModifiedPaths.has(runningTab)).toBe(modified) + } + ) + + it('keeps the spinner on a reopened running chat until its turn ends', async () => { + renderPanel() + await send('add an upscaler') + await openChat('Other chat', 'th-2') + await openChat('Running chat', 'th-1') + expect(screen.getByRole('button', { name: 'Stop' })).toBeEnabled() + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + expect(tabActivity().unseenModifiedPaths.has(runningTab)).toBe(false) + + emitDone() + await nextTick() + + expect(tabActivity().editingPaths.size).toBe(0) + expect(tabActivity().unseenModifiedPaths.has(runningTab)).toBe(true) + }) + + it('keeps a background chat spinning across a panel remount and marks it when it completes', async () => { + const { unmount } = renderPanel() + await send('add an upscaler') + await openChat('Other chat', 'th-2') + + unmount() + renderPanel() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().activeId).toBe('th-2') + ) + + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + + emitDone() + await nextTick() + + expect(tabActivity().editingPaths.size).toBe(0) + expect(tabActivity().unseenModifiedPaths.has(runningTab)).toBe(true) + }) + + it('moves the tab of the chat that asked for it when the user switches chats mid-open', async () => { + addBoundTab(otherTab, 'wf-other') + transcripts['th-2'] = liveOtherThread() + renderPanel() + await send('add an upscaler') + let finishOpening!: () => void + vi.mocked(useWorkflowService()).openWorkflow.mockImplementationOnce( + (tab) => + new Promise((resolve) => { + finishOpening = () => { + workflowStore.activeWorkflow = tab as LoadedComfyWorkflow + resolve(true) + } + }) + ) + + agentSocket.receive('agent_active_tab', { + workflow_id: 'wf-other', + thread_id: 'th-1' + }) + await vi.waitFor(() => + expect(useWorkflowService().openWorkflow).toHaveBeenCalled() + ) + await openChat('Other chat', 'th-2') + finishOpening() + await vi.waitFor(() => + expect(useAgentWorkflowTabBindingStore().tabPathFor('wf-other')).toBe( + otherTab + ) + ) + await nextTick() + expect(tabActivity().editingPaths.has(otherTab)).toBe(true) + + emitDone() + await nextTick() + + expect(tabActivity().editingPaths.has(otherTab)).toBe(false) + expect(tabActivity().unseenModifiedPaths.has(otherTab)).toBe(true) + expect(tabActivity().unseenModifiedPaths.has(runningTab)).toBe(false) + }) + + it.for([ + { + asked: 'while the chat is open', + beforeAsk: () => {}, + afterAsk: () => {} + }, + { + asked: 'while the chat is in the background', + beforeAsk: () => openChat('Other chat', 'th-2'), + afterAsk: () => {} + }, + { + asked: 'and then the chat is stashed', + beforeAsk: () => {}, + afterAsk: () => openChat('Other chat', 'th-2') + } + ])( + 'marks the tab as needing approval when asked $asked', + async ({ beforeAsk, afterAsk }) => { + renderPanel() + await send('add an upscaler') + await beforeAsk() + expect(tabActivity().awaitingApprovalPaths.size).toBe(0) + + emitRunApproval() + await nextTick() + await afterAsk() + expect([...tabActivity().awaitingApprovalPaths]).toEqual([runningTab]) + + agentSocket.receive('agent_ask_resolved', { + thread_id: 'th-1', + message_id: 'm-1', + ask_id: 'm-1:call-1', + status: 'answered', + selected: ['run'] + }) + await nextTick() + + expect(tabActivity().awaitingApprovalPaths.size).toBe(0) + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + } + ) + + it('stops showing needs-approval once the user answers, before the server confirms', async () => { + renderPanel() + await send('add an upscaler') + emitRunApproval() + await nextTick() + expect([...tabActivity().awaitingApprovalPaths]).toEqual([runningTab]) + + await userEvent.click(await screen.findByRole('button', { name: 'Run' })) + await vi.waitFor(() => + expect(fetchRequests({ method: 'POST', url: /\/asks\// })).toHaveLength(1) + ) + await nextTick() + + expect(tabActivity().awaitingApprovalPaths.size).toBe(0) + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + + await openChat('Other chat', 'th-2') + + expect(tabActivity().awaitingApprovalPaths.size).toBe(0) + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + }) + + it('follows the tab when it is renamed mid-turn', async () => { + const tab = workflowStore.activeWorkflow! + renderPanel() + await send('add an upscaler') + + await workflowStore.renameWorkflow(tab, 'workflows/renamed.json') + await nextTick() + + expect([...tabActivity().editingPaths]).toEqual(['workflows/renamed.json']) + + emitDone() + await nextTick() + + expect(tabActivity().editingPaths.size).toBe(0) + expect( + tabActivity().unseenModifiedPaths.has('workflows/renamed.json') + ).toBe(true) + }) + + it('drops the spinner when the tab closes mid-turn, even for a new tab with the same name', async () => { + addTab(otherTab) + const tab = workflowStore.activeWorkflow! + renderPanel() + await send('add an upscaler') + + await workflowStore.closeWorkflow(tab) + await nextTick() + expect(tabActivity().editingPaths.size).toBe(0) + + addTab(runningTab, { instanceId: 'same-name-replacement' }) + await nextTick() + expect(tabActivity().editingPaths.size).toBe(0) + }) + + it.for([ + { workflow: 'wf-other', spinning: [otherTab] }, + { workflow: undefined, spinning: [] } + ])( + 'spins the tab of a running chat opened from history once its workflow ($workflow) is restored', + async ({ workflow, spinning }) => { + addBoundTab(otherTab, 'wf-other') + transcripts['th-2'] = liveOtherThread(workflow) + renderPanel() + + await openChat('Other chat', 'th-2') + await vi.waitFor(() => + expect(useAgentConversationStore().activeTurnId).toBe('m-2') + ) + await nextTick() + + await vi.waitFor(() => + expect([...tabActivity().editingPaths]).toEqual(spinning) + ) + } + ) + + it("keeps a guessed turn on its tab when a remount finds the chat's workflow already decided", async () => { + addBoundTab(otherTab, 'wf-other') + transcripts['th-1'] = zAgentMessages.parse([userRow('th-1', 'wf-other')]) + acks = [{ message_id: 'm-1' }] + const { unmount } = renderPanel() + await send('add an upscaler') + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + + unmount() + renderPanel() + await vi.waitFor(() => + expect(useAgentConversationStore().activeTurnId).toBe('m-1') + ) + await nextTick() + + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + }) + + it('moves the tab of the turn named by agent_active_tab, not the latest one', async () => { + addBoundTab(otherTab, 'wf-other') + acks = [ + { message_id: 'm-1', workflow_id: 'wf-42' }, + { message_id: 'm-2', workflow_id: 'wf-42' } + ] + renderPanel() + await send('first') + emitDone() + await screen.findByRole('button', { name: 'Send' }) + await send('second') + + agentSocket.receive('agent_active_tab', { + workflow_id: 'wf-other', + thread_id: 'th-1', + message_id: 'm-1' + }) + await vi.waitFor(() => + expect(workflowStore.activeWorkflow?.path).toBe(otherTab) + ) + await nextTick() + + expect([...tabActivity().editingPaths]).toEqual([runningTab]) + }) + + it('marks a completed tab once after a remount and stops listening when unmounted', async () => { + const first = renderPanel() + await send('add an upscaler') + first.unmount() + renderPanel() + await vi.waitFor(() => + expect(useAgentConversationStore().activeTurnId).toBe('m-1') + ) + const markModified = vi.spyOn(tabActivity(), 'markModified') + + emitDone() + + expect(markModified.mock.calls).toEqual([[runningTab]]) + }) + + it("does not move a reopened chat's turn onto the workflow restored for that chat", async () => { + const tab = workflowStore.activeWorkflow! + addBoundTab(otherTab, 'wf-other') + transcripts['th-1'] = zAgentMessages.parse([userRow('th-1', 'wf-other')]) + renderPanel() + await send('add an upscaler') + await workflowStore.closeWorkflow(tab) + await openChat('Other chat', 'th-2') + + await openChat('Running chat', 'th-1') + await vi.waitFor(() => + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(otherTab) + ) + await nextTick() + + expect(screen.getByRole('button', { name: 'Stop' })).toBeEnabled() + expect([...tabActivity().editingPaths]).toEqual([]) + }) +}) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.test.ts b/src/workbench/extensions/agent/AgentPanelRoot.test.ts index e8744afedf7..378ad6b265d 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.test.ts +++ b/src/workbench/extensions/agent/AgentPanelRoot.test.ts @@ -38,6 +38,7 @@ import { useFreeUsePlacement } from './experiments/freeUsePlacement' setupInlinePromptEditorDom() +import { useSkillPacksStore } from '@/platform/skills/stores/skillPacksStore' import type { ComfyWorkflow } from '@/platform/workflow/management/stores/comfyWorkflow' import { useWorkflowService } from '@/platform/workflow/core/services/workflowService' import { useTeamWorkspaceStore } from '@/platform/workspace/stores/teamWorkspaceStore' @@ -277,6 +278,7 @@ vi.mock(import('@/platform/workspace/composables/useBillingCapabilities'), { spy: true }) +import type { ComposerReference } from './types/composerPrompt' import type { AgentMessages, TurnId } from './schemas/agentApiSchema' import { toTurnId, zAgentWsEvent } from './schemas/agentApiSchema' import { @@ -427,7 +429,7 @@ beforeEach(() => { } ) vi.mocked(useWorkflowService()).closeWorkflow.mockImplementation( - async (tab) => { + async (tab, options) => { if (workflowStore.activeWorkflow?.path === tab.path) { const replacement = workflowStore.openWorkflows.find( (candidate) => candidate.path !== tab.path @@ -435,17 +437,34 @@ beforeEach(() => { workflowStore.activeWorkflow = replacement ? await replacement.load() : null + if (replacement) options?.onReplacementOpened?.(replacement) } await workflowStore.closeWorkflow(tab) return true } ) + vi.mocked(useWorkflowService()).closeWorkflows.mockImplementation( + async (tabs, { initiator, ...options }) => { + const opened: { replacement?: ComfyWorkflow } = {} + for (const tab of tabs) + await useWorkflowService().closeWorkflow(tab, { + ...options, + onReplacementOpened: (replacement) => { + opened.replacement = replacement + } + }) + if (initiator === 'user' && opened.replacement) + workflowStore.reportUserActivation(opened.replacement) + } + ) vi.mocked(useWorkflowService()).openWorkflow.mockImplementation( - async (tab) => { + async (tab, options) => { const known = workflowStore.getWorkflowByPath(tab.path) if (known) { workflowStore.openWorkflowsInBackground({ right: [tab.path] }) workflowStore.activeWorkflow = await known.load() + if (options?.initiator === 'user') + workflowStore.reportUserActivation(known) } return true } @@ -635,6 +654,14 @@ async function renderAndSend(text: string): Promise { await sendFromComposer(text) } +async function activateTabAsUser(tab: ComfyWorkflow): Promise { + await useWorkflowService().openWorkflow(tab, { initiator: 'user' }) +} + +async function settleFollow(): Promise { + await setImmediate() +} + function addTab( path: string, overrides: Partial = {} @@ -5176,6 +5203,58 @@ describe('AgentPanelRoot history', () => { ) }) + it('keeps a new chat rename after recovering a deleted thread', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + workflowStore.activeWorkflow = addTab('workflows/new-chat.json') + mockMessagesEndpoint('wf-first') + let accepted = 0 + respondToFetch( + { method: 'POST', url: /\/agent\/threads\/[^/]+\/messages$/ }, + () => { + accepted += 1 + return json(202, { + thread_id: `th-${accepted}`, + message_id: `message-${accepted}`, + workflow_id: 'wf-first' + }) + } + ) + respondToFetch( + { method: 'GET', url: '/api/agent/threads/th-1/messages' }, + () => json(404, { error: 'gone' }) + ) + renderWithSelectedTarget() + agentSocket.open() + await sendFromComposer('First request') + expect(useAgentConversationStore().threadId).toBe('th-1') + + agentSocket.drop() + agentSocket.open() + await vi.advanceTimersByTimeAsync(1000) + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBeNull() + ) + await userEvent.click( + await screen.findByRole('button', { + name: i18n.global.t('agent.newChatTitle') + }) + ) + const renameInput = await screen.findByRole('textbox', { + name: i18n.global.t('g.rename') + }) + await userEvent.type(renameInput, 'Recovered storyboard{Enter}') + + await sendFromComposer('Try again') + + expect(useAgentConversationStore().threadId).toBe('th-2') + expect(useAgentChatHistoryStore().titleFor('th-2')).toBe( + 'Recovered storyboard' + ) + expect( + screen.getByRole('button', { name: 'Recovered storyboard' }) + ).toBeVisible() + }) + it('renames the current chat from the title menu on Enter', async () => { await renderWithActiveThread() @@ -5408,195 +5487,1982 @@ describe('AgentPanelRoot history', () => { }) }) - describe('history row title for the active chat', () => { - function stubActiveThread(serverTitle: string): void { - vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { - const url = String(input) - - if (threadListRoute.test(url)) - return json( + it('lists a chat with no valid time among today’s chats', async () => { + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => + threadListRoute.test(String(input)) + ? json( 200, agentThreadList([ agentThread({ - id: 'th-active', - title: serverTitle, - preview: 'delete everything on this canvas', - last_message_at: '2026-07-07T10:00:00Z' + id: 'th-stampless', + title: 'Stampless chat', + last_message_at: '', + updated_at: 'unknown', + created_at: '' }) ]) ) - if (url.includes('/messages')) - return json(200, [ - { - id: 'active-user', - thread_id: 'th-active', - seq: 1, - role: 'user', - status: 'complete', - turn_id: 'active-turn', - content: { text: 'Clear entire canvas' } - } - ]) - return json(200, []) - }) - useAgentConversationStore().setThreadId('th-active') - } - - it('shows the first user message while the server title is empty', async () => { - stubActiveThread('') - renderWithSelectedTarget() - await screen.findByRole('button', { name: 'Clear entire canvas' }) - - await openHistory() - - expect( - await screen.findByRole('button', { name: 'Clear entire canvas' }) - ).toBeInTheDocument() - expect( - screen.queryByText('delete everything on this canvas') - ).not.toBeInTheDocument() - }) - - it('keeps the server title when one exists', async () => { - stubActiveThread('Canvas cleanup') - renderWithSelectedTarget() - await screen.findByRole('button', { name: 'Clear entire canvas' }) - - await openHistory() - - expect( - await screen.findByRole('button', { name: 'Canvas cleanup' }) - ).toBeInTheDocument() - expect( - screen.queryByRole('button', { name: 'Clear entire canvas' }) - ).not.toBeInTheDocument() - }) - }) - - it('surfaces a thread-list failure via the host error modal', async () => { - executionErrors.showErrorOverlay.mockClear() - telemetry.trackAgentError.mockClear() - vi.mocked(fetch).mockImplementation( - async () => new Response('{}', { status: 500 }) + : json(200, []) ) renderWithSelectedTarget() + const history = useAgentChatHistoryStore() await vi.waitFor(() => - expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) - ) - expect(executionErrors.lastPromptError).toMatchObject({ - type: 'agent_api_failed' - }) - expect(telemetry.trackAgentError).toHaveBeenCalledWith( - expect.objectContaining({ - error_class: 'thread_list_load_failed', - failure_stage: 'pre_acceptance', - retryable: true, - turn_accepted: false, - ui_treatment: 'error_overlay' - }) + expect(history.grouped.today.map(({ id }) => id)).toEqual([ + 'th-stampless' + ]) ) - expect(useAgentChatHistoryStore().sessions).toHaveLength(0) }) - it('keeps the loaded chat list and reports a non-retryable failure when a refresh ends before its last page', async () => { - respondToFetch(threadListRoute, () => - 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(threadListRoute, () => - json( - 200, - agentThreadList( - [ + 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!: () => void + const workflowsListed = new Promise((resolve) => { + resolveWorkflows = resolve + }) + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (threadListRoute.test(url)) + return json( + 200, + agentThreadList([ agentThread({ - id: 'th-partial', - title: 'Partial chat', - last_message_at: '2026-07-07T11:00:00Z' + 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' }) - ], - { has_more: true } + ]) ) - ) + if (url.includes('/api/workflows')) { + await workflowsListed + 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, []) + } + return json(200, { data: [], pagination: { has_more: false } }) + }) + + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(2) ) + expect(useAgentConversationStore().threadId).toBeNull() - await openHistory() + await activateTabAsUser(second) + await settleFollow() + expect(useAgentConversationStore().threadId).toBeNull() + + resolveWorkflows() await vi.waitFor(() => - expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) - ) - expect(telemetry.trackAgentError).toHaveBeenCalledWith( - expect.objectContaining({ - error_class: 'thread_list_load_failed', - retryable: false - }) + expect(useAgentConversationStore().threadId).toBe('th-second') ) - expect(reportError).toHaveBeenCalledWith( - expect.objectContaining({ - message: 'Agent thread list ended before its last page' - }), - expect.objectContaining({ tags: { reason: 'missing_cursor' } }) + + await activateTabAsUser(first) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-first') ) - expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) + expect(loadedThreads).toEqual(['th-second', 'th-first']) }) - const staleRefreshOutcomes = [ - { - outcome: 'a list', - staleResponse: () => - json( - 200, - agentThreadList([ - agentThread({ - id: 'th-stale', - title: 'Stale chat', - last_message_at: '2026-07-07T09:00:00Z' + describe('following the active workflow tab', () => { + function transcriptFor(threadId: string, workflowId?: string): Response { + return json(200, [ + { + id: `${threadId}-user`, + thread_id: threadId, + seq: 1, + role: 'user', + status: 'complete', + turn_id: `${threadId}-turn`, + workflow_id: workflowId, + content: { text: `Prompt in ${threadId}` } + } + ] satisfies AgentMessages) + } + + function stubWorkflowBoundHistory( + threads: AgentThreadSummary[], + transcripts: Partial< + Record< + string, + { workflowId?: string; response?: () => Promise } + > + > = {}, + { + post = async (threadId: string) => + json(202, { thread_id: threadId, message_id: `${threadId}-sent` }) + }: { post?: (threadId: string) => Promise } = {} + ): { + loadedThreads: string[] + listCalls: () => number + } { + const loadedThreads: string[] = [] + let listCalls = 0 + function answerMessages( + threadId: string, + method: string | undefined + ): Promise | Response { + if (method === 'POST') return post(threadId) + loadedThreads.push(threadId) + const transcript = transcripts[threadId] + return transcript?.response + ? transcript.response() + : transcriptFor(threadId, transcript?.workflowId) + } + vi.mocked(fetch).mockImplementation( + async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input) + if (threadListRoute.test(url)) { + 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' }, + { id: 'wf-third', name: 'third' } + ], + pagination: { offset: 0, limit: 100, total: 3, has_more: false } }) - ]) - ) - }, - { outcome: 'a failure', staleResponse: () => json(500, {}) } - ] + const match = url.match(/\/api\/agent\/threads\/([^/]+)\/messages$/) + if (match) return answerMessages(match[1], init?.method) + return json(200, { data: [], pagination: { has_more: false } }) + } + ) + return { loadedThreads, listCalls: () => listCalls } + } - it.for(staleRefreshOutcomes)( - 'ignores a closed panel history refresh that ends with $outcome after the panel reopens', - async ({ staleResponse }) => { - const secondPageRoute = /\/api\/agent\/threads\?.*after=page-2/ - let resolveStale!: (response: Response) => void - const staleSecondPage = new Promise((resolve) => { - resolveStale = resolve - }) - respondToFetch(threadListRoute, () => - 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' } - ) - ) + function userPrompts(): string[] { + return useAgentConversationStore().entries.flatMap((entry) => + entry.role === 'user' ? [entry.text] : [] ) - respondToFetch(secondPageRoute, () => staleSecondPage, { times: 1 }) - const closedPanel = renderWithSelectedTarget() + } + + 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() + await activateTabAsUser(first) + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-first') + ) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-first']) + ) + + await activateTabAsUser(second) + await settleFollow() + + 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() + await activateTabAsUser(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') + ) + await vi.waitFor(() => + expect(listCalls()).toBeGreaterThan(callsBeforeSelect) + ) + await settleFollow() + + expect(useAgentConversationStore().threadId).toBe('th-other') + expect(loadedThreads).toEqual(['th-first', 'th-other']) + }) + + async function activateWhileTabIdsLoad(): Promise<{ + resolveWorkflows: () => void + loadedThreads: string[] + }> { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + + const loadedThreads: string[] = [] + let resolveWorkflows!: () => void + const workflowsListed = new Promise((resolve) => { + resolveWorkflows = resolve + }) + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (threadListRoute.test(url)) + 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')) { + await workflowsListed + return json(200, { + data: [{ id: 'wf-first', name: 'first' }], + pagination: { offset: 0, limit: 100, total: 1, has_more: false } + }) + } + 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) + ) + await activateTabAsUser(first) + await settleFollow() + expect(loadedThreads).toEqual([]) + + return { loadedThreads, resolveWorkflows } + } + + it.for([ + { meanwhile: 'nothing', act: async () => {}, loads: ['th-first'] }, + { + meanwhile: 'a new chat', + act: () => + userEvent.click( + screen.getByRole('button', { name: i18n.global.t('agent.newChat') }) + ), + loads: [] + }, + { + meanwhile: 'a draft typed and cleared', + act: async () => { + const composer = useAgentComposerStore() + composer.setText('make it blue') + await nextTick() + composer.setText('') + await nextTick() + }, + loads: [] + } + ])( + 'after $meanwhile, a follow waiting on the tab id loads $loads', + async ({ act, loads }) => { + const { resolveWorkflows, loadedThreads } = + await activateWhileTabIdsLoad() + + await act() + resolveWorkflows() + await settleFollow() + + expect(loadedThreads).toEqual(loads) + } + ) + + 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() + await activateTabAsUser(second) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-newer') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(loadedThreads).toEqual(['th-newer']) + }) + + type Composer = ReturnType + + it.for([ + { + draft: 'text', + fill: (composer: Composer) => composer.setText('make it blue'), + drafted: (composer: Composer) => composer.draft, + clear: (composer: Composer) => composer.setText('') + }, + { + draft: 'a workflow reference', + fill: (composer: Composer) => + composer.setWorkflowReferences([ + { id: 'wf-third', name: 'third', textOffset: 0 } + ]), + drafted: (composer: Composer) => + composer.workflowReferences.map(({ id }) => id), + clear: (composer: Composer) => composer.setWorkflowReferences([]) + }, + { + draft: 'only a scoped skill reference', + fill: (composer: Composer) => + composer.restorePrompt({ + text: '', + references: [ + { + kind: 'skill', + name: 'portrait', + description: 'Keep the subject recognizable', + scope: useSkillPacksStore().scope, + textOffset: 0 + } satisfies ComposerReference + ] + }), + drafted: (composer: Composer) => ({ + text: composer.prompt.text, + references: composer.prompt.references.map((reference) => ({ + ...reference + })) + }), + clear: (composer: Composer) => + composer.restorePrompt({ text: '', references: [] }) + } + ])( + 'keeps the chat, draft and target when the composer holds $draft', + async ({ fill, drafted, clear }) => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = 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' } } + ) + 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']) + ) + const composer = useAgentComposerStore() + fill(composer) + const before = drafted(composer) + expect(composer.hasDraft).toBe(true) + + await activateTabAsUser(second) + await settleFollow() + + expect(loadedThreads).toEqual(['th-first']) + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(userPrompts()).toEqual(['Prompt in th-first']) + expect(drafted(composer)).toEqual(before) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + expect(screen.getByRole('note')).toHaveTextContent( + i18n.global.t('agent.viewingDifferentWorkflow') + ) + + clear(composer) + await settleFollow() + expect(loadedThreads).toEqual(['th-first']) + } + ) + + it('sends a pinned draft to its original chat and workflow while another tab is active', async () => { + const firstState = fromPartial({ + nodes: [{ id: 17, type: 'FirstWorkflowNode' }], + links: [] + }) + const first = addTab('workflows/first.json', { activeState: firstState }) + const second = addTab('workflows/second.json', { + activeState: fromPartial({ + nodes: [{ id: 83, type: 'SecondWorkflowNode' }], + links: [] + }) + }) + workflowStore.activeWorkflow = first + 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' } } + ) + respondToFetch(/\/assets(?:\?|$)/, () => + json(200, { assets: [], total: 0, has_more: false }) + ) + 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']) + ) + await userEvent.click(screen.getByRole('textbox')) + await userEvent.paste('Keep this request on the first workflow') + + await activateTabAsUser(second) + await settleFollow() + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + await userEvent.click(screen.getByRole('button', { name: 'Send' })) + + await vi.waitFor(() => + expect( + fetchRequests({ method: 'POST', url: /\/messages$/ }) + ).toHaveLength(1) + ) + const [request] = fetchRequests({ method: 'POST', url: /\/messages$/ }) + expect(request.url).toBe('/api/agent/threads/th-first/messages') + expect(JSON.parse(String(request.body))).toMatchObject({ + content: 'Keep this request on the first workflow', + workflow_id: 'wf-first', + draft: { content: firstState } + }) + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(workflowStore.activeWorkflow.path).toBe(second.path) + expect(useAgentComposerStore().draft).toBe('') + }) + + 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 ') + + await activateTabAsUser(second) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(composer.draft).toBe('') + }) + + it("opens the tab's chat from an empty chat that was never sent", 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' + }) + ]) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + + await activateTabAsUser(second) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + }) + + it.for([ + { + outcome: 'succeeds', + titleSource: 'existing chat', + response: async () => transcriptFor('th-second', 'wf-second'), + expectedThreadId: 'th-second', + expectedTitle: 'Prompt in th-second', + showsFailure: false + }, + { + outcome: 'fails', + titleSource: 'unsent chat', + response: async () => json(500, { error: 'unavailable' }), + expectedThreadId: null, + expectedTitle: 'Duck storyboard', + showsFailure: true + } + ])( + 'keeps the $titleSource title when following from a renamed unsent chat $outcome', + async ({ response, expectedThreadId, expectedTitle, showsFailure }) => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const { loadedThreads } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ], + { 'th-second': { response } } + ) + respondToFetch(/\/assets(?:\?|$)/, () => + json(200, { assets: [], total: 0, has_more: false }) + ) + render(AgentPanelRoot, { global: { plugins: [i18n] } }) + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.newChatTitle') + }) + ) + const renameInput = await screen.findByRole('textbox', { + name: i18n.global.t('g.rename') + }) + await userEvent.type(renameInput, 'Duck storyboard{Enter}') + expect( + screen.getByRole('button', { name: 'Duck storyboard' }) + ).toBeVisible() + + await activateTabAsUser(second) + + await vi.waitFor(() => expect(loadedThreads).toEqual(['th-second'])) + await waitFor(() => + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + ) + expect(useAgentConversationStore().threadId).toBe(expectedThreadId) + expect(useAgentChatHistoryStore().titleFor('th-second')).toBeUndefined() + expect( + screen.getByRole('button', { name: expectedTitle }) + ).toBeVisible() + expect(screen.queryByText(followFailure()) !== null).toBe(showsFailure) + } + ) + + it('moves the target of a drafted chat that was never sent instead of switching', async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + 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) + ) + useAgentComposerStore().setText('make it blue') + + await activateTabAsUser(second) + await settleFollow() + + expect(loadedThreads).toEqual([]) + expect(useAgentConversationStore().threadId).toBeNull() + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(useAgentComposerStore().draft).toBe('make it blue') + }) + + it('follows the tab that takes over when the user closes the active one', async () => { + const first = addTab('workflows/first.json') + 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' + }) + ]) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + + await useWorkflowService().closeWorkflows([first], { + warnIfUnsaved: true, + initiator: 'user' + }) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe( + 'workflows/second.json' + ) + }) + + it('re-lists chats without waiting for another workflow lookup when the tab id is known', async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const { listCalls } = 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) + ) + await settleFollow() + const listedBefore = listCalls() + respondToFetch( + /\/api\/workflows(?:\?|$)/, + () => new Promise(() => {}) + ) + + workflowStore.activeWorkflow = second + workflowStore.reportUserActivation(second) + + await screen.findByRole('button', { name: 'Prompt in th-second' }) + expect(listCalls()).toBe(listedBefore + 1) + }) + + it('does not re-list chats for a saved tab that has no cloud workflow', async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const unlisted = addTab('workflows/fourth.json') + const { listCalls, loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }) + ]) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + const listedBefore = listCalls() + + await activateTabAsUser(unlisted) + await settleFollow() + + expect(listCalls()).toBe(listedBefore) + expect(loadedThreads).toEqual([]) + }) + + it('does not follow a tab the app activates on its own, like a restored or linked workflow', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const third = addTab('workflows/third.json') + workflowStore.activeWorkflow = third + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T08: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' + }), + agentThread({ + id: 'th-third', + title: 'Third chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-third' + }) + ]) + renderWithSelectedTarget() + await activateTabAsUser(first) + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-first') + ) + + await useWorkflowService().openWorkflow(second) + await activateTabAsUser(third) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-third') + ) + expect(loadedThreads).toEqual(['th-first', 'th-third']) + }) + + 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) + ) + + await activateTabAsUser(scratch) + + await settleFollow() + expect(loadedThreads).not.toContain('th-second') + 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 + let answerThird!: () => void + const { loadedThreads } = 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, [])) + }) + }, + 'th-third': { + response: () => + new Promise((resolve) => { + answerThird = () => + resolve(transcriptFor('th-third', 'wf-third')) + }) + } + } + ) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(2) + ) + + await activateTabAsUser(second) + await vi.waitFor(() => expect(loadedThreads).toEqual(['th-second'])) + expect( + await screen.findByRole('status', { name: 'Opening chat for second…' }) + ).toBeVisible() + await activateTabAsUser(third) + expect( + await screen.findByRole('status', { name: 'Opening chat for third…' }) + ).toBeVisible() + await vi.waitFor(() => + expect(loadedThreads).toEqual(['th-second', 'th-third']) + ) + answerSecond() + await settleFollow() + + expect( + screen.getByRole('status', { name: 'Opening chat for third…' }) + ).toBeVisible() + expect(screen.getByTestId('agent-panel-footer')).toHaveAttribute('inert') + answerThird() + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-third']) + ) + + 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.for([ + { + outcome: 'succeeds', + answer: () => transcriptFor('th-second', 'wf-second') + }, + { + outcome: 'fails', + answer: () => json(500, { error: 'unavailable' }) + } + ])( + 'keeps the original chat unlocked when pending second-tab messages $outcome after returning to first', + async ({ answer }) => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + let answerSecond!: () => void + const secondMessages = new Promise((resolve) => { + answerSecond = () => resolve(answer()) + }) + const { loadedThreads } = 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: () => secondMessages } + } + ) + 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']) + ) + + await activateTabAsUser(second) + await vi.waitFor(() => + expect(loadedThreads).toEqual(['th-first', 'th-second']) + ) + expect( + await screen.findByRole('status', { + name: 'Opening chat for second…' + }) + ).toBeVisible() + await activateTabAsUser(first) + await waitFor(() => + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + ) + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + + answerSecond() + await settleFollow() + + expect(workflowStore.activeWorkflow.path).toBe(first.path) + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + expect(userPrompts()).toEqual(['Prompt in th-first']) + expect(screen.queryByRole('status')).toBeNull() + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + expect(screen.getByRole('textbox')).toHaveTextContent(/^$/) + expect(screen.queryByText(followFailure())).toBeNull() + expect(loadedThreads).toEqual(['th-first', 'th-second']) + } + ) + + async function openFirstChatThenLoseTranscripts(): Promise<{ + loadedThreads: string[] + restoreTranscripts: () => void + }> { + const first = addTab('workflows/first.json') + addTab('workflows/second.json') + workflowStore.activeWorkflow = first + let transcriptsUp = true + const answer = (threadId: string, workflowId?: string) => async () => + transcriptsUp + ? transcriptFor(threadId, workflowId) + : json(500, { error: 'unavailable' }) + const { loadedThreads } = 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': { response: answer('th-first', 'wf-first') }, + 'th-second': { response: answer('th-second') } + } + ) + 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']) + ) + transcriptsUp = false + return { loadedThreads, restoreTranscripts: () => (transcriptsUp = true) } + } + + const followFailure = () => + i18n.global.t('agent.followedChatOpenFailed', { workflowName: 'second' }) + + const cachedSecondThread = agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + const failedFollowListing = () => json(500, { error: 'unavailable' }) + const incompleteFollowListing = () => + json(200, agentThreadList([], { has_more: true })) + + async function openFirstChatWithHistory(threads: AgentThreadSummary[]) { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-first', + title: 'First chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-first' + }), + ...threads + ], + { 'th-first': { workflowId: 'wf-first' } } + ) + 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']) + ) + await settleFollow() + return { first, second, loadedThreads } + } + + it.for([ + { + listing: 'failed', + cached: 'an old matching chat', + threads: [cachedSecondThread], + answer: failedFollowListing + }, + { + listing: 'incomplete', + cached: 'an old matching chat', + threads: [cachedSecondThread], + answer: incompleteFollowListing + }, + { + listing: 'failed', + cached: 'no matching chat', + threads: [], + answer: failedFollowListing + }, + { + listing: 'incomplete', + cached: 'no matching chat', + threads: [], + answer: incompleteFollowListing + } + ])( + 'keeps the current chat after a $listing follow listing with $cached cached, then retries the newest chat', + async ({ threads, answer }) => { + const { first, second, loadedThreads } = + await openFirstChatWithHistory(threads) + respondToFetch(threadListRoute, answer) + + await activateTabAsUser(second) + await settleFollow() + + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(userPrompts()).toEqual(['Prompt in th-first']) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + expect(workflowStore.activeWorkflow?.path).toBe(second.path) + expect(loadedThreads).toEqual(['th-first']) + expect(await screen.findByText(followFailure())).toBeVisible() + expect(screen.queryByRole('status')).toBeNull() + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + expect(executionErrors.recordPromptError).not.toHaveBeenCalled() + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + + respondToFetch(threadListRoute, () => + json( + 200, + agentThreadList([ + cachedSecondThread, + agentThread({ + id: 'th-newest', + title: 'Newest chat', + last_message_at: '2026-09-22T11:00:00Z', + workflow_id: 'wf-second' + }) + ]) + ) + ) + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.retryFollowedChat', { + workflowName: 'second' + }) + }) + ) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-newest') + ) + expect(userPrompts()).toEqual(['Prompt in th-newest']) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(loadedThreads).toEqual(['th-first', 'th-newest']) + expect(screen.queryByText(followFailure())).toBeNull() + } + ) + + it.for([ + { + listing: 'failed', + cancel: 'returning to the original tab', + answer: failedFollowListing, + retire: activateTabAsUser + }, + { + listing: 'incomplete', + cancel: 'starting a draft', + answer: incompleteFollowListing, + retire: async () => useAgentComposerStore().setText('Keep this chat') + }, + { + listing: 'complete', + cancel: 'returning to the original tab', + answer: () => json(200, agentThreadList([cachedSecondThread])), + retire: activateTabAsUser + } + ])( + 'ignores a late $listing follow listing after $cancel', + async ({ answer, retire }) => { + const { first, second, loadedThreads } = await openFirstChatWithHistory( + [cachedSecondThread] + ) + let answerList!: () => void + const listing = new Promise((resolve) => { + answerList = () => resolve(answer()) + }) + respondToFetch(threadListRoute, () => listing) + + await activateTabAsUser(second) + expect( + await screen.findByRole('status', { + name: 'Opening chat for second…' + }) + ).toBeVisible() + await retire(first) + answerList() + await settleFollow() + + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(userPrompts()).toEqual(['Prompt in th-first']) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(first.path) + expect(loadedThreads).toEqual(['th-first']) + expect(screen.queryByText(followFailure())).toBeNull() + expect(screen.queryByRole('status')).toBeNull() + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + } + ) + + it('keeps the current conversation covered until the followed chat is ready', async () => { + await openFirstChatThenLoseTranscripts() + const second = workflowStore.getWorkflowByPath('workflows/second.json') + assert(second) + const serve = vi.mocked(fetch).getMockImplementation() + assert(serve) + let answerList!: () => void + const listing = new Promise((resolve) => { + answerList = () => + resolve( + json( + 200, + agentThreadList([ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + ) + ) + }) + let answerMessages!: () => void + const transcript = new Promise((resolve) => { + answerMessages = () => resolve(transcriptFor('th-second', 'wf-second')) + }) + let markMessagesRequested!: () => void + const messagesRequested = new Promise((resolve) => { + markMessagesRequested = resolve + }) + vi.mocked(fetch).mockImplementation((input, init) => { + if (threadListRoute.test(String(input))) return listing + if (String(input).endsWith('/threads/th-second/messages')) { + markMessagesRequested() + return transcript + } + return serve(input, init) + }) + + await activateTabAsUser(second) + + expect(screen.getByTestId('agent-panel-footer')).toHaveAttribute('inert') + expect( + await screen.findByRole('status', { + name: 'Opening chat for second…' + }) + ).toBeVisible() + expect( + within(screen.getByTestId('agent-conversation')).getByText( + 'Prompt in th-first' + ) + ).toBeInTheDocument() + + answerList() + await messagesRequested + + expect( + screen.getByRole('status', { name: 'Opening chat for second…' }) + ).toBeVisible() + expect(userPrompts()).toEqual(['Prompt in th-first']) + + answerMessages() + await within(screen.getByTestId('agent-conversation')).findByText( + 'Prompt in th-second' + ) + + await vi.waitFor(() => + expect( + screen.queryByRole('status', { name: 'Opening chat for second…' }) + ).toBeNull() + ) + expect(screen.getByTestId('agent-panel-footer')).not.toHaveAttribute( + 'inert' + ) + }) + + it('reports a followed chat that fails to open only in its notice', async () => { + await openFirstChatThenLoseTranscripts() + const second = workflowStore.getWorkflowByPath('workflows/second.json') + assert(second) + + await activateTabAsUser(second) + + expect(await screen.findByText(followFailure())).toBeVisible() + expect(executionErrors.recordPromptError).not.toHaveBeenCalled() + expect(executionErrors.showErrorOverlay).not.toHaveBeenCalled() + }) + + it.for([ + { followList: 'still loading', overlays: 1 }, + { followList: 'already shown', overlays: 0 } + ])( + 'shows $overlays overlay for a failed history load while the follow list is $followList', + async ({ followList, overlays }) => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + let failMountList!: () => void + const mountList = new Promise((resolve) => { + failMountList = () => resolve(json(500, { error: 'unavailable' })) + }) + const lists = + followList === 'still loading' + ? [mountList, new Promise(() => {})] + : [mountList] + stubWorkflowBoundHistory([ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + const served = vi.mocked(fetch).getMockImplementation() + assert(served) + let listRequests = 0 + vi.mocked(fetch).mockImplementation((input, init) => { + if (!threadListRoute.test(String(input))) return served(input, init) + listRequests += 1 + return lists.splice(0, 1)[0] ?? served(input, init) + }) + renderWithSelectedTarget() + + await activateTabAsUser(second) + await vi.waitFor(() => expect(listRequests).toBe(2)) + await settleFollow() + failMountList() + await settleFollow() + + expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(overlays) + } + ) + + it('keeps the open chat untouched when the followed chat fails to open, and retries', async () => { + const { loadedThreads, restoreTranscripts } = + await openFirstChatThenLoseTranscripts() + const second = workflowStore.getWorkflowByPath('workflows/second.json') + assert(second) + + await activateTabAsUser(second) + + expect(await screen.findByText(followFailure())).toBeVisible() + expect(userPrompts()).toEqual(['Prompt in th-first']) + expect(useAgentConversationStore().threadId).toBe('th-first') + expect(useAgentPanelStore().selectedWorkflow?.path).toBe( + 'workflows/first.json' + ) + expect(workflowStore.activeWorkflow?.path).toBe(second.path) + expect(loadedThreads).toEqual(['th-first', 'th-second']) + + restoreTranscripts() + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.retryFollowedChat', { + workflowName: 'second' + }) + }) + ) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(screen.queryByText(followFailure())).toBeNull() + }) + + it('drops the follow failure notice once the user sends in the open chat', async () => { + await openFirstChatThenLoseTranscripts() + const second = workflowStore.getWorkflowByPath('workflows/second.json') + assert(second) + await activateTabAsUser(second) + expect(await screen.findByText(followFailure())).toBeVisible() + + await sendFromComposer('keep going here') + + expect(screen.queryByText(followFailure())).toBeNull() + expect(useAgentConversationStore().threadId).toBe('th-first') + }) + + it('holds the follow back while a message is still being sent', 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' + }) + ], + {}, + { post: () => new Promise(() => {}) } + ) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + await sendFromComposer('make it blue') + + await activateTabAsUser(second) + await settleFollow() + + expect(loadedThreads).toEqual([]) + expect(useAgentComposerStore().submission?.phase).toBe('pending') + }) + + it('follows while a sent message runs once the server has accepted it', 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' + }) + ]) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + await sendFromComposer('make it blue') + await vi.waitFor(() => + expect(useAgentComposerStore().submission).toBeNull() + ) + expect(screen.getByRole('button', { name: 'Stop' })).toBeVisible() + + await activateTabAsUser(second) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-second') + ) + }) + + it("opens the active tab's chat on mount when the target is another tab", async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + workflowStore.activeWorkflow = second + useAgentPanelStore().setWorkflowTarget(first) + 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(useAgentConversationStore().threadId).toBe('th-second') + ) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + }) + + 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 settleFollow() + expect(loadedThreads).not.toContain('th-newest') + 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']) + ) + await activateTabAsUser(second) + + await userEvent.click( + await screen.findByRole('button', { + name: 'Show target workflow: first' + }) + ) + await vi.waitFor(() => + expect(workflowStore.activeWorkflow?.path).toBe(first.path) + ) + + await settleFollow() + expect(loadedThreads).not.toContain('th-newest') + 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() + await activateTabAsUser(second) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-second']) + ) + await settleFollow() + + expect(workflowStore.activeWorkflow.path).toBe(second.path) + expect(useAgentPanelStore().selectedWorkflow?.path).toBe(second.path) + expect(useAgentConversationStore().threadId).toBe('th-second') + }) + + it('requests the activated tab chat before the next macrotask', async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + 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) + ) + + await activateTabAsUser(second) + await settleFollow() + + expect(loadedThreads).toEqual(['th-second']) + }) + + it("opens the tab's newest chat when it started after the list loaded", async () => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const threads = [ + agentThread({ + id: 'th-old', + title: 'Old chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-second' + }) + ] + const { loadedThreads } = stubWorkflowBoundHistory(threads) + renderWithSelectedTarget() + await vi.waitFor(() => + expect(useAgentChatHistoryStore().sessions).toHaveLength(1) + ) + threads.push( + agentThread({ + id: 'th-new', + title: 'New chat', + last_message_at: '2026-09-22T11:00:00Z', + workflow_id: 'wf-second' + }) + ) + + await activateTabAsUser(second) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-new') + ) + expect(loadedThreads).toEqual(['th-new']) + }) + + it.for([ + { + stamps: 'no message time', + last_message_at: '', + updated_at: '2026-09-01T10:00:00Z', + created_at: '2026-09-01T09:00:00Z' + }, + { + stamps: 'an unparsable message time', + last_message_at: 'yesterday', + updated_at: '2026-09-01T10:00:00Z', + created_at: '2026-09-01T09:00:00Z' + }, + { + stamps: 'no valid time at all', + last_message_at: '', + updated_at: 'unknown', + created_at: '' + } + ])( + 'ranks a chat with $stamps by its next valid time', + async ({ last_message_at, updated_at, created_at }) => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const { loadedThreads } = stubWorkflowBoundHistory([ + agentThread({ + id: 'th-stale', + title: 'Stale chat', + last_message_at, + updated_at, + created_at, + workflow_id: 'wf-second' + }), + agentThread({ + id: 'th-recent', + title: 'Recent chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ]) + renderWithSelectedTarget() + + await activateTabAsUser(second) + + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-recent') + ) + expect(loadedThreads).toEqual(['th-recent']) + } + ) + + it('keeps the open chat when the user returns to the tab it targets', async () => { + const first = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const third = addTab('workflows/third.json') + workflowStore.activeWorkflow = first + const { loadedThreads } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-newer', + title: 'Newer chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-older', + title: 'Older chat', + last_message_at: '2026-09-22T09:00:00Z', + workflow_id: 'wf-first' + }), + agentThread({ + id: 'th-third', + title: 'Third chat', + last_message_at: '2026-09-22T08:00:00Z', + workflow_id: 'wf-third' + }) + ], + { 'th-older': { workflowId: 'wf-first' } } + ) + renderWithSelectedTarget() + await userEvent.click( + screen.getByRole('button', { + name: i18n.global.t('agent.showChatHistory') + }) + ) + await userEvent.click(await screen.findByText('Older chat')) + await vi.waitFor(() => + expect(userPrompts()).toEqual(['Prompt in th-older']) + ) + + await activateTabAsUser(second) + await activateTabAsUser(first) + await settleFollow() + + expect(useAgentConversationStore().threadId).toBe('th-older') + expect(loadedThreads).toEqual(['th-older']) + + await activateTabAsUser(third) + await vi.waitFor(() => + expect(useAgentConversationStore().threadId).toBe('th-third') + ) + expect(loadedThreads).toEqual(['th-older', 'th-third']) + }) + it.for([ + { outcome: 'opens', answer: () => json(200, []) }, + { + outcome: 'fails', + answer: () => json(500, { error: 'unavailable' }) + } + ])( + 'leaves the user on a later tab when an earlier follow $outcome', + async ({ answer }) => { + workflowStore.activeWorkflow = addTab('workflows/first.json') + const second = addTab('workflows/second.json') + const scratch = addTab('workflows/scratch.json', { isTemporary: true }) + let answerSecond!: () => void + const { loadedThreads } = stubWorkflowBoundHistory( + [ + agentThread({ + id: 'th-second', + title: 'Second chat', + last_message_at: '2026-09-22T10:00:00Z', + workflow_id: 'wf-second' + }) + ], + { + 'th-second': { + response: () => + new Promise((resolve) => { + answerSecond = () => resolve(answer()) + }) + } + } + ) + renderWithSelectedTarget() + await activateTabAsUser(second) + await vi.waitFor(() => expect(loadedThreads).toEqual(['th-second'])) + + await activateTabAsUser(scratch) + answerSecond() + await settleFollow() + + expect(workflowStore.activeWorkflow.path).toBe(scratch.path) + expect(useAgentConversationStore().threadId).toBeNull() + expect( + screen.queryByText( + i18n.global.t('agent.followedChatOpenFailed', { + workflowName: 'second' + }) + ) + ).toBeNull() + } + ) + }) + + describe('history row title for the active chat', () => { + function stubActiveThread(serverTitle: string): void { + vi.mocked(fetch).mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + + if (threadListRoute.test(url)) + return json( + 200, + agentThreadList([ + agentThread({ + id: 'th-active', + title: serverTitle, + preview: 'delete everything on this canvas', + last_message_at: '2026-07-07T10:00:00Z' + }) + ]) + ) + if (url.includes('/messages')) + return json(200, [ + { + id: 'active-user', + thread_id: 'th-active', + seq: 1, + role: 'user', + status: 'complete', + turn_id: 'active-turn', + content: { text: 'Clear entire canvas' } + } + ]) + return json(200, []) + }) + useAgentConversationStore().setThreadId('th-active') + } + + it('shows the first user message while the server title is empty', async () => { + stubActiveThread('') + renderWithSelectedTarget() + await screen.findByRole('button', { name: 'Clear entire canvas' }) + + await openHistory() + + expect( + await screen.findByRole('button', { name: 'Clear entire canvas' }) + ).toBeInTheDocument() + expect( + screen.queryByText('delete everything on this canvas') + ).not.toBeInTheDocument() + }) + + it('keeps the server title when one exists', async () => { + stubActiveThread('Canvas cleanup') + renderWithSelectedTarget() + await screen.findByRole('button', { name: 'Clear entire canvas' }) + + await openHistory() + + expect( + await screen.findByRole('button', { name: 'Canvas cleanup' }) + ).toBeInTheDocument() + expect( + screen.queryByRole('button', { name: 'Clear entire canvas' }) + ).not.toBeInTheDocument() + }) + }) + + it('surfaces a thread-list failure via the host error modal', async () => { + executionErrors.showErrorOverlay.mockClear() + telemetry.trackAgentError.mockClear() + vi.mocked(fetch).mockImplementation( + async () => new Response('{}', { status: 500 }) + ) + + renderWithSelectedTarget() + + await vi.waitFor(() => + expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) + ) + expect(executionErrors.lastPromptError).toMatchObject({ + type: 'agent_api_failed' + }) + expect(telemetry.trackAgentError).toHaveBeenCalledWith( + expect.objectContaining({ + error_class: 'thread_list_load_failed', + failure_stage: 'pre_acceptance', + retryable: true, + turn_accepted: false, + ui_treatment: 'error_overlay' + }) + ) + expect(useAgentChatHistoryStore().sessions).toHaveLength(0) + }) + + it('keeps the loaded chat list and reports a non-retryable failure when a refresh ends before its last page', async () => { + respondToFetch(threadListRoute, () => + 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(threadListRoute, () => + json( + 200, + agentThreadList( + [ + agentThread({ + id: 'th-partial', + title: 'Partial chat', + last_message_at: '2026-07-07T11:00:00Z' + }) + ], + { has_more: true } + ) + ) + ) + + await openHistory() + + await vi.waitFor(() => + expect(executionErrors.showErrorOverlay).toHaveBeenCalledTimes(1) + ) + expect(telemetry.trackAgentError).toHaveBeenCalledWith( + expect.objectContaining({ + error_class: 'thread_list_load_failed', + retryable: false + }) + ) + expect(reportError).toHaveBeenCalledWith( + expect.objectContaining({ + message: 'Agent thread list ended before its last page' + }), + expect.objectContaining({ tags: { reason: 'missing_cursor' } }) + ) + expect(history.sessions.map(({ id }) => id)).toEqual(['th-kept']) + }) + + const staleRefreshOutcomes = [ + { + 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, {}) } + ] + + it.for(staleRefreshOutcomes)( + 'ignores a closed panel history refresh that ends with $outcome after the panel reopens', + async ({ staleResponse }) => { + const secondPageRoute = /\/api\/agent\/threads\?.*after=page-2/ + let resolveStale!: (response: Response) => void + const staleSecondPage = new Promise((resolve) => { + resolveStale = resolve + }) + respondToFetch(threadListRoute, () => + 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' } + ) + ) + ) + respondToFetch(secondPageRoute, () => staleSecondPage, { times: 1 }) + const closedPanel = renderWithSelectedTarget() await vi.waitFor(() => expect(fetchRequests(secondPageRoute)).toHaveLength(1) ) @@ -6309,14 +8175,16 @@ describe('AgentPanelRoot lifecycle', () => { it('clears workflow activity when the panel unmounts', () => { const activity = useWorkflowTabActivityStore() - activity.setEditing('workflows/active.json') + activity.setAgentTurnTabs([ + { path: 'workflows/active.json', awaitingApproval: false } + ]) activity.setCreating(true) const { unmount } = renderWithSelectedTarget() unmount() - expect(activity.$state.editingTabPath).toBeNull() + expect(activity.editingPaths.size).toBe(0) expect(activity.$state.creatingTab).toBe(false) }) }) @@ -8916,14 +10784,14 @@ describe('AgentPanelRoot workflow binding', () => { await renderAndSend('add an upscaler') const activity = useWorkflowTabActivityStore() - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) dispatchApiEvent('agent_message_done', { message_id: 'm-1', thread_id: 'th-1' }) await screen.findByRole('button', { name: 'Send' }) - expect(activity.editingTabPath).toBeNull() + expect(activity.editingPaths.size).toBe(0) expect(activity.unseenModifiedPaths.has('workflows/current.json')).toBe( true ) @@ -8937,12 +10805,12 @@ describe('AgentPanelRoot workflow binding', () => { await sendFromComposer('add an upscaler') const activity = useWorkflowTabActivityStore() - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) activity.setCreating(true) unmount() - expect(activity.editingTabPath).toBeNull() + expect(activity.editingPaths.size).toBe(0) expect(activity.creatingTab).toBe(false) }) @@ -9064,7 +10932,7 @@ describe('AgentPanelRoot workflow binding', () => { await renderAndSend('add an upscaler') const activity = useWorkflowTabActivityStore() - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) }) // PM-1575 regression: the canvas-sync gate was wired to @@ -9126,7 +10994,7 @@ describe('AgentPanelRoot workflow binding', () => { await renderAndSend('work here') const activity = useWorkflowTabActivityStore() - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) vi.useFakeTimers() dispatchApiEvent('agent_active_tab', { @@ -9137,7 +11005,7 @@ describe('AgentPanelRoot workflow binding', () => { await vi.advanceTimersByTimeAsync(500) await vi.waitFor(() => - expect(activity.editingTabPath).toBe('workflows/Video test.json') + expect([...activity.editingPaths]).toEqual(['workflows/Video test.json']) ) }) @@ -9149,10 +11017,10 @@ describe('AgentPanelRoot workflow binding', () => { await sendFromComposer('add an upscaler') const activity = useWorkflowTabActivityStore() - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) unmount() - expect(activity.editingTabPath).toBeNull() + expect(activity.editingPaths.size).toBe(0) const other = addTab('workflows/other.json') useAgentWorkflowTabBindingStore().bind('wf-other', other.path) @@ -9167,14 +11035,14 @@ describe('AgentPanelRoot workflow binding', () => { renderWithSelectedTarget() await vi.waitFor(() => - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) ) dispatchApiEvent('agent_message_done', { message_id: 'm-1', thread_id: 'th-1' }) - await vi.waitFor(() => expect(activity.editingTabPath).toBeNull()) + await vi.waitFor(() => expect(activity.editingPaths.size).toBe(0)) }) it("sends the active tab's saved workflow id with the turn", async () => { @@ -9303,20 +11171,20 @@ describe('AgentPanelRoot workflow binding', () => { await sendFromComposer('attached turn') const activity = useWorkflowTabActivityStore() - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) dispatchApiEvent('agent_message_done', { message_id: 'm-1', thread_id: 'th-1' }) - await vi.waitFor(() => expect(activity.editingTabPath).toBeNull()) + await vi.waitFor(() => expect(activity.editingPaths.size).toBe(0)) await userEvent.click( screen.getByRole('button', { name: i18n.global.t('agent.newChat') }) ) await sendFromComposer('detached turn') - expect(activity.editingTabPath).toBe('workflows/current.json') + expect([...activity.editingPaths]).toEqual(['workflows/current.json']) }) it('agent_active_tab activates the bound tab', async () => { @@ -9671,7 +11539,9 @@ describe('AgentPanelRoot workflow binding', () => { useAgentWorkflowTabBindingStore().tabPathFor('wf-other') ).toBeUndefined() expect(useTelemetry()!.trackAgentWorkflowApplied).not.toHaveBeenCalled() - expect(useWorkflowTabActivityStore().editingTabPath).toBe(current.path) + expect([...useWorkflowTabActivityStore().editingPaths]).toEqual([ + current.path + ]) expect(useWorkflowTabActivityStore().creatingTab).toBe(false) expect( Boolean(workflowStore.getWorkflowByPath('workflows/Other.json')) @@ -9747,7 +11617,7 @@ describe('AgentPanelRoot workflow binding', () => { useAgentWorkflowTabBindingStore().tabPathFor('wf-late') ).toBeUndefined() expect(useTelemetry()!.trackAgentWorkflowApplied).not.toHaveBeenCalled() - expect(useWorkflowTabActivityStore().editingTabPath).toBeNull() + expect(useWorkflowTabActivityStore().editingPaths.size).toBe(0) if (kind === 'new') expect(workflowStore.activeWorkflow).toEqual(current) expect( Boolean(workflowStore.getWorkflowByPath('workflows/Late.json')) @@ -9956,16 +11826,18 @@ describe('AgentPanelRoot workflow binding', () => { const activity = useWorkflowTabActivityStore() await vi.waitFor(() => - expect(activity.editingTabPath).toBe( + expect([...activity.editingPaths]).toEqual([ 'workflows/Unsaved Workflow (2).json' - ) + ]) ) dispatchApiEvent('agent_active_tab', { workflow_id: 'wf-a', thread_id: 'th-1' }) await vi.waitFor(() => - expect(activity.editingTabPath).toBe('workflows/Unsaved Workflow.json') + expect([...activity.editingPaths]).toEqual([ + 'workflows/Unsaved Workflow.json' + ]) ) }) diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index 89cb15c24aa..8b907452433 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -3,6 +3,7 @@ import './agentPanel.css' import type { AgentAnswerRequest } from '@comfyorg/ingest-types' import { useClipboard } from '@vueuse/core' +import { maxBy } from 'es-toolkit' import { storeToRefs } from 'pinia' import { computed, @@ -12,6 +13,7 @@ import { onMounted, provide, ref, + shallowRef, watch } from 'vue' import { useI18n } from 'vue-i18n' @@ -89,6 +91,7 @@ import { useFreeUsePlacement } from './experiments/freeUsePlacement' import { useStarterPromptSet } from './experiments/starterPromptSet' import AgentPanel from './components/agent/AgentPanel.vue' import AgentCreditTransitionNotice from './components/agent/AgentCreditTransitionNotice.vue' +import RunNoticeBanner from './components/agent/RunNoticeBanner.vue' import { agentBoundWorkflowIdKey } from './components/agent/agentBoundWorkflowId' import AgentGraphActivityBar from './components/AgentGraphActivityBar.vue' import OnboardingCoach from './components/agent/OnboardingCoach.vue' @@ -103,8 +106,12 @@ import { selectedNodeKey, useCanvasSelection } from './composables/agent/useCanvasSelection' -import type { AgentActiveTabData } from './schemas/agentApiSchema' -import type { ConversationEntry } from './stores/agent/agentConversationStore' +import type { AgentActiveTabData, TurnId } from './schemas/agentApiSchema' +import { toTurnId } from './schemas/agentApiSchema' +import type { + ConversationEntry, + TurnTab +} from './stores/agent/agentConversationStore' import { useAgentConversationStore } from './stores/agent/agentConversationStore' import type { TurnOrigin, @@ -461,6 +468,7 @@ const { selectTarget: onSelectWorkflowTarget, selectReference: onSelectWorkflowReference, restoreTarget: onWorkflowRestored, + adoptTarget: adoptWorkflowTarget, requestReferences: onRequestWorkflowReferences, cancelSelection: cancelWorkflowSelection } = useAgentWorkflowSelection({ @@ -791,8 +799,6 @@ function onWorkflowAdopted( previousWorkflowId: string | null ): void { if (sent === undefined) return - // An unbound tab adopts a workflow only when it was minted for this turn: - // an id that already resolves to an open tab belongs to that tab. const adoptable = sent.id === undefined ? bindingStore.tabPathFor(workflowId) === undefined && @@ -800,7 +806,6 @@ function onWorkflowAdopted( : sent.id === workflowId if (adoptable) { bindingStore.bind(workflowId, sent.tabPath) - tabActivity.setEditing(sent.tabPath) reportWorkflowBound( workflowId, previousWorkflowId, @@ -892,7 +897,7 @@ const { initialize: agentPanelStore.initializeTargetTracking, current: targetWorkflowTurnContext, adopted: onWorkflowAdopted, - restored: onWorkflowRestored, + restored: restoreChatWorkflow, prepare: async () => { try { await refreshCloudWorkflowIds() @@ -1041,57 +1046,80 @@ conversationStore.setCanvasSyncGate( () => crdtStatus.value.outcomes.appliedLive ) -// The resumed turn's own workflow outlives a panel remount (the session -// binds it at ack; only newChat/loadThread reset it), while the active tab -// may have changed since - prefer the bound tab over active-tab derivation. -function resumedTurnTabPath(): string | null { - if (workflowDetached.value) return null +function tabAt(path: string | undefined, status: 'guessed' | 'known'): TurnTab { + const workflow = + path === undefined ? undefined : workflowStore.getWorkflowByPath(path) + return workflow + ? { status, workflowInstanceId: workflow.instanceId } + : { status: 'unknown' } +} + +function turnTab(): TurnTab { + if (workflowDetached.value) + return { + status: agentPanelStore.canRestoreWorkflow ? 'unknown' : 'none' + } const bound = boundWorkflowId.value - if (bound === null) { - // An id-less context means the turn has no workflow at all: attributing - // it to whatever tab happens to be active lights the editing spinner on - // that tab and markModifieds it on completion. Only a context carrying a - // real workflow id may be attributed. - const context = targetWorkflowTurnContext() - return context?.id !== undefined ? context.tabPath : null - } - const boundPath = bindingStore.tabPathFor(bound) - if (boundPath !== undefined) return boundPath const context = targetWorkflowTurnContext() - return context?.id === bound ? context.tabPath : null + if (bound === null) + return tabAt( + context?.id === undefined ? undefined : context.tabPath, + 'guessed' + ) + return tabAt( + bindingStore.tabPathFor(bound) ?? + (context?.id === bound ? context.tabPath : undefined), + 'known' + ) +} + +function adoptRestoredWorkflowTab(workflowId: string): void { + const restored = selectedTarget.value + const threadId = conversationStore.threadId + if ( + restored !== null && + threadId !== null && + bindingStore.tabPathFor(workflowId) === restored.path + ) + conversationStore.adoptThreadTab(threadId, restored.instanceId) } -// Adoption (onWorkflowAdopted) and tab activation (onAgentActiveTab) are the -// primary spinner setters; the non-idle branch only re-arms it after the -// stash/resume flip of a panel remount, where those setters never run. +async function restoreThreadWorkflow( + workflowId: string | undefined, + isCurrent: () => boolean +): Promise { + const restoring = agentPanelStore.canRestoreWorkflow + const ready = await onWorkflowRestored(workflowId, isCurrent) + if (ready && restoring && workflowId !== undefined) + adoptRestoredWorkflowTab(workflowId) + return ready +} + +conversationStore.setTurnTabResolver(turnTab) +conversationStore.onTurnCompleted((path) => tabActivity.markModified(path)) +watch( + () => conversationStore.turnTabs, + (tabs) => tabActivity.setAgentTurnTabs(tabs), + { immediate: true, flush: 'sync' } +) + let wasTurnActive = false watch( [status, conversationTurnId], ([value, turnId]) => { const completedTurn = wasTurnActive && value === 'idle' if (value === 'idle') { - // The immediate idle value on remount is a hydration snapshot, not a - // completed turn. A real idle transition is observed after this pass. if (completedTurn) graphActivity.finishTurn() } else graphActivity.startTurn(turnId) wasTurnActive = value !== 'idle' - if (value === 'idle') { - // A server-side LLM-hop refusal does not reach the browser as a 402. - // Refresh the authoritative effective-funds verdict after every observed - // turn completion so both exhaustion and external top-ups converge. - if (completedTurn && billingType.value === 'workspace') { - void refreshBillingStatus().catch((error: unknown) => { - reportError(error, { - surface: 'agent', - errorType: 'error_refreshing_agent_billing_status' - }) + if (completedTurn && billingType.value === 'workspace') { + void refreshBillingStatus().catch((error: unknown) => { + reportError(error, { + surface: 'agent', + errorType: 'error_refreshing_agent_billing_status' }) - } - const completedPath = tabActivity.editingTabPath - tabActivity.setEditing(null) - if (completedPath !== null) tabActivity.markModified(completedPath) - } else if (tabActivity.editingTabPath === null) - tabActivity.setEditing(resumedTurnTabPath()) + }) + } }, { immediate: true, flush: 'sync' } ) @@ -1122,7 +1150,13 @@ let activeTabChain: Promise = Promise.resolve() function enqueueActiveTab(data: AgentActiveTabData): Promise { const generation = ++activeTabGeneration - const result = activeTabChain.then(() => onAgentActiveTab(data, generation)) + const turnId = + data.message_id === undefined + ? conversationTurnId.value + : toTurnId(data.message_id) + const result = activeTabChain.then(() => + onAgentActiveTab(data, generation, turnId) + ) activeTabChain = result.then(() => undefined) return result } @@ -1193,18 +1227,36 @@ function agentTabFilename(name: string | undefined): string | undefined { return cleaned.length === 0 ? undefined : `${cleaned}.json` } +interface ActiveTabActivation { + stale: () => boolean + showTurnOn: (tab: ComfyWorkflow) => void +} + async function onAgentActiveTab( data: AgentActiveTabData, - generation: number + generation: number, + turnId: TurnId | null ): Promise { const previousWorkflowId = boundWorkflowId.value const stale = () => generation !== activeTabGeneration if (stale()) return false + const activation: ActiveTabActivation = { + stale, + showTurnOn: (tab) => { + if (turnId !== null) + conversationStore.moveTurnToTab(turnId, tab.instanceId) + } + } try { const bound = boundOrOpenWorkflowFor(data.workflow_id) return bound - ? await activateExistingAgentTab(data, bound, previousWorkflowId, stale) - : await createAndActivateAgentTab(data, previousWorkflowId, stale) + ? await activateExistingAgentTab( + data, + bound, + previousWorkflowId, + activation + ) + : await createAndActivateAgentTab(data, previousWorkflowId, activation) } catch (error) { if (stale()) return false bindWorkflow(data.workflow_id) @@ -1227,7 +1279,7 @@ async function activateExistingAgentTab( data: AgentActiveTabData, bound: ComfyWorkflow, previousWorkflowId: string | null, - stale: () => boolean + { stale, showTurnOn }: ActiveTabActivation ): Promise { const opened = await workflowService.openWorkflow(bound) if (stale()) return false @@ -1237,7 +1289,7 @@ async function activateExistingAgentTab( return false } bindingStore.bind(data.workflow_id, bound.path) - if (status.value !== 'idle') tabActivity.setEditing(bound.path) + showTurnOn(bound) bindWorkflow(data.workflow_id) reportWorkflowBound(data.workflow_id, previousWorkflowId, 'active_tab') useTelemetry()?.trackAgentWorkflowApplied({ @@ -1250,7 +1302,7 @@ async function activateExistingAgentTab( async function createAndActivateAgentTab( data: AgentActiveTabData, previousWorkflowId: string | null, - stale: () => boolean + { stale, showTurnOn }: ActiveTabActivation ): Promise { const creatingStartedAt = Date.now() tabActivity.setCreating(true) @@ -1279,7 +1331,7 @@ async function createAndActivateAgentTab( } return false } - if (status.value !== 'idle') tabActivity.setEditing(tab.path) + showTurnOn(tab) bindingStore.bind(data.workflow_id, tab.path) bindWorkflow(data.workflow_id) reportWorkflowBound(data.workflow_id, previousWorkflowId, 'active_tab') @@ -1366,17 +1418,15 @@ onBeforeUnmount(() => { invalidateActiveTabGeneration: () => { ++activeTabGeneration }, - clearEditingTab: () => { - tabActivity.setEditing(null) + clearAgentTurnTabs: () => { + tabActivity.setAgentTurnTabs([]) + }, + resetTurnTabResolver: () => { + conversationStore.setTurnTabResolver(() => ({ status: 'unknown' })) }, clearCreatingTab: () => { tabActivity.setCreating(false) }, - // PM-1575: the store singleton outlives this component. Without resetting - // the gate here, a remount's own setCanvasSyncGate() call is the only - // thing standing between the old (now torn-down) follower's gate and a - // turn resumed in the meantime reading it -- reset to the always-safe - // default instead of leaving whatever this instance last set. resetCanvasSyncGate: () => { conversationStore.setCanvasSyncGate( () => false, @@ -1437,7 +1487,7 @@ const { refreshHistory } = useAgentChatHistoryRefresh({ listThreads: rest.listThreads, history, untitledChat: () => t('agent.untitledChat'), - onFailure: (failure) => { + onFailure: (failure, uiTreatment) => { const error = failure.status === 'failed' ? failure.cause @@ -1448,39 +1498,20 @@ const { refreshHistory } = useAgentChatHistoryRefresh({ tags: failure.status === 'incomplete' ? { reason: failure.reason } : undefined }) - surfaceAgentError( - 'agent_api_failed', - error instanceof Error ? error.message : String(error) - ) - trackAgentError( - 'thread_list_load_failed', - 'pre_acceptance', - 'error_overlay', - { - retryable: - failure.status === 'failed' && isRetryableRequestFailure(error, false) - } - ) + if (uiTreatment === 'error_overlay') + surfaceAgentError( + 'agent_api_failed', + error instanceof Error ? error.message : String(error) + ) + trackAgentError('thread_list_load_failed', 'pre_acceptance', uiTreatment, { + retryable: + failure.status === 'failed' && isRetryableRequestFailure(error, false) + }) } }) const provisionalTitle = ref() -watch( - threadId, - (id, previousId) => { - if ( - id === null || - previousId !== null || - provisionalTitle.value === undefined - ) - return - history.rename(id, provisionalTitle.value) - provisionalTitle.value = undefined - }, - { immediate: true } -) - void refreshHistory() const currentChatReady = computed( @@ -1500,10 +1531,62 @@ const historyGroups = computed(() => { ) }) +type FollowOperation = { + status: 'loading' + generation: number + workflow: ComfyWorkflow + chat: { threadId: string; workflowId: string } | null +} + +let followGeneration = 0 +const followState = shallowRef< + | { status: 'idle' } + | FollowOperation + | { status: 'failed'; workflow: ComfyWorkflow } +>({ status: 'idle' }) + +watch( + threadId, + (id, previousId) => { + if ( + id === null || + previousId !== null || + provisionalTitle.value === undefined + ) + return + const follow = followState.value + if (follow.status !== 'loading' || follow.chat?.threadId !== id) + history.rename(id, provisionalTitle.value) + provisionalTitle.value = undefined + }, + { immediate: true, flush: 'sync' } +) + +const followFailure = computed(() => + followState.value.status === 'failed' ? followState.value.workflow : null +) +const openingWorkflowName = computed(() => + followState.value.status === 'loading' && + followState.value.workflow.path === workflowStore.activeWorkflow?.path + ? followState.value.workflow.filename + : undefined +) + +function retireFollow(): void { + ++followGeneration + followState.value = { status: 'idle' } +} + +function onOpenHistory(): void { + retireFollow() + void refreshHistory() +} + async function onSelectHistory( id: string, isCurrent: () => boolean ): Promise { + retireFollow() provisionalTitle.value = undefined if (currentChatReady.value && id === threadId.value) return onShowTarget(isCurrent, warnRestoreFailed) @@ -1518,6 +1601,155 @@ async function onSelectHistory( return opened } +function latestChatFor(workflowId: string): string | undefined { + return maxBy( + history.sessions.filter((session) => session.workflowId === workflowId), + ({ lastActivityAt }) => lastActivityAt ?? Number.NEGATIVE_INFINITY + )?.id +} + +function chatTargets(workflow: ComfyWorkflow): boolean { + return ( + !agentPanelStore.followsVisibleWorkflow && + selectedTarget.value?.path === workflow.path + ) +} + +function userEngaged(): boolean { + return composerStore.hasDraft || isSending.value || workflowSelecting.value +} + +function followHeldBack(workflow: ComfyWorkflow): boolean { + return workflow.isTemporary || userEngaged() || chatTargets(workflow) +} + +async function refreshedCloudIdFor( + workflow: ComfyWorkflow +): Promise { + await refreshCloudWorkflowIds() + return cloudIdFor(workflow) +} + +async function openFollowedChat( + id: string, + operation: FollowOperation, + workflowId: string, + isCurrent: () => boolean +): Promise { + followState.value = { + ...operation, + chat: { threadId: id, workflowId } + } + const opened = await loadThread(id, isCurrent, { + keepOpenChatUntilLoaded: true + }) + if (!isCurrent()) return + followState.value = opened + ? { status: 'idle' } + : { status: 'failed', workflow: operation.workflow } + if (!opened) return + if (!composerStore.hasDraft) composerStore.setText('') + useTelemetry()?.trackAgentThreadStarted({ source: 'history_select' }) +} + +async function refreshHistoryForFollow( + workflow: ComfyWorkflow, + isCurrent: () => boolean +): Promise { + const historyOutcome = await refreshHistory('none') + if (!isCurrent()) return false + if (historyOutcome === 'failed' || historyOutcome === 'incomplete') + followState.value = { status: 'failed', workflow } + return historyOutcome === 'complete' +} + +async function followTab(workflow: ComfyWorkflow): Promise { + const generation = ++followGeneration + followState.value = { status: 'idle' } + if (followHeldBack(workflow)) return + const operation: FollowOperation = { + status: 'loading', + generation, + workflow, + chat: null + } + followState.value = operation + const isCurrent = () => + generation === followGeneration && + workflowStore.activeWorkflow?.path === workflow.path && + !userEngaged() + try { + const workflowId = + cloudIdFor(workflow) ?? (await refreshedCloudIdFor(workflow)) + if (workflowId === undefined || !isCurrent()) return + const historyReady = await refreshHistoryForFollow(workflow, isCurrent) + if (!historyReady || !isCurrent()) return + const latest = latestChatFor(workflowId) + if (latest !== undefined && latest !== threadId.value) + await openFollowedChat(latest, operation, workflowId, isCurrent) + } finally { + finishFollow(generation) + } +} + +function finishFollow(generation: number): void { + if ( + followState.value.status === 'loading' && + followState.value.generation === generation + ) + followState.value = { status: 'idle' } +} + +function restoreChatWorkflow( + workflowId: string | undefined, + isCurrent: () => boolean +): Promise | boolean { + const followed = followState.value + if ( + followed.status !== 'loading' || + followed.chat?.threadId !== conversationStore.threadId + ) + return restoreThreadWorkflow(workflowId, isCurrent) + adoptWorkflowTarget(followed.workflow, followed.chat.workflowId) + adoptRestoredWorkflowTab(followed.chat.workflowId) + return true +} + +function onRetryFollow(): void { + const failed = followFailure.value + if (failed !== null) void followTab(failed) +} + +onBeforeUnmount(() => { + ++followGeneration +}) + +watch( + () => workflowStore.activeWorkflow, + (workflow) => { + const follow = followState.value + if ( + follow.status !== 'idle' && + (follow.status === 'failed' || follow.workflow.path !== workflow?.path) + ) + retireFollow() + } +) + +workflowStore.onUserActivation((workflow) => void followTab(workflow)) + +watch(userEngaged, (engaged) => { + if (engaged) retireFollow() +}) + +const mountedOn = workflowStore.activeWorkflow +if ( + mountedOn !== null && + selectedTarget.value !== null && + selectedTarget.value.path !== mountedOn.path +) + void followTab(mountedOn) + function buildTranscriptMarkdown(entries: ConversationEntry[]): string { return entries .map((entry) => { @@ -1676,6 +1908,7 @@ function onDeleteHistory(id: string): void { } function onNewChat(source?: 'new_chat_button' | 'history_delete'): void { + retireFollow() provisionalTitle.value = undefined composerStore.invalidateSubmission() cancelWorkflowSelection() @@ -2004,6 +2237,7 @@ async function onPanelDrop(event: DragEvent): Promise { :history-groups="historyGroups" :select-history="onSelectHistory" :current-chat-ready="currentChatReady" + :opening-workflow-name="openingWorkflowName" :session-id="threadId" :custom-title="history.titleFor(threadId) ?? provisionalTitle" :selection-tags="selectionTags" @@ -2051,7 +2285,7 @@ async function onPanelDrop(event: DragEvent): Promise { @start-tour="restartCoach" @toggle-size="agentPanelStore.toggleMaximize()" @close="onClosePanel" - @open-history="refreshHistory()" + @open-history="onOpenHistory" @delete-history="onDeleteHistory" @rename-history="onRenameHistory" @rename-chat="onRenameChat" @@ -2061,6 +2295,12 @@ async function onPanelDrop(event: DragEvent): Promise {