Skip to content

AI-native design editor. Open-source Figma alternative.

fix(ai): rest a Pi or ACP chat's agent when its reply ends (#1130)

Danila Poyarkov73558f7528f7
diff --git a/changes/1130/fixed.md b/changes/1130/fixed.md
new file mode 100644
index 000000000..5c63ce913
--- /dev/null
+++ b/changes/1130/fixed.md
@@ -0,0 +1 @@
+- The agent of a Pi or ACP chat in the desktop app leaves the canvas as soon as a reply finishes, is stopped, or fails, instead of staying at work for up to 20 seconds and keeping your view following it. A tool call already in progress still finishes, but no longer puts the agent back to work.
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index d2bb1aa8c..0feb34f80 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -26,6 +26,7 @@ import { createRunPreview } from '@/app/ai/preview/run'
import { createAITools, currentRun, endRun, recordStep, startRun } from '@/app/ai/tools'
import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'
import { aiToolOverrides } from '@/app/ai/tools/preferences'
+import { restAgents } from '@/app/automation/agents'
import { diagnosticErrorDetails } from '@/app/diagnostics'
import {
recordChatCompleted,
@@ -373,9 +374,17 @@ export function createChatSessionManager({
const messages = initialMessages ?? currentChatMessages.get(store)
const diagnosticContext: AIDiagnosticContext = { sessionId, runId: crypto.randomUUID() }
let transport: ChatTransport<UIMessage>
- if (isACPProvider.value) transport = await createActiveACPTransport()
- else if (isHarnessProvider.value) transport = await createActiveHarnessTransport(sessionId)
- else transport = await createTransport(store, diagnosticContext)
+ // An ACP or Pi chat's tool calls show as an agent of that kind (`src/app/automation/agents.ts`).
+ let agentKind: 'acp' | 'harness' | null = null
+ if (isACPProvider.value) {
+ agentKind = 'acp'
+ transport = await createActiveACPTransport()
+ } else if (isHarnessProvider.value) {
+ agentKind = 'harness'
+ transport = await createActiveHarnessTransport(sessionId)
+ } else {
+ transport = await createTransport(store, diagnosticContext)
+ }
const created: Chat<UIMessage> = new Chat<UIMessage>({
transport: {
sendMessages: (options) => {
@@ -394,6 +403,8 @@ export function createChatSessionManager({
},
onFinish: (event) => {
handleChatFinish(diagnosticContext, event)
+ // The reply is over, however it ended; its agent rests instead of waiting it out.
+ if (agentKind) restAgents(agentKind)
if (event.isAbort || event.isDisconnect || event.isError) {
void settleEndedReply(created, store, event.message.id, event.isAbort)
}
diff --git a/src/app/automation/agents.ts b/src/app/automation/agents.ts
index 4fda748a2..c4c1b8360 100644
--- a/src/app/automation/agents.ts
+++ b/src/app/automation/agents.ts
@@ -33,6 +33,9 @@ export function readAgentSession(value: unknown): AgentSession | null {
interface SessionAgent {
handle: AgentHandle
+ kind: AgentSession['kind']
+ /** Counts the times its chat's replies ended; a tool call from an earlier reply is ignored. */
+ replies: number
idleTimer?: ReturnType<typeof setTimeout>
goneTimer?: ReturnType<typeof setTimeout>
}
@@ -48,7 +51,11 @@ function sessionAgent(store: EditorStore, session: AgentSession): SessionAgent {
}
let agent = agents.get(store)
if (!agent) {
- agent = { handle: addAgent(store, session.kind, session.client || undefined) }
+ agent = {
+ handle: addAgent(store, session.kind, session.client || undefined),
+ kind: session.kind,
+ replies: 0
+ }
agents.set(store, agent)
}
return agent
@@ -105,11 +112,15 @@ export function touchedNodeIds(store: EditorStore, args: unknown, result: unknow
})
}
-/** A session started a tool call on `pageId`: its agent shows it is at work there. */
-export function agentStarted(store: EditorStore, session: AgentSession, pageId: string): void {
+/**
+ * A session started a tool call on `pageId`: its agent shows it is at work there. Returns the
+ * reply the call belongs to, for `agentFinished`.
+ */
+export function agentStarted(store: EditorStore, session: AgentSession, pageId: string): number {
const agent = sessionAgent(store, session)
agent.handle.update({ status: 'thinking', pageId })
restartTimers(store, session.session, agent)
+ return agent.replies
}
/**
@@ -119,9 +130,12 @@ export function agentStarted(store: EditorStore, session: AgentSession, pageId:
export function agentFinished(
store: EditorStore,
session: AgentSession,
- work: { pageId: string; nodeIds: readonly string[]; edited: boolean }
+ work: { pageId: string; nodeIds: readonly string[]; edited: boolean; reply: number }
): void {
const agent = sessionAgent(store, session)
+ // A call that was running when its chat's reply ended lands without bringing the agent back
+ // or moving it away from what a later reply works on.
+ if (work.reply !== agent.replies) return
const placement = agentPlacement(store, work.nodeIds, work.pageId)
agent.handle.update({
status: work.edited ? 'editing' : 'thinking',
@@ -131,6 +145,22 @@ export function agentFinished(
restartTimers(store, session.session, agent)
}
+/**
+ * The app's own ACP or Pi chat ended a reply, finished, stopped, or failed: that chat's agents
+ * rest now rather than when their idle timer runs out. Only the app's chats send these kinds
+ * (`src/app/integrations/mcp`), so no outside MCP client is touched.
+ */
+export function restAgents(kind: Exclude<AgentSession['kind'], 'mcp'>): void {
+ for (const agents of sessions.values()) {
+ for (const agent of agents.values()) {
+ if (agent.kind !== kind) continue
+ clearTimeout(agent.idleTimer)
+ agent.replies++
+ agent.handle.update({ status: 'idle', cursor: undefined, selection: undefined })
+ }
+ }
+}
+
/** The MCP server says a session ended: its agents leave every document. */
export function endAgentSession(sessionId: string): void {
// Removing entries while iterating a Map is safe: visited ones stay visited.
diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.ts
index b9397628e..cf19db23a 100644
--- a/src/app/automation/bridge/tool-handlers.ts
+++ b/src/app/automation/bridge/tool-handlers.ts
@@ -40,10 +40,11 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {
// A call from an MCP session shows as that session's agent, working where the call works.
const session = readAgentSession((args as { agent?: unknown }).agent)
- if (session) agentStarted(target.store, session, target.pageId)
+ const reply = session ? agentStarted(target.store, session, target.pageId) : 0
const response = await runTool(target, toolName, toolArgs)
if (session) {
agentFinished(target.store, session, {
+ reply,
pageId: target.pageId,
nodeIds: touchedNodeIds(target.store, toolArgs, response.result),
edited: response.edited
diff --git a/tests/app/automation/agents.test.ts b/tests/app/automation/agents.test.ts
index 6992f64c3..8d55837cf 100644
--- a/tests/app/automation/agents.test.ts
+++ b/tests/app/automation/agents.test.ts
@@ -9,6 +9,7 @@ import {
agentStarted,
endAgentSession,
readAgentSession,
+ restAgents,
touchedNodeIds,
type AgentSession
} from '@/app/automation/agents'
@@ -18,6 +19,7 @@ import { presenceOf } from '@/app/presence/registry'
import { expectDefined } from '#tests/helpers/assert'
const claude: AgentSession = { session: 'session-1', kind: 'mcp', client: 'claude-code' }
+const pi: AgentSession = { session: 'session-pi', kind: 'harness', client: 'pi' }
let store: EditorStore
@@ -28,6 +30,7 @@ beforeEach(() => {
afterEach(() => {
endAgentSession(claude.session)
+ endAgentSession(pi.session)
store.preparationController.dispose()
jest.useRealTimers()
})
@@ -50,11 +53,12 @@ describe('MCP sessions as agents', () => {
test('the agent points at what a call reads and what it edits', () => {
const card = store.graph.createNode('FRAME', pageId(), { x: 40, y: 60, width: 100, height: 80 })
- agentStarted(store, claude, pageId())
+ const reply = agentStarted(store, claude, pageId())
agentFinished(store, claude, {
pageId: pageId(),
nodeIds: touchedNodeIds(store, { id: card.id }, { name: 'Card' }),
- edited: false
+ edited: false,
+ reply
})
expect(agents()[0]).toMatchObject({
status: 'thinking',
@@ -66,7 +70,8 @@ describe('MCP sessions as agents', () => {
agentFinished(store, claude, {
pageId: pageId(),
nodeIds: touchedNodeIds(store, {}, { results: [{ id: made.id }] }),
- edited: true
+ edited: true,
+ reply
})
expect(agents()[0]).toMatchObject({ status: 'editing', selection: [made.id] })
})
@@ -74,7 +79,8 @@ describe('MCP sessions as agents', () => {
test('the agent works on the page of the layers it touched', () => {
const other = store.graph.addPage('Other')
const node = store.graph.createNode('RECTANGLE', other.id, {})
- agentFinished(store, claude, { pageId: pageId(), nodeIds: [node.id], edited: true })
+ const reply = agentStarted(store, claude, pageId())
+ agentFinished(store, claude, { pageId: pageId(), nodeIds: [node.id], edited: true, reply })
expect(agents()[0]).toMatchObject({ pageId: other.id, cursor: { pageId: other.id } })
})
@@ -117,3 +123,34 @@ describe('MCP sessions as agents', () => {
expect(readAgentSession(undefined)).toBeNull()
})
})
+
+describe("the app's own ACP and Pi chats", () => {
+ const status = (session: AgentSession) =>
+ agents().find((agent) => agent.kind === session.kind)?.status
+
+ test("when a chat's reply ends, its agent rests at once and outside clients keep working", () => {
+ agentStarted(store, pi, pageId())
+ agentStarted(store, claude, pageId())
+
+ restAgents('harness')
+
+ expect(status(pi)).toBe('idle')
+ expect(status(claude)).toBe('thinking')
+ })
+
+ test('a call that was running when the reply ended does not bring the agent back', () => {
+ const card = store.graph.createNode('FRAME', pageId(), {})
+ const late = agentStarted(store, pi, pageId())
+ restAgents('harness')
+
+ agentFinished(store, pi, { pageId: pageId(), nodeIds: [card.id], edited: true, reply: late })
+ expect(status(pi)).toBe('idle')
+
+ // The chat's next reply calls a tool, and the earlier call landing then leaves it be.
+ const next = agentStarted(store, pi, pageId())
+ agentFinished(store, pi, { pageId: pageId(), nodeIds: [card.id], edited: true, reply: late })
+ expect(status(pi)).toBe('thinking')
+ agentFinished(store, pi, { pageId: pageId(), nodeIds: [card.id], edited: true, reply: next })
+ expect(status(pi)).toBe('editing')
+ })
+})