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