PluginProbe
Extendify / 3.2.3
Extendify v3.2.3
3.2.3 3.2.2 3.2.1 3.2.0 3.1.6 3.1.5 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 3.0.6 3.0.5 3.0.4 trunk 0.1.0 0.10.0 0.10.1 0.10.2 0.11.0 0.11.1 0.2.0 0.3.0 0.3.1 0.4.0 All 129 releases
← All changes | src/Agent/Agent.jsx +509 -147 3.1.2 → 3.2.3 View file →
@@ -1,26 +1,42 @@
1 1 import {
2 2 callTool,
3 + handleCanvas,
3 4 handleWorkflow,
4 5 pickWorkflow,
5 6 recordAgentActivity,
6 7 } from '@agent/api';
7 8 import { Chat } from '@agent/Chat';
9 +import {
10 + Canvas,
11 + useCanvasAssist,
12 + useCanvasOpen,
13 +} from '@agent/components/Canvas';
8 14 import { ChatInput } from '@agent/components/ChatInput';
9 15 import { ChatMessages } from '@agent/components/ChatMessages';
16 +import { StatusIndicator } from '@agent/components/messages/StatusIndicator';
10 17 import { UsageMessage } from '@agent/components/messages/UsageMessage';
11 -import { PageDocument } from '@agent/components/PageDocument';
18 +import { useFollowUpHistory } from '@agent/follow-ups/history';
19 +import {
20 + cardMessageIndex,
21 + pickNextCard,
22 + toolCallsThisRun,
23 +} from '@agent/follow-ups/pick-next';
12 24 import { useLockPost } from '@agent/hooks/useLockPost';
25 +import { isAbilityTool, isAbilityWorkflow } from '@agent/lib/abilities';
13 26 import {
14 - abilityAffectsCurrentPage,
15 - isAbilityWorkflow,
16 -} from '@agent/lib/abilities';
17 -import { getRedirectUrl } from '@agent/lib/redirects';
27 + getClientToolFallbackReply,
28 + getClientTools,
29 +} from '@agent/lib/client-tools';
30 +import { localPickWorkflow } from '@agent/lib/local-pick';
31 +import { doReload } from '@agent/lib/reload';
32 +import { useCanvasStore } from '@agent/state/canvas';
18 33 import { useChatStore } from '@agent/state/chat';
19 34 import { useGlobalStore } from '@agent/state/global';
20 35 import { useStatusStore } from '@agent/state/status';
21 -import { useSuggestionsStore } from '@agent/state/suggestions';
22 36 import { useWorkflowStore } from '@agent/state/workflows';
37 +import { hasRunComponent } from '@agent/workflows/abilities/components/run';
38 +import startOnboardingWorkflow from '@agent/workflows/misc/start-onboarding';
23 39 import { useQuickEditStore } from '@quick-edit/state/store';
24 40 import { digest } from '@shared/api/digest';
25 41 import {
26 42 useCallback,
@@ -28,18 +44,48 @@
28 44 useMemo,
29 45 useRef,
30 46 useState,
31 47 } from '@wordpress/element';
32 -import { __ } from '@wordpress/i18n';
48 +import { __, _n, sprintf } from '@wordpress/i18n';
33 49
34 50 const devmode = window.extSharedData.devbuild;
51 +// Logged with tool errors: the banner sends users here and support needs to
52 +// know which site the console they paste came from.
53 +const { siteId } = window.extSharedData;
35 54 // Used to abort when wf canceled - reset in cleanup()
36 55 let controller = new AbortController();
37 56 const { postId } = window?.extAgentData?.context || {};
38 57
58 +// Floor a resolution so its result doesn't re-render over the still-animating
59 +// scroll-to-top, which leaves the chat scrolled to the wrong place.
60 +const withMinDuration = async (promise, ms) => {
61 + const [result] = await Promise.all([
62 + promise,
63 + new Promise((resolve) => setTimeout(resolve, ms)),
64 + ]);
65 + return result;
66 +};
67 +
68 +// cleanup() swaps in a fresh controller; a signal read after the wait is never aborted.
69 +const canceledDuring = async (ms) => {
70 + const { signal } = controller;
71 + await new Promise((resolve) => setTimeout(resolve, ms));
72 + return signal.aborted;
73 +};
74 +
75 +const nextSteps = (workflowId, status, messages) => {
76 + if (status === 'completed') {
77 + useFollowUpHistory.getState().markDone(workflowId);
78 + }
79 + const card = pickNextCard({ workflowId, status, messages });
80 + return card
81 + ? { followUp: card.id, followUpData: card.data }
82 + : { followUp: null };
83 +};
84 +
39 85 export const Agent = () => {
40 - const { addMessage, popMessage } = useChatStore();
41 - const { pushStatus, clearStatuses } = useStatusStore();
86 + const { addMessage, updateMessage, popMessage, messages } = useChatStore();
87 + const { pushStatus, clearStatuses, leavingPage } = useStatusStore();
42 88 const {
43 89 mergeWorkflowData,
44 90 getWorkflow,
45 91 getWorkflowByExample,
@@ -47,12 +93,12 @@
47 93 setWorkflow,
48 94 setWhenFinishedToolProps,
49 95 whenFinishedToolProps,
50 96 getAvailableWorkflows,
97 + requireBlock,
51 98 } = useWorkflowStore();
52 99 const block = useQuickEditStore((s) => s.agentBlock);
53 100 const setBlock = useQuickEditStore((s) => s.setAgentBlock);
54 - const workflowIds = getAvailableWorkflows().map((w) => w.id);
55 101 const { open, setOpen, updateRetryAfter, isChatAvailable } = useGlobalStore();
56 102 useLockPost({ postId, enabled: !!open });
57 103 const [canType, setCanType] = useState(true);
58 104 const agentWorking = useRef(false);
@@ -57,68 +103,118 @@
57 103 const [canType, setCanType] = useState(true);
58 104 const agentWorking = useRef(false);
59 105 const toolWorking = useRef(false);
60 106 const retrying = useRef(false);
61 - const [waitingOnToolOrUser, setWaitingOnToolOrUser] = useState(false);
107 + // Starting false would re-run the agent's last turn on every reload.
108 + const [waitingOnToolOrUser, setWaitingOnToolOrUser] = useState(() => {
109 + const last = useChatStore.getState().messages.at(-1);
110 + if (last?.type === 'tool') return !('result' in (last.details ?? {}));
111 + return last?.type === 'message' && last.details?.role === 'assistant';
112 + });
62 113 const [loop, setLoop] = useState(0);
63 114 const workflow = getWorkflow();
115 + const canvasOpen = useCanvasOpen();
116 + const canvasAssist = useCanvasAssist();
117 + const canvasNoticeShown = useRef(false);
64 118 const chatAvailable = useMemo(() => isChatAvailable(), [isChatAvailable]);
65 - const { addSuggestions, getSuggestions } = useSuggestionsStore();
119 + // Options render only while their message is last; a reply dismisses them.
120 + const lastMessage = messages.at(-1);
121 + const qaSuggestions =
122 + lastMessage?.type === 'message' &&
123 + lastMessage.details?.role === 'assistant' &&
124 + Array.isArray(lastMessage.details?.qaSuggestions)
125 + ? lastMessage.details.qaSuggestions
126 + : null;
66 127
128 + useEffect(() => {
129 + const { messages, updateMessage } = useChatStore.getState();
130 + const index = cardMessageIndex(messages);
131 + const { id, details } = messages[index] ?? {};
132 + if (!id || details.followUp !== undefined || details.followUpClosed) return;
133 + const { workflowId, status } = details;
134 + const steps = nextSteps(workflowId, status, messages.slice(0, index));
135 + if (steps.followUp) updateMessage(id, steps);
136 + }, []);
137 +
138 + // Without this the input stays disabled for as long as the canvas is open.
139 + useEffect(() => {
140 + if (canvasOpen && canvasAssist) setCanType(true);
141 + // A workflow reached by example carries no sessionId to key this on.
142 + if (!canvasOpen) canvasNoticeShown.current = false;
143 + }, [canvasOpen, canvasAssist]);
144 +
67 145 const cleanup = useCallback(() => {
68 146 setCanType(true);
69 147 agentWorking.current = false;
70 148 setWaitingOnToolOrUser(false);
71 149 controller = new AbortController();
72 - block && setBlock(null);
150 + const { agentBlock, setCommittedSelection } = useQuickEditStore.getState();
151 + agentBlock && setBlock(null);
152 + // A class or pin left up freezes Quick Edit hover site-wide.
153 + document
154 + .querySelector('.wp-site-blocks')
155 + ?.classList.remove(
156 + 'extendify-agent-working',
157 + 'extendify-agent-busy',
158 + 'extendify-agent-waiting',
159 + 'extendify-agent-task',
160 + );
161 + setCommittedSelection(null);
73 162 clearStatuses();
74 163 window.dispatchEvent(new Event('extendify-agent:remove-block-highlight'));
75 - // scrollIntoView below walks up and scrolls the page itself,
76 - // fighting useLayoutShift's scroll restore when closing.
77 - if (!useGlobalStore.getState().open) return;
78 - const c = Array.from(
79 - document.querySelectorAll(
80 - '#extendify-agent-chat-scroll-area div:last-child',
81 - ),
82 - )?.at(-1);
83 - c?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
84 - c?.scrollBy({ top: -5, behavior: 'smooth' });
85 - }, [setBlock, block, clearStatuses]);
164 + }, [setBlock, clearStatuses]);
86 165
166 + useEffect(() => {
167 + const handle = ({ detail }) => {
168 + if (!detail?.id) return;
169 + updateMessage(detail.id, { result: detail.result });
170 + setWaitingOnToolOrUser(false);
171 + agentWorking.current = false;
172 + // The main loop parks on a staged tool; leaving one strands the run.
173 + setWhenFinishedToolProps(null);
174 + setLoop((prev) => prev + 1);
175 + };
176 + window.addEventListener('extendify-agent:client-tool-done', handle);
177 + return () =>
178 + window.removeEventListener('extendify-agent:client-tool-done', handle);
179 + }, [updateMessage, setWhenFinishedToolProps]);
180 +
87 181 const findAgent = useCallback(
88 182 async (options = {}) => {
89 183 pushStatus('calling-agent');
90 - const response = await pickWorkflow({
91 - workflows: workflowIds,
92 - options: { signal: controller.signal, ...options },
93 - }).catch(async (error) => {
94 - devmode && console.error(error);
95 - if (error?.response?.status === 429) {
96 - updateRetryAfter(error?.response?.headers?.get('Retry-After'));
97 - setCanType(false);
98 - pushStatus('credits-exhausted');
184 + const { signal } = controller;
185 + const response = await withMinDuration(
186 + pickWorkflow({
187 + // A mid-turn drop clears the block after this closure was made.
188 + workflows: getAvailableWorkflows().map((w) => w.id),
189 + options: { signal, ...options },
190 + }).catch(async (error) => {
191 + devmode && console.error(error);
192 + if (error?.response?.status === 429) {
193 + updateRetryAfter(error?.response?.headers?.get('Retry-After'));
194 + setCanType(false);
195 + pushStatus('credits-exhausted');
196 + return;
197 + }
198 + setCanType(true);
199 + if (error === 'Workflow aborted') return;
200 +
201 + await new Promise((resolve) => setTimeout(resolve, 1000));
202 + addMessage('message', {
203 + role: 'assistant',
204 + // translators: This message is shown when the AI agent fails to find a suitable workflow.
205 + content: __(
206 + 'Something went wrong while trying to start this request. Please try again.',
207 + 'extendify-local',
208 + ),
209 + error: true,
210 + });
99 211 return;
100 - }
101 - setCanType(true);
102 - if (error === 'Workflow aborted') {
103 - addMessage('workflow', { status: 'canceled' });
104 - return;
105 - }
212 + }),
213 + 500,
214 + );
215 + if (!response || signal.aborted) return;
106 216
107 - await new Promise((resolve) => setTimeout(resolve, 1000));
108 - addMessage('message', {
109 - role: 'assistant',
110 - // translators: This message is shown when the AI agent fails to find a suitable workflow.
111 - content: __(
112 - 'Something went wrong while trying to start this request. Please try again.',
113 - 'extendify-local',
114 - ),
115 - error: true,
116 - });
117 - return;
118 - });
119 - if (!response) return;
120 -
121 217 const { workflow: wf, reply } = response;
122 218 if (wf?.id) setWorkflow(wf);
123 219 if (reply) {
124 220 const data = { role: 'assistant', content: reply, agent: wf?.agent };
@@ -125,23 +221,114 @@
125 221 addMessage('message', data);
126 222 }
127 223 if (!wf?.id) setCanType(true);
128 224 },
129 - [addMessage, pushStatus, updateRetryAfter, setWorkflow, workflowIds],
225 + [
226 + addMessage,
227 + pushStatus,
228 + updateRetryAfter,
229 + setWorkflow,
230 + getAvailableWorkflows,
231 + ],
130 232 );
131 233
234 + // The backend caps tool runs; nothing here bounds the loop.
235 + const handleCanvasMessage = useCallback(async () => {
236 + setCanType(false);
237 + // cleanup() replaces the controller, so a cancel is lost between passes.
238 + const { signal } = controller;
239 + while (!signal.aborted) {
240 + pushStatus('agent-working');
241 + const response = await handleCanvas({
242 + toolId: whenFinishedToolProps?.id,
243 + sessionId: workflow?.sessionId,
244 + abilities: workflow?.abilities,
245 + options: { signal },
246 + }).catch((error) => {
247 + if (error === 'Workflow aborted') return null;
248 + const { sessionId } = workflow || {};
249 + digest({
250 + error,
251 + details: { source: 'agent', caller: 'handle-canvas', sessionId },
252 + });
253 + devmode && console.error(error);
254 + return { error: error.message };
255 + });
256 + // A request that settled before the abort still resolves with a reply.
257 + if (!response || signal.aborted) break;
258 + if (response.error) {
259 + addMessage('message', {
260 + role: 'assistant',
261 + // translators: Shown when the AI agent could not answer a question about the form it has open on screen.
262 + content: __(
263 + 'Sorry, something went wrong. Please try asking again.',
264 + 'extendify-local',
265 + ),
266 + error: true,
267 + });
268 + break;
269 + }
270 + if (response.reply) {
271 + addMessage('message', {
272 + role: 'assistant',
273 + content: response.reply,
274 + followup: !!response.tool,
275 + agent: workflow?.agent,
276 + });
277 + }
278 + // The model is never told what is on screen around the canvas.
279 + if (response.cannotHelp && !canvasNoticeShown.current) {
280 + canvasNoticeShown.current = true;
281 + addMessage('canvas-notice', {});
282 + }
283 + if (!response.tool) break;
284 + const { id, inputs, labels } = response.tool;
285 + pushStatus('tool-started', labels?.started);
286 + const result = await callTool({
287 + tool: id,
288 + inputs,
289 + abilities: workflow?.abilities,
290 + }).catch((error) => {
291 + const { sessionId } = workflow || {};
292 + digest({
293 + error,
294 + details: { source: 'agent', caller: `canvas: ${id}`, sessionId },
295 + });
296 + console.error(`Extendify agent tool error: ${id}`, { siteId, error });
297 + return { error: { message: error?.message, code: error?.code } };
298 + });
299 + addMessage('tool', { id, inputs, result, label: labels?.confirm });
300 + }
301 + setCanType(true);
302 + }, [addMessage, pushStatus, whenFinishedToolProps, workflow]);
303 +
132 304 const handleSubmit = useCallback(
133 - async (message) => {
134 - // Save any in-flight QE canvas edits before the agent runs so
135 - // the user doesn't lose their work to a workflow that touches
136 - // the same block. No-op when no QE canvas is mounted.
137 - window.dispatchEvent(
138 - new CustomEvent('extendify-quick-edit:agent-submit'),
139 - );
305 + async (message, { hidden = false, step } = {}) => {
306 + // chat-submit events skip the textarea; disabling it isn't enough.
307 + if (useQuickEditStore.getState().selected) return;
308 + if (whenFinishedToolProps?.processing) return;
140 309 setWaitingOnToolOrUser(false);
141 310 agentWorking.current = false;
142 - addMessage('message', { role: 'user', content: message });
311 + if (step) addMessage('tool', { ...step, inputs: {}, fromCard: true });
312 + addMessage('message', { role: 'user', content: message, hidden });
143 313
314 + // Without this a typed message would drop the workflow and close the canvas.
315 + if (canvasOpen && canvasAssist) return handleCanvasMessage();
316 +
317 + // A staged tool the user walked away from still owes its receipt.
318 + if (workflow?.id && whenFinishedToolProps?.id) {
319 + const { answerId, whenFinishedTool } =
320 + whenFinishedToolProps.agentResponse || {};
321 + addMessage('workflow', {
322 + status: 'canceled',
323 + label: whenFinishedTool?.labels?.cancel,
324 + agent: workflow.agent,
325 + workflowId: workflow.id,
326 + answerId,
327 + followUp: null,
328 + });
329 + }
330 +
144 331 // Let some phrases auto load workflows
145 332 const bypass = getWorkflowByExample(message);
146 333 if (bypass?.example?.agentResponse) {
147 334 // whenFinishedTool → inline input UI; none → ask for a typed reply.
@@ -166,13 +353,25 @@
166 353 mergeWorkflowData(wfData);
167 354 return;
168 355 }
169 356
357 + // Skip the network find-agent when the staged block makes the edit certain.
358 + const localPick = localPickWorkflow({ block });
359 + if (localPick) {
360 + if (await canceledDuring(500)) return;
361 + setWorkflow(localPick);
362 + return;
363 + }
364 +
170 365 await findAgent().catch((e) => devmode && console.error(e));
171 366 },
172 367 [
173 368 addMessage,
369 + block,
370 + canvasAssist,
371 + canvasOpen,
174 372 findAgent,
373 + handleCanvasMessage,
175 374 mergeWorkflowData,
176 375 whenFinishedToolProps,
177 376 setWorkflow,
178 377 workflow,
@@ -188,9 +387,9 @@
188 387 if (!agentResponse) return;
189 388 setWorkflow(workflow);
190 389 setCanType(false);
191 390 agentWorking.current = true;
192 - await new Promise((resolve) => setTimeout(resolve, 750));
391 + if (await canceledDuring(750)) return;
193 392 addMessage('message', {
194 393 role: 'assistant',
195 394 content: agentResponse.reply,
196 395 });
@@ -214,12 +413,14 @@
214 413 // Without this the loop calls the backend before the user has typed.
215 414 setWaitingOnToolOrUser(true);
216 415 setCanType(false);
217 416 agentWorking.current = true;
218 - await new Promise((resolve) => setTimeout(resolve, 750));
417 + if (await canceledDuring(750)) return;
219 418 addMessage('message', {
220 419 role: 'assistant',
221 420 content: agentResponse.reply,
421 + // A workflow example can carry its own suggestions; none still asks.
422 + qaSuggestions: agentResponse.qaSuggestions ?? [],
222 423 });
223 424 agentWorking.current = false;
224 425 setCanType(true);
225 426 recordAgentActivity({
@@ -232,21 +433,30 @@
232 433 useEffect(() => {
233 434 // Allow external messages to trigger the agent
234 435 const handleMessage = ({ detail }) => {
235 436 if (!detail?.message) return;
236 - handleSubmit(detail.message);
437 + const { message, hidden, step } = detail;
438 + handleSubmit(message, { hidden, step });
237 439 };
238 440 // Allow external code to clear the block and workflow
239 441 const handleCleanup = () => {
442 + // cleanup() resets canType and agentWorking, so read them before it runs.
443 + const interrupted = agentWorking.current || !canType;
240 444 controller.abort('Workflow aborted');
241 445 cleanup();
446 + // Deferred a frame: the input stays disabled until the cancel lands.
447 + requestAnimationFrame(() =>
448 + document.querySelector('#extendify-agent-chat-textarea')?.focus(),
449 + );
242 450
243 - if (!workflow?.id) return;
451 + // An options panel can outlive its workflow; cancel must still clear it.
452 + if (!workflow?.id && !qaSuggestions && !interrupted) return;
244 453 setWorkflow(null);
245 454 addMessage('workflow', {
246 455 status: 'canceled',
247 - agent: workflow.agent,
248 - workflowId: workflow.id,
456 + agent: workflow?.agent,
457 + workflowId: workflow?.id,
458 + ...nextSteps(workflow?.id, 'canceled'),
249 459 });
250 460 return;
251 461 };
252 462 window.addEventListener('extendify-agent:cancel-workflow', handleCleanup);
@@ -257,22 +467,59 @@
257 467 handleCleanup,
258 468 );
259 469 window.removeEventListener('extendify-agent:chat-submit', handleMessage);
260 470 };
261 - }, [handleSubmit, cleanup, setWorkflow, addMessage, workflow]);
471 + }, [
472 + handleSubmit,
473 + cleanup,
474 + setWorkflow,
475 + addMessage,
476 + workflow,
477 + qaSuggestions,
478 + canType,
479 + ]);
262 480
481 + // Dispatching before chat-submit has a listener drops the workflow.
482 + useEffect(() => {
483 + if (!startOnboardingWorkflow.available()) return;
484 + window.dispatchEvent(
485 + new CustomEvent('extendify-agent:chat-submit', {
486 + detail: { message: startOnboardingWorkflow.example.text, hidden: true },
487 + }),
488 + );
489 + }, []);
490 +
491 + // ChatMessages hides a confirm restored by a reload; left open, the workflow would sit unfinishable.
492 + useEffect(() => {
493 + const { getWorkflow, reloadedToolProps } = useWorkflowStore.getState();
494 + const { whenFinished, needsRedirect } = getWorkflow() ?? {};
495 + if (!reloadedToolProps?.id || !whenFinished?.component) return;
496 + if (whenFinished.canvas || needsRedirect?.()) return;
497 + window.dispatchEvent(new Event('extendify-agent:cancel-workflow'));
498 + }, []);
499 +
263 500 // Handle whenFinished component confirm/cancel
264 501 useEffect(() => {
265 502 const handleConfirm = async ({ detail }) => {
266 503 if (toolWorking.current) return;
267 - setWhenFinishedToolProps(null);
268 - pushStatus('workflow-tool-processing');
269 504 toolWorking.current = true;
270 505 const { data, whenFinishedToolProps, shouldRefreshPage, redirectUrl } =
271 506 detail ?? {};
272 - const { whenFinishedTool, answerId, redirectTo } =
507 + // Staged until the tool returns, so the chat shows it saving.
508 + setWhenFinishedToolProps(
509 + whenFinishedToolProps
510 + ? { ...whenFinishedToolProps, processing: true }
511 + : null,
512 + );
513 + const { whenFinishedTool, answerId } =
273 514 whenFinishedToolProps?.agentResponse || {};
274 515 const { id, labels } = whenFinishedTool || {};
516 + // Staged unanswered so its own component can show the run in progress.
517 + const runMessageId = id ? addMessage('tool', { id, inputs: data }) : null;
518 + // In the chat, the saving state shows this label instead.
519 + if (!hasRunComponent(id) && workflow?.whenFinished?.canvas) {
520 + pushStatus('workflow-tool-processing', labels?.started);
521 + }
275 522 // Not all workflows have a tool at the end (e.g. tours)
276 523 const toolResponse = await callTool?.({ tool: id, inputs: data }).catch(
277 524 (error) => {
278 525 const { sessionId } = workflow || {};
@@ -283,17 +530,42 @@
283 530 caller: `when-finished: ${id}`,
284 531 sessionId,
285 532 },
286 533 });
287 - devmode && console.error(error);
534 + console.error(`Extendify agent tool error: ${id}`, { siteId, error });
288 535 return { error: { message: error?.message, code: error?.code } };
289 536 },
290 537 );
291 538 toolWorking.current = false;
539 + setWhenFinishedToolProps(null);
540 + if (runMessageId) updateMessage(runMessageId, { result: toolResponse });
541 + if (toolResponse?.refused) {
542 + await new Promise((resolve) => setTimeout(resolve, 1000));
543 + const refusalMessages = {
544 + // translators: Shown when the AI agent's edit produced no change to the block, which is unexpected.
545 + 'no-op': __(
546 + "That edit came back unchanged, which wasn't expected. Please try rephrasing what you'd like to change.",
547 + 'extendify-local',
548 + ),
549 + };
550 + addMessage('message', {
551 + role: 'assistant',
552 + content:
553 + refusalMessages[toolResponse.reason] ??
554 + // translators: Shown when the AI agent could not safely apply an edit to the selected block.
555 + __(
556 + "I couldn't safely apply that edit to the selected block. Please re-select the block and try again.",
557 + 'extendify-local',
558 + ),
559 + error: true,
560 + });
561 + setWorkflow(null);
562 + cleanup();
563 + return;
564 + }
292 565 // Only loop back on error, so the model can recover. A clean
293 566 // whenFinished tool means the workflow is done.
294 567 if (toolResponse?.error) {
295 - addMessage('tool', { id, inputs: data, result: toolResponse });
296 568 setWaitingOnToolOrUser(false);
297 569 agentWorking.current = false;
298 570 setLoop((prev) => prev + 1);
299 571 return;
@@ -298,11 +570,13 @@
298 570 setLoop((prev) => prev + 1);
299 571 return;
300 572 }
301 573
302 - // Later runs of this workflow need the result (e.g. created ids).
303 - if (id) addMessage('tool', { id, inputs: data, result: toolResponse });
304 - addSuggestions(whenFinishedToolProps.agentResponse?.recommendations);
574 + // Reloading here unmounts a run component still watching its ability finish.
575 + const refreshForAbility =
576 + isAbilityTool(id) && shouldRefreshPage !== false;
577 + const willReload = redirectUrl || shouldRefreshPage || refreshForAbility;
578 + // A card shown now would flash just before the reload.
305 579 addMessage('workflow', {
306 580 status: 'completed',
307 581 label: labels?.confirm,
308 582 agent: workflow.agent,
@@ -307,25 +581,37 @@
307 581 label: labels?.confirm,
308 582 agent: workflow.agent,
309 583 workflowId: workflow.id,
310 584 answerId,
311 - suggestions: getSuggestions(),
585 + ...(willReload ? {} : nextSteps(workflow.id, 'completed')),
312 586 });
587 + // A chat message persists, so the next turn's model knows the save was partial.
588 + const refusedCount = toolResponse?.refusedOperations?.length;
589 + if (refusedCount) {
590 + addMessage('message', {
591 + role: 'assistant',
592 + content: sprintf(
593 + // translators: %d is how many of the requested edits were not applied.
594 + _n(
595 + "Heads up — %d of those changes couldn't be applied. If something still looks the same, ask me to redo just that part.",
596 + "Heads up — %d of those changes couldn't be applied. If something still looks the same, ask me to redo just those parts.",
597 + refusedCount,
598 + 'extendify-local',
599 + ),
600 + refusedCount,
601 + ),
602 + });
603 + }
313 604 setWorkflow(null);
605 + useCanvasStore.getState().endSession();
314 606
315 - const url = getRedirectUrl(redirectTo, whenFinishedToolProps?.inputs);
316 - const refreshForAbility = abilityAffectsCurrentPage(id, data);
317 - if (url || redirectUrl || shouldRefreshPage || refreshForAbility) {
318 - await new Promise((resolve) => setTimeout(resolve, 1000));
319 - }
320 - if (url) return window.location.assign(url);
321 - if (redirectUrl) return window.location.assign(redirectUrl);
322 - if (shouldRefreshPage || refreshForAbility)
323 - return window.location.reload();
607 + if (willReload) return doReload(redirectUrl);
324 608 cleanup();
325 609 };
326 610 const handleCancel = ({ detail }) => {
327 611 if (toolWorking.current) return;
612 + // Without this a canvas closed mid-turn keeps replying into the chat.
613 + controller.abort('Workflow aborted');
328 614 const { answerId, whenFinishedTool } =
329 615 detail.whenFinishedToolProps?.agentResponse || {};
330 616 addMessage('workflow', {
331 617 status: 'canceled',
@@ -332,11 +618,12 @@
332 618 label: whenFinishedTool?.labels?.cancel,
333 619 agent: workflow.agent,
334 620 workflowId: workflow.id,
335 621 answerId,
336 - suggestions: getSuggestions(),
622 + ...nextSteps(workflow.id, 'canceled'),
337 623 });
338 624 setWorkflow(null);
625 + useCanvasStore.getState().endSession();
339 626 cleanup();
340 627 };
341 628 const handleRetry = () => {
342 629 popMessage();
@@ -358,18 +645,9 @@
358 645 handleCancel,
359 646 );
360 647 window.removeEventListener('extendify-agent:workflow-retry', handleRetry);
361 648 };
362 - }, [
363 - addMessage,
364 - pushStatus,
365 - popMessage,
366 - cleanup,
367 - setWorkflow,
368 - workflow,
369 - getSuggestions,
370 - addSuggestions,
371 - ]);
649 + }, [addMessage, pushStatus, popMessage, cleanup, setWorkflow, workflow]);
372 650
373 651 useEffect(() => {
374 652 const handleClose = () => setOpen(false);
375 653 const handleOpen = () => setOpen(true);
@@ -389,9 +667,26 @@
389 667 if (open) return;
390 668 if (block) setBlock(null);
391 669 }, [open, block, setBlock]);
392 670
671 + // A pick answers select-block's "which one?"; making the user also type stalls it.
672 + const previousBlock = useRef(block);
393 673 useEffect(() => {
674 + const picked = block && !previousBlock.current;
675 + previousBlock.current = block;
676 + if (!picked || workflow?.id !== 'select-block') return;
677 + if (!waitingOnToolOrUser || !canType || whenFinishedToolProps?.id) return;
678 + handleSubmit('This is the block I mean.', { hidden: true });
679 + }, [
680 + block,
681 + workflow?.id,
682 + waitingOnToolOrUser,
683 + canType,
684 + whenFinishedToolProps?.id,
685 + handleSubmit,
686 + ]);
687 +
688 + useEffect(() => {
394 689 if (waitingOnToolOrUser || !open || !workflow?.id) return;
395 690 // Some workflows require they dont change pages
396 691 const theyMoved = workflow?.startingPage !== window.location.href;
397 692 // Requires a block to be selected
@@ -402,9 +697,9 @@
402 697 addMessage('workflow', {
403 698 status: 'canceled',
404 699 agent: workflow.agent,
405 700 workflowId: workflow.id,
406 - suggestions: getSuggestions(),
701 + ...nextSteps(workflow.id, 'canceled'),
407 702 });
408 703 setWorkflow(null);
409 704 cleanup();
410 705 return;
@@ -448,14 +743,20 @@
448 743 window.extAgentData.failedWorkflows.add(workflow.id);
449 744 throw new Error(`Error handling workflow: ${agentResponse.error}`);
450 745 }
451 746 // The ai sent back some text to show to the user
452 - if (agentResponse.reply) {
747 + const reply =
748 + agentResponse.reply ??
749 + (agentResponse.tool
750 + ? getClientToolFallbackReply(agentResponse.tool.id)
751 + : null);
752 + if (reply) {
453 753 addMessage('message', {
454 754 role: 'assistant',
455 - content: agentResponse.reply,
755 + content: reply,
456 756 followup: !!agentResponse.tool,
457 757 pageSuggestion: agentResponse.pageSuggestion,
758 + qaSuggestions: agentResponse.qaSuggestions,
458 759 agent: workflow.agent,
459 760 sessionId: workflow?.sessionId,
460 761 workflowId: workflow?.id,
461 762 language: workflow?.language,
@@ -460,8 +761,26 @@
460 761 workflowId: workflow?.id,
461 762 language: workflow?.language,
462 763 });
463 764 }
765 + // Set when the request needs something no block edit can do.
766 + if (agentResponse.dropSelection) {
767 + setBlock(null);
768 + window.dispatchEvent(
769 + new Event('extendify-agent:remove-block-highlight'),
770 + );
771 + setWorkflow(null);
772 + pushStatus(
773 + 'tool-started',
774 + // translators: Shown while the AI agent deselects a block that can't serve the request.
775 + __('Removing selected block', 'extendify-local'),
776 + );
777 + // findAgent pushes its own status right away; let this one read first.
778 + if (await canceledDuring(2500)) return;
779 + agentWorking.current = false;
780 + await findAgent();
781 + return;
782 + }
464 783 // This is at the end of the workflow
465 784 // and we are about to execute the final tool
466 785 if (agentResponse.whenFinishedTool?.id) {
467 786 setWhenFinishedToolProps({
@@ -469,9 +788,10 @@
469 788 agentResponse,
470 789 });
471 790 // If static, add it as a message
472 791 const { id, inputs, static: staticC } = agentResponse.whenFinishedTool;
473 - if (staticC) {
792 + // A canvas workflow renders in the canvas and ends on close or submit.
793 + if (staticC && !workflow.whenFinished?.canvas) {
474 794 addMessage('workflow-component', {
475 795 id,
476 796 status: 'completed',
477 797 inputs,
@@ -476,9 +796,8 @@
476 796 status: 'completed',
477 797 inputs,
478 798 workflowId: workflow.id,
479 799 });
480 - addSuggestions(agentResponse.recommendations);
481 800 setWorkflow(null);
482 801 addMessage('workflow', {
483 802 status: 'completed',
484 803 agent: workflow.agent,
@@ -483,9 +802,9 @@
483 802 status: 'completed',
484 803 agent: workflow.agent,
485 804 workflowId: workflow.id,
486 805 answerId,
487 - suggestions: getSuggestions(),
806 + ...nextSteps(workflow.id, 'completed'),
488 807 });
489 808 cleanup();
490 809 }
491 810 return;
@@ -491,19 +810,21 @@
491 810 return;
492 811 }
493 812 // If we're done, it means the AI has the answer
494 813 if (agentResponse.status !== 'in-progress') {
495 - const { recommendations, status } = agentResponse;
496 - const isCompleted = status === 'completed';
497 - if (recommendations) addSuggestions(recommendations);
814 + const status =
815 + agentResponse.status === 'completed' ? 'completed' : 'canceled';
816 + // A reply that changed nothing isn't a finished task to follow up.
817 + const didWork =
818 + toolCallsThisRun(useChatStore.getState().messages).length > 0;
498 819 setWorkflow(null);
499 820 cleanup();
500 821 addMessage('workflow', {
501 - status: isCompleted ? 'completed' : 'canceled',
822 + status,
502 823 agent: workflow.agent,
503 824 workflowId: workflow.id,
504 825 answerId,
505 - suggestions: getSuggestions(),
826 + ...(didWork ? nextSteps(workflow.id, status) : { followUp: null }),
506 827 });
507 828 return;
508 829 }
509 830 if (sessionId && sessionId !== workflow.sessionId) {
@@ -514,9 +835,19 @@
514 835 mergeWorkflowData(agentResponse.inputs);
515 836 // Agent needs more info from a
516 837 if (agentResponse.tool) {
517 838 const { id, inputs, labels } = agentResponse.tool;
518 - pushStatus('tool-started', labels?.started);
839 + // A client tool is answered by in-chat UI, so the turn ends here.
840 + if (getClientTools().includes(id)) {
841 + addMessage('tool', { id, inputs });
842 + // Clearing agentWorking here fires a second turn: the wait flag
843 + // has not committed yet.
844 + setWaitingOnToolOrUser(true);
845 + setCanType(false);
846 + return;
847 + }
848 + // A reply sent with the tool clears the status, blanking the line.
849 + pushStatus('agent-working');
519 850 const toolData = await Promise.all([
520 851 callTool({ tool: id, inputs }),
521 852 new Promise((resolve) => setTimeout(resolve, 3000)),
522 853 ])
@@ -530,19 +861,27 @@
530 861 caller: `in-progress: ${id}`,
531 862 sessionId,
532 863 },
533 864 });
534 - devmode && console.error(error);
865 + console.error(`Extendify agent tool error: ${id}`, {
866 + siteId,
867 + error,
868 + });
535 869 // Don't throw; the loop hands the error to the model.
536 870 return { error: { message: error?.message, code: error?.code } };
537 871 });
538 - pushStatus('tool-completed', labels?.confirm);
539 - await new Promise((resolve) => setTimeout(resolve, 1000));
540 872 // do-when-finished spreads first-class workflowData into the tool.
541 873 if (!toolData?.error && !isAbilityWorkflow(workflow.id)) {
542 874 mergeWorkflowData(toolData);
543 875 }
544 - addMessage('tool', { id, inputs, result: toolData });
876 + if (toolData?.stagedBlockIds?.length) requireBlock();
877 + addMessage('tool', {
878 + id,
879 + inputs,
880 + result: toolData,
881 + label: labels?.confirm,
882 + started: labels?.started,
883 + });
545 884 setWaitingOnToolOrUser(false);
546 885 agentWorking.current = false;
547 886 setLoop((prev) => prev + 1); // Trigger next loop
548 887 return;
@@ -580,14 +919,15 @@
580 919 setWorkflow,
581 920 agentWorking,
582 921 waitingOnToolOrUser,
583 922 mergeWorkflowData,
923 + requireBlock,
584 924 canType,
585 925 whenFinishedToolProps,
586 926 setWhenFinishedToolProps,
587 927 block,
588 - addSuggestions,
589 - getSuggestions,
928 + setBlock,
929 + findAgent,
590 930 ]);
591 931
592 932 useEffect(() => {
593 933 if (!canType) return;
@@ -593,41 +933,63 @@
593 933 if (!canType) return;
594 934 document.querySelector('#extendify-agent-chat-textarea')?.focus();
595 935 }, [canType]);
596 936
597 - const busy = !canType || !chatAvailable || workflow?.id;
937 + // A task waiting on a reply leaves the page pickable so the user can answer by pointing.
938 + const waiting =
939 + canType &&
940 + chatAvailable &&
941 + Boolean(workflow?.id) &&
942 + !whenFinishedToolProps?.id;
943 + const busy = !canType || !chatAvailable || (workflow?.id && !waiting);
944 + // `busy` is true at rest; 429 is blocked, not working.
945 + const working = !canType && chatAvailable;
598 946
599 947 return (
600 - <Chat busy={busy}>
601 - <div className="relative z-50 flex h-full flex-col justify-between overflow-auto">
602 - <ChatMessages
603 - redirectComponent={
604 - workflow?.needsRedirect?.() ? workflow.redirectComponent : null
605 - }
606 - />
607 - <div>
608 - <div className="relative flex flex-col px-4 pb-2 pt-2.5 shadow-lg-flipped">
609 - {block ? <PageDocument busy={busy} blockId={block.id} /> : null}
610 - <UsageMessage
611 - onReady={() => {
612 - cleanup();
613 - pushStatus('credits-restored');
614 - }}
615 - />
948 + <>
949 + <Canvas />
950 + <Chat
951 + busy={busy}
952 + working={working}
953 + waiting={waiting}
954 + taskActive={Boolean(workflow?.id)}
955 + >
956 + <div className="relative z-50 flex h-full flex-col justify-between overflow-auto">
957 + <ChatMessages
958 + redirectComponent={
959 + workflow?.needsRedirect?.() ? workflow.redirectComponent : null
960 + }
961 + />
962 + <div>
963 + <div className="relative flex flex-col px-4 pb-2 pt-2.5 shadow-lg-flipped">
964 + <UsageMessage
965 + onReady={() => {
966 + cleanup();
967 + pushStatus('credits-restored');
968 + }}
969 + />
970 + </div>
971 + <div className="p-4 pb-2 pt-0">
972 + <StatusIndicator />
973 + <ChatInput
974 + disabled={
975 + !canType ||
976 + !chatAvailable ||
977 + !!qaSuggestions ||
978 + leavingPage ||
979 + whenFinishedToolProps?.processing
980 + }
981 + handleSubmit={handleSubmit}
982 + />
983 + </div>
984 + <div className="text-pretty px-4 pb-2 text-center text-xss leading-none text-gray-700">
985 + {__(
986 + 'AI Agent can make mistakes. Check changes before saving.',
987 + 'extendify-local',
988 + )}
989 + </div>
616 990 </div>
617 - <div className="p-4 pb-2 pt-0">
618 - <ChatInput
619 - disabled={!canType || !chatAvailable}
620 - handleSubmit={handleSubmit}
621 - />
622 - </div>
623 - <div className="text-pretty px-4 pb-2 text-center text-xss leading-none text-gray-700">
624 - {__(
625 - 'AI Agent can make mistakes. Check changes before saving.',
626 - 'extendify-local',
627 - )}
628 - </div>
629 991 </div>
630 - </div>
631 - </Chat>
992 + </Chat>
993 + </>
632 994 );
633 995 };