| @@ -1,14 +1,27 @@ | ||
| 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'; |
| 18 | +import { useFollowUpHistory } from '@agent/follow-ups/history'; | |
| 19 | +import { | |
| 20 | + cardMessageIndex, | |
| 21 | + pickNextCard, | |
| 22 | + toolCallsThisRun, | |
| 23 | +} from '@agent/follow-ups/pick-next'; | |
| 11 | 24 | import { useLockPost } from '@agent/hooks/useLockPost'; |
| 12 | 25 | import { isAbilityTool, isAbilityWorkflow } from '@agent/lib/abilities'; |
| 13 | 26 | import { |
| 14 | 27 | getClientToolFallbackReply, |
| @@ -15,14 +28,16 @@ | ||
| 15 | 28 | getClientTools, |
| 16 | 29 | } from '@agent/lib/client-tools'; |
| 17 | 30 | import { localPickWorkflow } from '@agent/lib/local-pick'; |
| 18 | 31 | import { getRedirectUrl } from '@agent/lib/redirects'; |
| 32 | +import { doReload } from '@agent/lib/reload'; | |
| 33 | +import { useCanvasStore } from '@agent/state/canvas'; | |
| 19 | 34 | import { useChatStore } from '@agent/state/chat'; |
| 20 | 35 | import { useGlobalStore } from '@agent/state/global'; |
| 21 | 36 | import { useStatusStore } from '@agent/state/status'; |
| 22 | -import { useSuggestionsStore } from '@agent/state/suggestions'; | |
| 23 | 37 | import { useWorkflowStore } from '@agent/state/workflows'; |
| 24 | 38 | import { hasRunComponent } from '@agent/workflows/abilities/components/run'; |
| 39 | +import startOnboardingWorkflow from '@agent/workflows/misc/start-onboarding'; | |
| 25 | 40 | import { useQuickEditStore } from '@quick-edit/state/store'; |
| 26 | 41 | import { digest } from '@shared/api/digest'; |
| 27 | 42 | import { |
| 28 | 43 | useCallback, |
| @@ -50,11 +65,28 @@ | ||
| 50 | 65 | ]); |
| 51 | 66 | return result; |
| 52 | 67 | }; |
| 53 | 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 | + | |
| 54 | 86 | export const Agent = () => { |
| 55 | 87 | const { addMessage, updateMessage, popMessage, messages } = useChatStore(); |
| 56 | - const { pushStatus, clearStatuses } = useStatusStore(); | |
| 88 | + const { pushStatus, clearStatuses, leavingPage } = useStatusStore(); | |
| 57 | 89 | const { |
| 58 | 90 | mergeWorkflowData, |
| 59 | 91 | getWorkflow, |
| 60 | 92 | getWorkflowByExample, |
| @@ -80,10 +112,12 @@ | ||
| 80 | 112 | return last?.type === 'message' && last.details?.role === 'assistant'; |
| 81 | 113 | }); |
| 82 | 114 | const [loop, setLoop] = useState(0); |
| 83 | 115 | const workflow = getWorkflow(); |
| 116 | + const canvasOpen = useCanvasOpen(); | |
| 117 | + const canvasAssist = useCanvasAssist(); | |
| 118 | + const canvasNoticeShown = useRef(false); | |
| 84 | 119 | const chatAvailable = useMemo(() => isChatAvailable(), [isChatAvailable]); |
| 85 | - const { addSuggestions, getSuggestions } = useSuggestionsStore(); | |
| 86 | 120 | // Options render only while their message is last; a reply dismisses them. |
| 87 | 121 | const lastMessage = messages.at(-1); |
| 88 | 122 | const qaSuggestions = |
| 89 | 123 | lastMessage?.type === 'message' && |
| @@ -91,8 +125,25 @@ | ||
| 91 | 125 | Array.isArray(lastMessage.details?.qaSuggestions) |
| 92 | 126 | ? lastMessage.details.qaSuggestions |
| 93 | 127 | : null; |
| 94 | 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 | + | |
| 95 | 146 | const cleanup = useCallback(() => { |
| 96 | 147 | setCanType(true); |
| 97 | 148 | agentWorking.current = false; |
| 98 | 149 | setWaitingOnToolOrUser(false); |
| @@ -101,9 +152,14 @@ | ||
| 101 | 152 | agentBlock && setBlock(null); |
| 102 | 153 | // A class or pin left up freezes Quick Edit hover site-wide. |
| 103 | 154 | document |
| 104 | 155 | .querySelector('.wp-site-blocks') |
| 105 | - ?.classList.remove('extendify-agent-working', 'extendify-agent-busy'); | |
| 156 | + ?.classList.remove( | |
| 157 | + 'extendify-agent-working', | |
| 158 | + 'extendify-agent-busy', | |
| 159 | + 'extendify-agent-waiting', | |
| 160 | + 'extendify-agent-task', | |
| 161 | + ); | |
| 106 | 162 | setCommittedSelection(null); |
| 107 | 163 | clearStatuses(); |
| 108 | 164 | window.dispatchEvent(new Event('extendify-agent:remove-block-highlight')); |
| 109 | 165 | }, [setBlock, clearStatuses]); |
| @@ -125,13 +181,14 @@ | ||
| 125 | 181 | |
| 126 | 182 | const findAgent = useCallback( |
| 127 | 183 | async (options = {}) => { |
| 128 | 184 | pushStatus('calling-agent'); |
| 185 | + const { signal } = controller; | |
| 129 | 186 | const response = await withMinDuration( |
| 130 | 187 | pickWorkflow({ |
| 131 | 188 | // A mid-turn drop clears the block after this closure was made. |
| 132 | 189 | workflows: getAvailableWorkflows().map((w) => w.id), |
| 133 | - options: { signal: controller.signal, ...options }, | |
| 190 | + options: { signal, ...options }, | |
| 134 | 191 | }).catch(async (error) => { |
| 135 | 192 | devmode && console.error(error); |
| 136 | 193 | if (error?.response?.status === 429) { |
| 137 | 194 | updateRetryAfter(error?.response?.headers?.get('Retry-After')); |
| @@ -139,15 +196,9 @@ | ||
| 139 | 196 | pushStatus('credits-exhausted'); |
| 140 | 197 | return; |
| 141 | 198 | } |
| 142 | 199 | setCanType(true); |
| 143 | - if (error === 'Workflow aborted') { | |
| 144 | - addMessage('workflow', { | |
| 145 | - status: 'canceled', | |
| 146 | - suggestions: getSuggestions(), | |
| 147 | - }); | |
| 148 | - return; | |
| 149 | - } | |
| 200 | + if (error === 'Workflow aborted') return; | |
| 150 | 201 | |
| 151 | 202 | await new Promise((resolve) => setTimeout(resolve, 1000)); |
| 152 | 203 | addMessage('message', { |
| 153 | 204 | role: 'assistant', |
| @@ -161,9 +212,9 @@ | ||
| 161 | 212 | return; |
| 162 | 213 | }), |
| 163 | 214 | 500, |
| 164 | 215 | ); |
| 165 | - if (!response) return; | |
| 216 | + if (!response || signal.aborted) return; | |
| 166 | 217 | |
| 167 | 218 | const { workflow: wf, reply } = response; |
| 168 | 219 | if (wf?.id) setWorkflow(wf); |
| 169 | 220 | if (reply) { |
| @@ -177,20 +228,107 @@ | ||
| 177 | 228 | pushStatus, |
| 178 | 229 | updateRetryAfter, |
| 179 | 230 | setWorkflow, |
| 180 | 231 | getAvailableWorkflows, |
| 181 | - getSuggestions, | |
| 182 | 232 | ], |
| 183 | 233 | ); |
| 184 | 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 | + | |
| 185 | 305 | const handleSubmit = useCallback( |
| 186 | - async (message) => { | |
| 187 | - // Suggestions reach the agent without the textarea; disabling it isn't enough. | |
| 306 | + async (message, { hidden = false } = {}) => { | |
| 307 | + // chat-submit events skip the textarea; disabling it isn't enough. | |
| 188 | 308 | if (useQuickEditStore.getState().selected) return; |
| 309 | + if (whenFinishedToolProps?.processing) return; | |
| 189 | 310 | setWaitingOnToolOrUser(false); |
| 190 | 311 | agentWorking.current = false; |
| 191 | - addMessage('message', { role: 'user', content: message }); | |
| 312 | + addMessage('message', { role: 'user', content: message, hidden }); | |
| 192 | 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 | + | |
| 193 | 331 | // Let some phrases auto load workflows |
| 194 | 332 | const bypass = getWorkflowByExample(message); |
| 195 | 333 | if (bypass?.example?.agentResponse) { |
| 196 | 334 | // whenFinishedTool → inline input UI; none → ask for a typed reply. |
| @@ -218,9 +356,9 @@ | ||
| 218 | 356 | |
| 219 | 357 | // Skip the network find-agent when the staged block makes the edit certain. |
| 220 | 358 | const localPick = localPickWorkflow({ block }); |
| 221 | 359 | if (localPick) { |
| 222 | - await new Promise((resolve) => setTimeout(resolve, 500)); | |
| 360 | + if (await canceledDuring(500)) return; | |
| 223 | 361 | setWorkflow(localPick); |
| 224 | 362 | return; |
| 225 | 363 | } |
| 226 | 364 | |
| @@ -228,9 +366,12 @@ | ||
| 228 | 366 | }, |
| 229 | 367 | [ |
| 230 | 368 | addMessage, |
| 231 | 369 | block, |
| 370 | + canvasAssist, | |
| 371 | + canvasOpen, | |
| 232 | 372 | findAgent, |
| 373 | + handleCanvasMessage, | |
| 233 | 374 | mergeWorkflowData, |
| 234 | 375 | whenFinishedToolProps, |
| 235 | 376 | setWorkflow, |
| 236 | 377 | workflow, |
| @@ -246,9 +387,9 @@ | ||
| 246 | 387 | if (!agentResponse) return; |
| 247 | 388 | setWorkflow(workflow); |
| 248 | 389 | setCanType(false); |
| 249 | 390 | agentWorking.current = true; |
| 250 | - await new Promise((resolve) => setTimeout(resolve, 750)); | |
| 391 | + if (await canceledDuring(750)) return; | |
| 251 | 392 | addMessage('message', { |
| 252 | 393 | role: 'assistant', |
| 253 | 394 | content: agentResponse.reply, |
| 254 | 395 | }); |
| @@ -272,9 +413,9 @@ | ||
| 272 | 413 | // Without this the loop calls the backend before the user has typed. |
| 273 | 414 | setWaitingOnToolOrUser(true); |
| 274 | 415 | setCanType(false); |
| 275 | 416 | agentWorking.current = true; |
| 276 | - await new Promise((resolve) => setTimeout(resolve, 750)); | |
| 417 | + if (await canceledDuring(750)) return; | |
| 277 | 418 | addMessage('message', { |
| 278 | 419 | role: 'assistant', |
| 279 | 420 | content: agentResponse.reply, |
| 280 | 421 | // A workflow example can carry its own suggestions; none still asks. |
| @@ -292,12 +433,14 @@ | ||
| 292 | 433 | useEffect(() => { |
| 293 | 434 | // Allow external messages to trigger the agent |
| 294 | 435 | const handleMessage = ({ detail }) => { |
| 295 | 436 | if (!detail?.message) return; |
| 296 | - handleSubmit(detail.message); | |
| 437 | + handleSubmit(detail.message, { hidden: detail.hidden }); | |
| 297 | 438 | }; |
| 298 | 439 | // Allow external code to clear the block and workflow |
| 299 | 440 | const handleCleanup = () => { |
| 441 | + // cleanup() resets canType and agentWorking, so read them before it runs. | |
| 442 | + const interrupted = agentWorking.current || !canType; | |
| 300 | 443 | controller.abort('Workflow aborted'); |
| 301 | 444 | cleanup(); |
| 302 | 445 | // Deferred a frame: the input stays disabled until the cancel lands. |
| 303 | 446 | requestAnimationFrame(() => |
| @@ -304,15 +447,15 @@ | ||
| 304 | 447 | document.querySelector('#extendify-agent-chat-textarea')?.focus(), |
| 305 | 448 | ); |
| 306 | 449 | |
| 307 | 450 | // An options panel can outlive its workflow; cancel must still clear it. |
| 308 | - if (!workflow?.id && !qaSuggestions) return; | |
| 451 | + if (!workflow?.id && !qaSuggestions && !interrupted) return; | |
| 309 | 452 | setWorkflow(null); |
| 310 | 453 | addMessage('workflow', { |
| 311 | 454 | status: 'canceled', |
| 312 | 455 | agent: workflow?.agent, |
| 313 | 456 | workflowId: workflow?.id, |
| 314 | - suggestions: getSuggestions(), | |
| 457 | + ...nextSteps(workflow?.id, 'canceled'), | |
| 315 | 458 | }); |
| 316 | 459 | return; |
| 317 | 460 | }; |
| 318 | 461 | window.addEventListener('extendify-agent:cancel-workflow', handleCleanup); |
| @@ -330,25 +473,52 @@ | ||
| 330 | 473 | setWorkflow, |
| 331 | 474 | addMessage, |
| 332 | 475 | workflow, |
| 333 | 476 | qaSuggestions, |
| 334 | - getSuggestions, | |
| 477 | + canType, | |
| 335 | 478 | ]); |
| 336 | 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 | + | |
| 337 | 499 | // Handle whenFinished component confirm/cancel |
| 338 | 500 | useEffect(() => { |
| 339 | 501 | const handleConfirm = async ({ detail }) => { |
| 340 | 502 | if (toolWorking.current) return; |
| 341 | - setWhenFinishedToolProps(null); | |
| 342 | 503 | toolWorking.current = true; |
| 343 | 504 | const { data, whenFinishedToolProps, shouldRefreshPage, redirectUrl } = |
| 344 | 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 | + ); | |
| 345 | 512 | const { whenFinishedTool, answerId, redirectTo } = |
| 346 | 513 | whenFinishedToolProps?.agentResponse || {}; |
| 347 | 514 | const { id, labels } = whenFinishedTool || {}; |
| 348 | 515 | // Staged unanswered so its own component can show the run in progress. |
| 349 | 516 | const runMessageId = id ? addMessage('tool', { id, inputs: data }) : null; |
| 350 | - if (!hasRunComponent(id)) pushStatus('workflow-tool-processing'); | |
| 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 | + } | |
| 351 | 521 | // Not all workflows have a tool at the end (e.g. tours) |
| 352 | 522 | const toolResponse = await callTool?.({ tool: id, inputs: data }).catch( |
| 353 | 523 | (error) => { |
| 354 | 524 | const { sessionId } = workflow || {}; |
| @@ -364,8 +534,9 @@ | ||
| 364 | 534 | return { error: { message: error?.message, code: error?.code } }; |
| 365 | 535 | }, |
| 366 | 536 | ); |
| 367 | 537 | toolWorking.current = false; |
| 538 | + setWhenFinishedToolProps(null); | |
| 368 | 539 | if (runMessageId) updateMessage(runMessageId, { result: toolResponse }); |
| 369 | 540 | if (toolResponse?.refused) { |
| 370 | 541 | await new Promise((resolve) => setTimeout(resolve, 1000)); |
| 371 | 542 | const refusalMessages = { |
| @@ -373,13 +544,8 @@ | ||
| 373 | 544 | 'no-op': __( |
| 374 | 545 | "That edit came back unchanged, which wasn't expected. Please try rephrasing what you'd like to change.", |
| 375 | 546 | 'extendify-local', |
| 376 | 547 | ), |
| 377 | - // translators: Shown when the user asked the AI agent to edit a block that lives in a site template (e.g. the header or footer), which the agent cannot save yet. | |
| 378 | - 'template-part': __( | |
| 379 | - "That block is part of your site's template, like the header or footer, and I can't make changes there yet.", | |
| 380 | - 'extendify-local', | |
| 381 | - ), | |
| 382 | 548 | }; |
| 383 | 549 | addMessage('message', { |
| 384 | 550 | role: 'assistant', |
| 385 | 551 | content: |
| @@ -403,9 +569,15 @@ | ||
| 403 | 569 | setLoop((prev) => prev + 1); |
| 404 | 570 | return; |
| 405 | 571 | } |
| 406 | 572 | |
| 407 | - 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. | |
| 408 | 580 | addMessage('workflow', { |
| 409 | 581 | status: 'completed', |
| 410 | 582 | label: labels?.confirm, |
| 411 | 583 | agent: workflow.agent, |
| @@ -410,9 +582,9 @@ | ||
| 410 | 582 | label: labels?.confirm, |
| 411 | 583 | agent: workflow.agent, |
| 412 | 584 | workflowId: workflow.id, |
| 413 | 585 | answerId, |
| 414 | - suggestions: getSuggestions(), | |
| 586 | + ...(willReload ? {} : nextSteps(workflow.id, 'completed')), | |
| 415 | 587 | }); |
| 416 | 588 | // A chat message persists, so the next turn's model knows the save was partial. |
| 417 | 589 | const refusedCount = toolResponse?.refusedOperations?.length; |
| 418 | 590 | if (refusedCount) { |
| @@ -430,22 +602,17 @@ | ||
| 430 | 602 | ), |
| 431 | 603 | }); |
| 432 | 604 | } |
| 433 | 605 | setWorkflow(null); |
| 606 | + useCanvasStore.getState().endSession(); | |
| 434 | 607 | |
| 435 | - const url = getRedirectUrl(redirectTo, whenFinishedToolProps?.inputs); | |
| 436 | - const refreshForAbility = isAbilityTool(id); | |
| 437 | - if (url || redirectUrl || shouldRefreshPage || refreshForAbility) { | |
| 438 | - await new Promise((resolve) => setTimeout(resolve, 1000)); | |
| 439 | - } | |
| 440 | - if (url) return window.location.assign(url); | |
| 441 | - if (redirectUrl) return window.location.assign(redirectUrl); | |
| 442 | - if (shouldRefreshPage || refreshForAbility) | |
| 443 | - return window.location.reload(); | |
| 608 | + if (willReload) return doReload(url || redirectUrl); | |
| 444 | 609 | cleanup(); |
| 445 | 610 | }; |
| 446 | 611 | const handleCancel = ({ detail }) => { |
| 447 | 612 | if (toolWorking.current) return; |
| 613 | + // Without this a canvas closed mid-turn keeps replying into the chat. | |
| 614 | + controller.abort('Workflow aborted'); | |
| 448 | 615 | const { answerId, whenFinishedTool } = |
| 449 | 616 | detail.whenFinishedToolProps?.agentResponse || {}; |
| 450 | 617 | addMessage('workflow', { |
| 451 | 618 | status: 'canceled', |
| @@ -452,11 +619,12 @@ | ||
| 452 | 619 | label: whenFinishedTool?.labels?.cancel, |
| 453 | 620 | agent: workflow.agent, |
| 454 | 621 | workflowId: workflow.id, |
| 455 | 622 | answerId, |
| 456 | - suggestions: getSuggestions(), | |
| 623 | + ...nextSteps(workflow.id, 'canceled'), | |
| 457 | 624 | }); |
| 458 | 625 | setWorkflow(null); |
| 626 | + useCanvasStore.getState().endSession(); | |
| 459 | 627 | cleanup(); |
| 460 | 628 | }; |
| 461 | 629 | const handleRetry = () => { |
| 462 | 630 | popMessage(); |
| @@ -478,18 +646,9 @@ | ||
| 478 | 646 | handleCancel, |
| 479 | 647 | ); |
| 480 | 648 | window.removeEventListener('extendify-agent:workflow-retry', handleRetry); |
| 481 | 649 | }; |
| 482 | - }, [ | |
| 483 | - addMessage, | |
| 484 | - pushStatus, | |
| 485 | - popMessage, | |
| 486 | - cleanup, | |
| 487 | - setWorkflow, | |
| 488 | - workflow, | |
| 489 | - getSuggestions, | |
| 490 | - addSuggestions, | |
| 491 | - ]); | |
| 650 | + }, [addMessage, pushStatus, popMessage, cleanup, setWorkflow, workflow]); | |
| 492 | 651 | |
| 493 | 652 | useEffect(() => { |
| 494 | 653 | const handleClose = () => setOpen(false); |
| 495 | 654 | const handleOpen = () => setOpen(true); |
| @@ -509,9 +668,26 @@ | ||
| 509 | 668 | if (open) return; |
| 510 | 669 | if (block) setBlock(null); |
| 511 | 670 | }, [open, block, setBlock]); |
| 512 | 671 | |
| 672 | + // A pick answers select-block's "which one?"; making the user also type stalls it. | |
| 673 | + const previousBlock = useRef(block); | |
| 513 | 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(() => { | |
| 514 | 690 | if (waitingOnToolOrUser || !open || !workflow?.id) return; |
| 515 | 691 | // Some workflows require they dont change pages |
| 516 | 692 | const theyMoved = workflow?.startingPage !== window.location.href; |
| 517 | 693 | // Requires a block to be selected |
| @@ -522,9 +698,9 @@ | ||
| 522 | 698 | addMessage('workflow', { |
| 523 | 699 | status: 'canceled', |
| 524 | 700 | agent: workflow.agent, |
| 525 | 701 | workflowId: workflow.id, |
| 526 | - suggestions: getSuggestions(), | |
| 702 | + ...nextSteps(workflow.id, 'canceled'), | |
| 527 | 703 | }); |
| 528 | 704 | setWorkflow(null); |
| 529 | 705 | cleanup(); |
| 530 | 706 | return; |
| @@ -599,9 +775,9 @@ | ||
| 599 | 775 | // translators: Shown while the AI agent deselects a block that can't serve the request. |
| 600 | 776 | __('Removing selected block', 'extendify-local'), |
| 601 | 777 | ); |
| 602 | 778 | // findAgent pushes its own status right away; let this one read first. |
| 603 | - await new Promise((resolve) => setTimeout(resolve, 2500)); | |
| 779 | + if (await canceledDuring(2500)) return; | |
| 604 | 780 | agentWorking.current = false; |
| 605 | 781 | await findAgent(); |
| 606 | 782 | return; |
| 607 | 783 | } |
| @@ -613,9 +789,10 @@ | ||
| 613 | 789 | agentResponse, |
| 614 | 790 | }); |
| 615 | 791 | // If static, add it as a message |
| 616 | 792 | const { id, inputs, static: staticC } = agentResponse.whenFinishedTool; |
| 617 | - if (staticC) { | |
| 793 | + // A canvas workflow renders in the canvas and ends on close or submit. | |
| 794 | + if (staticC && !workflow.whenFinished?.canvas) { | |
| 618 | 795 | addMessage('workflow-component', { |
| 619 | 796 | id, |
| 620 | 797 | status: 'completed', |
| 621 | 798 | inputs, |
| @@ -620,9 +797,8 @@ | ||
| 620 | 797 | status: 'completed', |
| 621 | 798 | inputs, |
| 622 | 799 | workflowId: workflow.id, |
| 623 | 800 | }); |
| 624 | - addSuggestions(agentResponse.recommendations); | |
| 625 | 801 | setWorkflow(null); |
| 626 | 802 | addMessage('workflow', { |
| 627 | 803 | status: 'completed', |
| 628 | 804 | agent: workflow.agent, |
| @@ -627,9 +803,9 @@ | ||
| 627 | 803 | status: 'completed', |
| 628 | 804 | agent: workflow.agent, |
| 629 | 805 | workflowId: workflow.id, |
| 630 | 806 | answerId, |
| 631 | - suggestions: getSuggestions(), | |
| 807 | + ...nextSteps(workflow.id, 'completed'), | |
| 632 | 808 | }); |
| 633 | 809 | cleanup(); |
| 634 | 810 | } |
| 635 | 811 | return; |
| @@ -635,19 +811,21 @@ | ||
| 635 | 811 | return; |
| 636 | 812 | } |
| 637 | 813 | // If we're done, it means the AI has the answer |
| 638 | 814 | if (agentResponse.status !== 'in-progress') { |
| 639 | - const { recommendations, status } = agentResponse; | |
| 640 | - const isCompleted = status === 'completed'; | |
| 641 | - 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; | |
| 642 | 820 | setWorkflow(null); |
| 643 | 821 | cleanup(); |
| 644 | 822 | addMessage('workflow', { |
| 645 | - status: isCompleted ? 'completed' : 'canceled', | |
| 823 | + status, | |
| 646 | 824 | agent: workflow.agent, |
| 647 | 825 | workflowId: workflow.id, |
| 648 | 826 | answerId, |
| 649 | - suggestions: getSuggestions(), | |
| 827 | + ...(didWork ? nextSteps(workflow.id, status) : { followUp: null }), | |
| 650 | 828 | }); |
| 651 | 829 | return; |
| 652 | 830 | } |
| 653 | 831 | if (sessionId && sessionId !== workflow.sessionId) { |
| @@ -667,9 +845,10 @@ | ||
| 667 | 845 | setWaitingOnToolOrUser(true); |
| 668 | 846 | setCanType(false); |
| 669 | 847 | return; |
| 670 | 848 | } |
| 671 | - pushStatus('tool-started', labels?.started); | |
| 849 | + // A reply sent with the tool clears the status, blanking the line. | |
| 850 | + pushStatus('agent-working'); | |
| 672 | 851 | const toolData = await Promise.all([ |
| 673 | 852 | callTool({ tool: id, inputs }), |
| 674 | 853 | new Promise((resolve) => setTimeout(resolve, 3000)), |
| 675 | 854 | ]) |
| @@ -700,8 +879,9 @@ | ||
| 700 | 879 | id, |
| 701 | 880 | inputs, |
| 702 | 881 | result: toolData, |
| 703 | 882 | label: labels?.confirm, |
| 883 | + started: labels?.started, | |
| 704 | 884 | }); |
| 705 | 885 | setWaitingOnToolOrUser(false); |
| 706 | 886 | agentWorking.current = false; |
| 707 | 887 | setLoop((prev) => prev + 1); // Trigger next loop |
| @@ -747,10 +927,8 @@ | ||
| 747 | 927 | setWhenFinishedToolProps, |
| 748 | 928 | block, |
| 749 | 929 | setBlock, |
| 750 | 930 | findAgent, |
| 751 | - addSuggestions, | |
| 752 | - getSuggestions, | |
| 753 | 931 | ]); |
| 754 | 932 | |
| 755 | 933 | useEffect(() => { |
| 756 | 934 | if (!canType) return; |
| @@ -756,42 +934,63 @@ | ||
| 756 | 934 | if (!canType) return; |
| 757 | 935 | document.querySelector('#extendify-agent-chat-textarea')?.focus(); |
| 758 | 936 | }, [canType]); |
| 759 | 937 | |
| 760 | - 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); | |
| 761 | 945 | // `busy` is true at rest; 429 is blocked, not working. |
| 762 | 946 | const working = !canType && chatAvailable; |
| 763 | 947 | |
| 764 | 948 | return ( |
| 765 | - <Chat busy={busy} working={working}> | |
| 766 | - <div className="relative z-50 flex h-full flex-col justify-between overflow-auto"> | |
| 767 | - <ChatMessages | |
| 768 | - redirectComponent={ | |
| 769 | - workflow?.needsRedirect?.() ? workflow.redirectComponent : null | |
| 770 | - } | |
| 771 | - /> | |
| 772 | - <div> | |
| 773 | - <div className="relative flex flex-col px-4 pb-2 pt-2.5 shadow-lg-flipped"> | |
| 774 | - <UsageMessage | |
| 775 | - onReady={() => { | |
| 776 | - cleanup(); | |
| 777 | - pushStatus('credits-restored'); | |
| 778 | - }} | |
| 779 | - /> | |
| 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> | |
| 780 | 991 | </div> |
| 781 | - <div className="p-4 pb-2 pt-0"> | |
| 782 | - <ChatInput | |
| 783 | - disabled={!canType || !chatAvailable || !!qaSuggestions} | |
| 784 | - handleSubmit={handleSubmit} | |
| 785 | - /> | |
| 786 | - </div> | |
| 787 | - <div className="text-pretty px-4 pb-2 text-center text-xss leading-none text-gray-700"> | |
| 788 | - {__( | |
| 789 | - 'AI Agent can make mistakes. Check changes before saving.', | |
| 790 | - 'extendify-local', | |
| 791 | - )} | |
| 792 | - </div> | |
| 793 | 992 | </div> |
| 794 | - </div> | |
| 795 | - </Chat> | |
| 993 | + </Chat> | |
| 994 | + </> | |
| 796 | 995 | ); |
| 797 | 996 | }; |