@conduction/nextcloud-vue 2.171.0 → 2.173.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/esm/components/CnActionDialog/CnActionDialog.vue.js +1 -1
  2. package/dist/esm/components/CnActionDialog/CnActionDialog.vue2.js.map +1 -1
  3. package/dist/esm/components/CnActionDialog/CnActionDialog.vue3.js.map +1 -1
  4. package/dist/esm/components/CnAiCompanion/CnAiChatWidget.vue2.js +3 -2
  5. package/dist/esm/components/CnAiCompanion/CnAiChatWidget.vue2.js.map +1 -1
  6. package/dist/esm/components/CnAiCompanion/CnAiChatWidget.vue3.js +2 -1
  7. package/dist/esm/components/CnAiCompanion/CnAiChatWidget.vue3.js.map +1 -1
  8. package/dist/esm/components/CnAiCompanion/CnAiCompanion.vue2.js +39 -0
  9. package/dist/esm/components/CnAiCompanion/CnAiCompanion.vue2.js.map +1 -1
  10. package/dist/esm/components/CnAiCompanion/CnAiCompanion.vue3.js.map +1 -1
  11. package/dist/esm/components/CnChecklistRunWidget/CnChecklistRunWidget.vue.js +1 -1
  12. package/dist/esm/components/CnChecklistRunWidget/CnChecklistRunWidget.vue2.js +22 -3
  13. package/dist/esm/components/CnChecklistRunWidget/CnChecklistRunWidget.vue2.js.map +1 -1
  14. package/dist/esm/components/CnChecklistRunWidget/CnChecklistRunWidget.vue3.js.map +1 -1
  15. package/dist/esm/components/CnDashboardGrid/CnDashboardGrid.vue.js +1 -1
  16. package/dist/esm/components/CnDashboardGrid/CnDashboardGrid.vue2.js.map +1 -1
  17. package/dist/esm/components/CnDashboardGrid/CnDashboardGrid.vue3.js.map +1 -1
  18. package/dist/esm/components/CnDeviceFramesWidget/CnDeviceFramesWidget.vue.js +1 -1
  19. package/dist/esm/components/CnDeviceFramesWidget/CnDeviceFramesWidget.vue2.js +75 -4
  20. package/dist/esm/components/CnDeviceFramesWidget/CnDeviceFramesWidget.vue2.js.map +1 -1
  21. package/dist/esm/components/CnDeviceFramesWidget/CnDeviceFramesWidget.vue3.js.map +1 -1
  22. package/dist/esm/components/CnFactsWidget/CnFactsWidget.vue.js +1 -1
  23. package/dist/esm/components/CnFactsWidget/CnFactsWidget.vue2.js +7 -3
  24. package/dist/esm/components/CnFactsWidget/CnFactsWidget.vue2.js.map +1 -1
  25. package/dist/esm/components/CnFactsWidget/CnFactsWidget.vue3.js.map +1 -1
  26. package/dist/esm/components/CnFilesBrowser/CnFilesBrowser.vue.js +1 -1
  27. package/dist/esm/components/CnFilesBrowser/CnFilesBrowser.vue2.js +34 -4
  28. package/dist/esm/components/CnFilesBrowser/CnFilesBrowser.vue2.js.map +1 -1
  29. package/dist/esm/components/CnFilesBrowser/CnFilesBrowser.vue3.js +42 -34
  30. package/dist/esm/components/CnFilesBrowser/CnFilesBrowser.vue3.js.map +1 -1
  31. package/dist/esm/components/CnFlowsPage/CnFlowBoard.vue.js +1 -1
  32. package/dist/esm/components/CnFlowsPage/CnFlowBoard.vue2.js +21 -6
  33. package/dist/esm/components/CnFlowsPage/CnFlowBoard.vue2.js.map +1 -1
  34. package/dist/esm/components/CnFlowsPage/CnFlowBoard.vue3.js.map +1 -1
  35. package/dist/esm/components/CnTreeView/CnTreeNode.vue.js +1 -1
  36. package/dist/esm/components/CnTreeView/CnTreeNode.vue2.js +54 -4
  37. package/dist/esm/components/CnTreeView/CnTreeNode.vue2.js.map +1 -1
  38. package/dist/esm/components/CnTreeView/CnTreeNode.vue3.js +32 -26
  39. package/dist/esm/components/CnTreeView/CnTreeNode.vue3.js.map +1 -1
  40. package/dist/esm/components/CnTreeView/CnTreeView.vue.js +1 -1
  41. package/dist/esm/components/CnTreeView/CnTreeView.vue2.js +28 -4
  42. package/dist/esm/components/CnTreeView/CnTreeView.vue2.js.map +1 -1
  43. package/dist/esm/components/CnTreeView/CnTreeView.vue3.js +4 -1
  44. package/dist/esm/components/CnTreeView/CnTreeView.vue3.js.map +1 -1
  45. package/dist/esm/composables/aiChatConfig.js +13 -1
  46. package/dist/esm/composables/aiChatConfig.js.map +1 -1
  47. package/dist/esm/composables/useAiChatStream.js +53 -1
  48. package/dist/esm/composables/useAiChatStream.js.map +1 -1
  49. package/dist/esm/library-style.js +1 -1
  50. package/dist/esm/nextcloud-vue.css +745 -403
  51. package/dist/esm/utils/builtInFormatters.js +19 -1
  52. package/dist/esm/utils/builtInFormatters.js.map +1 -1
  53. package/dist/nextcloud-vue.cjs.js +919 -569
  54. package/dist/nextcloud-vue.cjs.js.map +2 -2
  55. package/dist/nextcloud-vue.css +745 -403
  56. package/package.json +1 -1
  57. package/src/components/CnActionDialog/CnActionDialog.vue +4 -1
  58. package/src/components/CnAiCompanion/CnAiChatWidget.md +1 -0
  59. package/src/components/CnAiCompanion/CnAiChatWidget.vue +4 -2
  60. package/src/components/CnAiCompanion/CnAiCompanion.md +1 -0
  61. package/src/components/CnAiCompanion/CnAiCompanion.vue +39 -0
  62. package/src/components/CnChecklistRunWidget/CnChecklistRunWidget.vue +24 -3
  63. package/src/components/CnDashboardGrid/CnDashboardGrid.vue +5 -2
  64. package/src/components/CnDeviceFramesWidget/CnDeviceFramesWidget.vue +75 -4
  65. package/src/components/CnFactsWidget/CnFactsWidget.vue +7 -3
  66. package/src/components/CnFilesBrowser/CnFilesBrowser.vue +45 -4
  67. package/src/components/CnFlowsPage/CnFlowBoard.vue +27 -6
  68. package/src/components/CnTreeView/CnTreeNode.vue +69 -6
  69. package/src/components/CnTreeView/CnTreeView.vue +31 -4
  70. package/src/composables/aiChatConfig.js +12 -0
  71. package/src/composables/useAiChatStream.js +53 -0
  72. package/src/css/look-board-detail.css +200 -6
  73. package/src/css/look-board-index.css +7 -6
  74. package/src/css/look-board.css +118 -0
  75. package/src/css/patches.css +4 -1
  76. package/src/utils/builtInFormatters.js +18 -0
@@ -1,6 +1,6 @@
1
1
  import axios__default from '@nextcloud/axios';
2
2
  import { reactive } from 'vue';
3
- import { DEFAULT_CHAT_APP_ID, chatStreamUrl, chatSendUrl, conversationMessagesUrl } from './aiChatConfig.js';
3
+ import { DEFAULT_CHAT_APP_ID, chatStreamUrl, chatSendUrl, conversationMessagesUrl, sessionsUrl } from './aiChatConfig.js';
4
4
  import { useAiContext } from './useAiContext.js';
5
5
  import { fetchEventSource } from '../node_modules/@microsoft/fetch-event-source/lib/esm/fetch.js';
6
6
 
@@ -476,8 +476,13 @@ function useAiChatStream(contextInstance, options = {}) {
476
476
  * conversations identically to live ones. OR does not persist tool calls
477
477
  * on messages, so toolCalls degrades to [].
478
478
  *
479
+ * The approvals the agent still waits on come with the messages
480
+ * (`pendingApprovals`, the shape of the stream's `final` event), so a
481
+ * reopened conversation shows them as a live turn does.
482
+ *
479
483
  * @param {string} conversationUuid - UUID of the conversation to resume
480
484
  * @returns {Promise<void>}
485
+ * @spec openspec/changes/ai-chat-opens-the-subject-session/specs/ai-companion/spec.md#requirement-a-loaded-conversation-keeps-its-pending-approvals
481
486
  */
482
487
  async function loadConversation(conversationUuid) {
483
488
  try {
@@ -496,6 +501,7 @@ function useAiChatStream(contextInstance, options = {}) {
496
501
  content: m.content || '',
497
502
  toolCalls: m.toolCalls || m.tool_calls || [],
498
503
  }));
504
+ state.pendingApprovals = Array.isArray(data.pendingApprovals) ? data.pendingApprovals : [];
499
505
  // Don't force a new thread — resume this conversation, and remember its
500
506
  // uuid so the next send() continues it instead of starting a new one.
501
507
  state._newThread = false;
@@ -506,6 +512,35 @@ function useAiChatStream(contextInstance, options = {}) {
506
512
  }
507
513
  }
508
514
 
515
+ /**
516
+ * Open the user's most recent session about one record, if there is one.
517
+ *
518
+ * A session is accepted only when its subject is that record, so a backend
519
+ * that ignores the `subject` filter leaves the thread empty instead of
520
+ * opening a conversation about something else.
521
+ *
522
+ * @param {string} objectUuid The record the page is about.
523
+ * @return {Promise<boolean>} Whether a session was opened.
524
+ * @spec openspec/changes/ai-chat-opens-the-subject-session/specs/ai-companion/spec.md#requirement-an-embedded-chat-may-open-the-users-session-about-the-pages-record
525
+ */
526
+ async function loadSubjectSession(objectUuid) {
527
+ let sessions;
528
+ try {
529
+ const response = await axios__default.get(sessionsUrl(chatAppId), { params: { subject: objectUuid, limit: 1 } });
530
+ sessions = Array.isArray(response.data?.results) ? response.data.results : [];
531
+ } catch (err) {
532
+ // eslint-disable-next-line no-console
533
+ console.info('[useAiChatStream] Could not list the sessions about the record:', err?.message);
534
+ return false
535
+ }
536
+ const session = sessions.find((candidate) => subjectOf(candidate) === objectUuid);
537
+ if (!session) {
538
+ return false
539
+ }
540
+ await loadConversation(session.uuid || session.id);
541
+ return state.conversationUuid !== null
542
+ }
543
+
509
544
  return {
510
545
  // Reactive state (accessed as state.isStreaming etc. from the component)
511
546
  state,
@@ -514,7 +549,24 @@ function useAiChatStream(contextInstance, options = {}) {
514
549
  abort,
515
550
  startNewThread,
516
551
  loadConversation,
552
+ loadSubjectSession,
553
+ }
554
+ }
555
+
556
+ /**
557
+ * The record a session is about: `subject.objectUuid`, or the same under its
558
+ * `metadata`, where the session stores it.
559
+ *
560
+ * @param {object} session A session from the session list.
561
+ * @return {string} The record's uuid, or '' when the session names none.
562
+ * @spec openspec/changes/ai-chat-opens-the-subject-session/specs/ai-companion/spec.md#requirement-an-embedded-chat-may-open-the-users-session-about-the-pages-record
563
+ */
564
+ function subjectOf(session) {
565
+ const subject = session?.subject || session?.metadata?.subject;
566
+ if (typeof subject === 'string') {
567
+ return subject
517
568
  }
569
+ return (subject && typeof subject.objectUuid === 'string') ? subject.objectUuid : ''
518
570
  }
519
571
 
520
572
  export { useAiChatStream };
@@ -1 +1 @@
1
- {"version":3,"file":"useAiChatStream.js","sources":["../../../src/composables/useAiChatStream.js"],"sourcesContent":["/**\n * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl>\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\n * useAiChatStream — Conversation transport composable for the AI Chat Companion.\n *\n * Owns the full SSE lifecycle:\n * - Attempts POST /index.php/apps/{chatAppId}/api/chat/stream via\n * @microsoft/fetch-event-source (handles POST body, abort signals, reconnect,\n * and SSE frame parsing).\n * - Handles the six-event envelope: token, tool_call, tool_result, heartbeat,\n * final, error.\n * - Falls back to POST /index.php/apps/{chatAppId}/api/chat/send via axios\n * when the streaming endpoint returns 404/501 or fails mid-handshake,\n * synthesising a single \"final\" event so rendering code does not branch.\n * - Sends the active cnAiContext snapshot in every outgoing request body.\n * - Tracks `state.conversationUuid`, the server-side Conversation the active\n * session is writing to (set from the `final` event's `conversationUuid` /\n * the fallback response's `conversation` field, both already on the wire).\n * Every send() echoes it back under both key spellings the two backend\n * controllers read (`conversation` / `conversationUuid`) so a multi-turn\n * session stays one Conversation row server-side instead of implicitly\n * starting a new one on every turn — previously neither key was ever sent.\n *\n * The backend app id (`chatAppId`) is a single configuration point — see\n * ./aiChatConfig.js. It defaults to `hermiq` (per hydra ADR-034 \"Amendment\n * 2026-07-05\"); pass `{ chatAppId }` to target another backend (e.g.\n * `openregister` during its compat window) without touching this file.\n */\n\nimport { fetchEventSource } from '@microsoft/fetch-event-source'\nimport axios from '@nextcloud/axios'\nimport { reactive } from 'vue'\nimport {\n\tchatSendUrl,\n\tchatStreamUrl,\n\tconversationMessagesUrl,\n\tDEFAULT_CHAT_APP_ID,\n} from './aiChatConfig.js'\nimport { useAiContext } from './useAiContext.js'\n\n/**\n * Factory that creates and returns a reactive AI chat stream state object.\n *\n * This follows the Vue 2 \"factory composable\" pattern — it returns a plain\n * reactive object (via Vue.observable) rather than Vue 3 refs. One instance\n * should be created per CnAiCompanion mount.\n *\n * @param {object} [contextInstance] Vue component instance to read cnAiContext from.\n * Pass the CnAiCompanion component instance so the outgoing request includes\n * the current page context.\n * @param {object} [options] Transport options.\n * @param {string} [options.chatAppId] Backend app id the chat/conversation URLs\n * resolve against. Defaults to {@link DEFAULT_CHAT_APP_ID} (`openregister`).\n * @returns {object} Reactive state + methods\n */\nexport function useAiChatStream(contextInstance, options = {}) {\n\t/** Backend app id for every URL this composable builds (see aiChatConfig.js) */\n\tconst chatAppId = options.chatAppId || DEFAULT_CHAT_APP_ID\n\tconst STREAM_URL = chatStreamUrl(chatAppId)\n\tconst SEND_URL = chatSendUrl(chatAppId)\n\t/** Stable reactive state object */\n\tconst state = reactive({\n\t\t/** Whether an SSE or fallback request is in-flight */\n\t\tisStreaming: false,\n\t\t/** Partial assistant text built from token events */\n\t\tcurrentText: '',\n\t\t/** Tool call entries: { toolId, arguments, result?, isError? } */\n\t\ttoolCalls: [],\n\t\t/**\n\t\t * Approvals the agent is waiting on, so they can be decided HERE.\n\t\t *\n\t\t * Deliberately generic: each entry carries its own `kind` and its own\n\t\t * `resolveUrl`, so a new approval type (fetching a URL, editing a file\n\t\t * that is not open) is rendered and resolved by this same code with no\n\t\t * change — the server says where the decision is posted.\n\t\t *\n\t\t * Shape: { id, kind, title, app, reach, reason, agentId, resolveUrl }\n\t\t */\n\t\tpendingApprovals: [],\n\t\t/** Error state: { code, message } | null */\n\t\terror: null,\n\t\t/** Full conversation message history for the current session */\n\t\tmessages: [],\n\t\t/** Whether the next send() should signal OR to start a new Conversation row */\n\t\t_newThread: false,\n\t\t/**\n\t\t * UUID of the conversation currently being written to, or null before the\n\t\t * first turn. Populated from the `final` SSE event's `conversationUuid`\n\t\t * field / the non-streaming fallback's `conversation` field (both already\n\t\t * on the wire — see finalise()) and echoed back on every subsequent send()\n\t\t * so the whole session stays one Conversation server-side instead of a new\n\t\t * one per turn. Reset by startNewThread(), set directly by loadConversation().\n\t\t */\n\t\tconversationUuid: null,\n\t})\n\n\t/** AbortController for the active fetchEventSource call */\n\tlet abortController = null\n\t/** Resolve/reject for the Promise returned by send() */\n\tlet _resolve = null\n\tlet _reject = null\n\n\t/**\n\t * Get the current cnAiContext snapshot for inclusion in request bodies.\n\t *\n\t * @returns {object}\n\t */\n\tfunction getContextSnapshot() {\n\t\t// An EXPLICIT context wins over the injected one.\n\t\t//\n\t\t// The injected path assumes a CnAppRoot ancestor provides the context.\n\t\t// A companion mounted standalone on a page that is not ours has no such\n\t\t// ancestor, so it falls back to `defaultContext` — whose `appId` is the\n\t\t// literal string 'unknown'. The agent then receives \"app context:\n\t\t// unknown\" and, correctly, refuses to act: measured, it answered a\n\t\t// document edit request with \"I don't have a clear app context\" while\n\t\t// the user was looking straight at the document.\n\t\t//\n\t\t// The host that mounted the companion is the one thing that DOES know\n\t\t// what page it is on, so it may state it.\n\t\tconst ctx = options.context || useAiContext(contextInstance)\n\n\t\treturn {\n\t\t\tappId: ctx.appId,\n\t\t\tpageKind: ctx.pageKind,\n\t\t\tobjectUuid: ctx.objectUuid,\n\t\t\tregisterSlug: ctx.registerSlug,\n\t\t\tschemaSlug: ctx.schemaSlug,\n\t\t\tfileId: ctx.fileId,\n\t\t\troute: ctx.route,\n\t\t}\n\t}\n\n\t/**\n\t * Handle an individual SSE message frame.\n\t *\n\t * @param {object} msg - { event, data } from fetchEventSource\n\t */\n\tfunction handleSseMessage(msg) {\n\t\tconst { event, data } = msg\n\t\tlet parsed\n\t\ttry {\n\t\t\tparsed = JSON.parse(data)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\n\t\tswitch (event) {\n\t\t\tcase 'token':\n\t\t\t\tstate.currentText += (parsed.delta || '')\n\t\t\t\tbreak\n\n\t\t\tcase 'tool_call':\n\t\t\t\tstate.toolCalls.push({\n\t\t\t\t\ttoolId: parsed.toolId,\n\t\t\t\t\targuments: parsed.arguments,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\tisError: false,\n\t\t\t\t})\n\t\t\t\tbreak\n\n\t\t\tcase 'tool_result': {\n\t\t\t\tconst entry = state.toolCalls.find((tc) => tc.toolId === parsed.toolId)\n\t\t\t\tif (entry) {\n\t\t\t\t\tentry.result = parsed.result\n\t\t\t\t\tentry.isError = Boolean(parsed.isError)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'heartbeat':\n\t\t\t// Liveness signal only — no UI update\n\t\t\t\tbreak\n\n\t\t\tcase 'final':\n\t\t\t// Commit the streamed text as a finalised assistant message.\n\t\t\t// If no `token` events arrived (non-streaming-provider fallback path —\n\t\t\t// the contract allows the server to emit only the terminal `final`\n\t\t\t// event with `fullText` for providers that don't stream), seed\n\t\t\t// `currentText` from the payload so the assistant bubble renders.\n\t\t\t\tif (state.currentText === '' && typeof parsed.fullText === 'string') {\n\t\t\t\t\tstate.currentText = parsed.fullText\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(parsed.pendingApprovals)) {\n\t\t\t\t\tstate.pendingApprovals = parsed.pendingApprovals\n\t\t\t\t}\n\t\t\t\tfinalise(parsed.messageId, parsed.conversationUuid, parsed)\n\t\t\t\tbreak\n\n\t\t\tcase 'error':\n\t\t\t\tfail(parsed.code || 'unknown', parsed.message || 'Unknown error')\n\t\t\t\tbreak\n\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\t/**\n\t * Push the completed assistant message into state.messages and resolve send().\n\t *\n\t * @param {string|undefined} messageId - Server-supplied id from the final event;\n\t * when empty/missing we synthesise a stable client-side id so Vue's :key\n\t * stays unique within the conversation.\n\t * @param {string|undefined} [conversationUuid] - The conversation this turn was\n\t * written to (SSE `final.conversationUuid` / fallback `.conversation`). Stored\n\t * on state so the *next* send() continues the same server-side Conversation\n\t * instead of implicitly starting a new one every turn.\n\t * @param {object} [extras] - The `final` frame (or JSON reply); its\n\t * `attachments` and `attachmentNotices` arrays are kept on the message.\n\t */\n\tfunction finalise(messageId, conversationUuid, extras) {\n\t\tconst assistantMessage = {\n\t\t\tid: (typeof messageId === 'string' && messageId !== '')\n\t\t\t\t? messageId\n\t\t\t\t: `client-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,\n\t\t\trole: 'assistant',\n\t\t\tcontent: state.currentText,\n\t\t\ttoolCalls: state.toolCalls.slice(),\n\t\t}\n\t\tif (Array.isArray(extras?.attachments)) {\n\t\t\tassistantMessage.attachments = extras.attachments\n\t\t}\n\t\tif (Array.isArray(extras?.attachmentNotices)) {\n\t\t\tassistantMessage.attachmentNotices = extras.attachmentNotices\n\t\t}\n\t\tstate.messages.push(assistantMessage)\n\t\tif (typeof conversationUuid === 'string' && conversationUuid !== '') {\n\t\t\tstate.conversationUuid = conversationUuid\n\t\t}\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tstate.isStreaming = false\n\t\tif (_resolve) {\n\t\t\t_resolve()\n\t\t\t_resolve = null\n\t\t\t_reject = null\n\t\t}\n\t}\n\n\t/**\n\t * Handle an error event or transport failure.\n\t *\n\t * @param {string} code - Machine-readable error code (e.g. 'rate_limited', 'connection_error')\n\t * @param {string} message - Human-readable error message for the UI\n\t */\n\tfunction fail(code, message) {\n\t\tstate.isStreaming = false\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tstate.error = { code, message }\n\t\tif (_reject) {\n\t\t\tconst err = new Error(message)\n\t\t\terr.code = code\n\t\t\t_reject(err)\n\t\t\t_resolve = null\n\t\t\t_reject = null\n\t\t}\n\t}\n\n\t/**\n\t * Non-streaming fallback: POST to /api/chat/send via axios, then synthesise\n\t * a single \"final\" event from the JSON response.\n\t *\n\t * @param {string} content - The user's message text\n\t * @param {object} body - Request body already built by send() (message, context, newThread)\n\t */\n\tasync function sendFallback(content, body) {\n\t\ttry {\n\t\t\tconst response = await axios.post(SEND_URL, body)\n\t\t\tconst data = response.data\n\t\t\t// Treat the response as a final event — populate currentText from the reply\n\t\t\tconst replyContent = data?.content || data?.message || data?.reply || ''\n\t\t\tstate.currentText = replyContent\n\t\t\t// Same two fields the SSE `final` event carries, so the fallback path\n\t\t\t// shows tool steps and approvals exactly as the streaming one does.\n\t\t\tif (Array.isArray(data?.toolCalls)) {\n\t\t\t\tstate.toolCalls = data.toolCalls\n\t\t\t}\n\t\t\tif (Array.isArray(data?.pendingApprovals)) {\n\t\t\t\tstate.pendingApprovals = data.pendingApprovals\n\t\t\t}\n\t\t\t// ChatController::sendMessage() echoes the conversation uuid back as\n\t\t\t// `conversation` (ChatStreamController's SSE `final` event uses\n\t\t\t// `conversationUuid` instead — see finalise() caller in handleSseMessage).\n\t\t\tfinalise(undefined, data?.conversation || data?.conversationUuid, data)\n\t\t} catch (err) {\n\t\t\tconst code = err.response?.status?.toString() || 'network_error'\n\t\t\tconst message = err.message || 'Fallback request failed'\n\t\t\tfail(code, message)\n\t\t}\n\t}\n\n\t/**\n\t * Send a user message. Attempts the SSE stream first; falls back to the\n\t * non-streaming endpoint on 404/501 or connection failure.\n\t *\n\t * @param {string} content - The user's message text\n\t * @param {object} [options] - Send options\n\t * @param {boolean} [options.newThread] - Force a new Conversation row on the server\n\t * @param {string} [options.agentUuid] - Agent to start a *new* conversation with\n\t * (agent-picker selection). Ignored server-side once a conversation uuid is\n\t * resolved — safe to pass on every call.\n\t * @param {Array<{path: string, name: string, fileId?: number}>} [options.attachments] - Files\n\t * already uploaded via the attachments endpoint (see aiChatConfig.js\n\t * `attachmentsUrl()`), to be read by the backend from `body.attachments`.\n\t * Omitted from the request body entirely when empty so existing backends\n\t * that don't yet read the key see no change to the payload shape.\n\t * @returns {Promise<void>} Resolves on \"final\", rejects on \"error\" or abort\n\t */\n\tfunction send(content, options = {}) {\n\t\tif (state.isStreaming) {\n\t\t\treturn Promise.reject(new Error('A stream is already in progress'))\n\t\t}\n\n\t\t// Push the user message into the local history immediately\n\t\tconst userMessage = { role: 'user', content }\n\t\tif (Array.isArray(options.attachments) && options.attachments.length > 0) {\n\t\t\tuserMessage.attachments = options.attachments\n\t\t}\n\t\tstate.messages.push(userMessage)\n\t\tstate.isStreaming = true\n\t\tstate.error = null\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\n\t\tconst newThread = options.newThread || state._newThread\n\t\tstate._newThread = false\n\n\t\t// The conversation this send() continues — '' (never sent) forces both\n\t\t// controllers to create a fresh Conversation row. Cleared on a new thread\n\t\t// so the *next* turn starts a new server-side conversation instead of\n\t\t// reusing the one that just ended.\n\t\tconst activeConversationUuid = newThread ? '' : (state.conversationUuid || '')\n\t\tif (newThread) {\n\t\t\tstate.conversationUuid = null\n\t\t}\n\n\t\t// OR's ChatStreamController reads `$body['message']` (matches the existing\n\t\t// non-streaming `/api/chat/send` request shape). We keep `content` as a\n\t\t// fallback alias for clients that already used the old field name — the\n\t\t// controller ignores unknown keys. Conversation continuity is likewise\n\t\t// duplicated under both key spellings the two backend endpoints read\n\t\t// (ChatController::extractMessageRequestParams() reads `conversation`,\n\t\t// ChatStreamController::stream() reads `conversationUuid`); `agentUuid` is\n\t\t// the same key on both and only consulted when no conversation is resolved.\n\t\tconst body = {\n\t\t\tmessage: content,\n\t\t\tcontent,\n\t\t\tcontext: getContextSnapshot(),\n\t\t\tnewThread,\n\t\t\tconversation: activeConversationUuid,\n\t\t\tconversationUuid: activeConversationUuid,\n\t\t\tagentUuid: options.agentUuid || '',\n\t\t}\n\t\t// Only add the key when there's something to send — keeps the payload\n\t\t// shape unchanged (and any backend not yet reading `attachments`\n\t\t// unaffected) for the common no-attachment turn.\n\t\tif (Array.isArray(options.attachments) && options.attachments.length > 0) {\n\t\t\tbody.attachments = options.attachments\n\t\t}\n\n\t\tabortController = new AbortController()\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\t_resolve = resolve\n\t\t\t_reject = reject\n\n\t\t\tfetchEventSource(STREAM_URL, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'X-Requested-With': 'XMLHttpRequest',\n\t\t\t\t\t// Nextcloud's CSRF middleware accepts either the\n\t\t\t\t\t// requesttoken header or X-Requested-With. We send\n\t\t\t\t\t// both so the SSE POST works whether or not the\n\t\t\t\t\t// app's controller opts out of CSRF (the orchestrator\n\t\t\t\t\t// keeps CSRF on; see ChatStreamController docblock).\n\t\t\t\t\trequesttoken: typeof OC !== 'undefined' ? OC.requestToken : '',\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\tsignal: abortController.signal,\n\n\t\t\t\tasync onopen(response) {\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\t// Happy path — SSE stream opened\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Treat 404/501 as \"streaming not available\" — fall back\n\t\t\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\t\t\t// Throw a custom error that onmessage/onerror won't catch\n\t\t\t\t\t\tthrow Object.assign(new Error('streaming_unavailable'), {\n\t\t\t\t\t\t\tisFallback: true,\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\t// Other HTTP errors — propagate\n\t\t\t\t\tthrow new Error(`SSE open failed: ${response.status}`)\n\t\t\t\t},\n\n\t\t\t\tonmessage(msg) {\n\t\t\t\t\thandleSseMessage(msg)\n\t\t\t\t},\n\n\t\t\t\tonerror(err) {\n\t\t\t\t\tif (err && err.isFallback) {\n\t\t\t\t\t\t// Signal to the catch block that we need the fallback\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}\n\t\t\t\t\t// fetchEventSource calls onerror for connection issues and will\n\t\t\t\t\t// automatically retry. We convert terminal errors to fail().\n\t\t\t\t\tfail('connection_error', err?.message || 'Connection error')\n\t\t\t\t\tthrow err // Stop retrying\n\t\t\t\t},\n\n\t\t\t\tonclose() {\n\t\t\t\t\t// Stream closed without a \"final\" event — treat as connection reset\n\t\t\t\t\tif (state.isStreaming) {\n\t\t\t\t\t\tfail('connection_closed', 'Stream closed unexpectedly')\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}).catch((err) => {\n\t\t\t\tif (err && err.isFallback) {\n\t\t\t\t\t// Non-streaming fallback path\n\t\t\t\t\treturn sendFallback(content, body)\n\t\t\t\t}\n\t\t\t\tif (err && err.name === 'AbortError') {\n\t\t\t\t\t// Intentional abort — already handled by abort()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfail(err?.code || 'unknown', err?.message || 'Unknown error')\n\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * Abort the currently in-flight stream.\n\t * Rejects the send() Promise with a cancellation error.\n\t */\n\tfunction abort() {\n\t\tif (abortController) {\n\t\t\tabortController.abort()\n\t\t\tabortController = null\n\t\t}\n\t\tstate.isStreaming = false\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tif (_reject) {\n\t\t\tconst err = new Error('Reply was cancelled')\n\t\t\terr.code = 'cancelled'\n\t\t\t_reject(err)\n\t\t\t_resolve = null\n\t\t\t_reject = null\n\t\t}\n\t}\n\n\t/**\n\t * Discard current conversation state and signal OR to start a fresh\n\t * Conversation row on the next send() call.\n\t */\n\tfunction startNewThread() {\n\t\tif (state.isStreaming) {\n\t\t\tabort()\n\t\t}\n\t\tstate.messages = []\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tstate.error = null\n\t\tstate._newThread = true\n\t\tstate.conversationUuid = null\n\t}\n\n\t/**\n\t * Load an existing conversation's messages into the state.\n\t * Used by CnAiHistoryDialog when the user selects a past conversation.\n\t *\n\t * Fetches GET /api/conversations/{uuid}/messages (OR's conversation#messages\n\t * route), which returns { results: [...] } ordered oldest-first. Each OR\n\t * message carries { id, uuid, conversationId, role, content, sources,\n\t * context, created } — mapped here onto the { role, content, toolCalls }\n\t * shape the send/stream paths produce so CnAiMessageList renders resumed\n\t * conversations identically to live ones. OR does not persist tool calls\n\t * on messages, so toolCalls degrades to [].\n\t *\n\t * @param {string} conversationUuid - UUID of the conversation to resume\n\t * @returns {Promise<void>}\n\t */\n\tasync function loadConversation(conversationUuid) {\n\t\ttry {\n\t\t\tconst response = await axios.get(\n\t\t\t\tconversationMessagesUrl(chatAppId, conversationUuid),\n\t\t\t\t// The backend controller defaults to 50 messages; raise the limit\n\t\t\t\t// so long threads resume fully.\n\t\t\t\t{ params: { limit: 200 } },\n\t\t\t)\n\t\t\tconst data = response.data\n\t\t\tconst messages = Array.isArray(data.results)\n\t\t\t\t? data.results\n\t\t\t\t: (Array.isArray(data.messages) ? data.messages : [])\n\t\t\tstate.messages = messages.map((m) => ({\n\t\t\t\trole: m.role || 'assistant',\n\t\t\t\tcontent: m.content || '',\n\t\t\t\ttoolCalls: m.toolCalls || m.tool_calls || [],\n\t\t\t}))\n\t\t\t// Don't force a new thread — resume this conversation, and remember its\n\t\t\t// uuid so the next send() continues it instead of starting a new one.\n\t\t\tstate._newThread = false\n\t\t\tstate.conversationUuid = conversationUuid\n\t\t} catch (err) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.info('[useAiChatStream] Could not load conversation:', err?.message)\n\t\t}\n\t}\n\n\treturn {\n\t\t// Reactive state (accessed as state.isStreaming etc. from the component)\n\t\tstate,\n\t\t// Methods\n\t\tsend,\n\t\tabort,\n\t\tstartNewThread,\n\t\tloadConversation,\n\t}\n}\n"],"names":["axios"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAWA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,eAAe,CAAC,eAAe,EAAE,OAAO,GAAG,EAAE,EAAE;AAC/D;AACA,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,oBAAmB;AAC3D,CAAC,MAAM,UAAU,GAAG,aAAa,CAAC,SAAS,EAAC;AAC5C,CAAC,MAAM,QAAQ,GAAG,WAAW,CAAC,SAAS,EAAC;AACxC;AACA,CAAC,MAAM,KAAK,GAAG,QAAQ,CAAC;AACxB;AACA,EAAE,WAAW,EAAE,KAAK;AACpB;AACA,EAAE,WAAW,EAAE,EAAE;AACjB;AACA,EAAE,SAAS,EAAE,EAAE;AACf;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,EAAE,gBAAgB,EAAE,EAAE;AACtB;AACA,EAAE,KAAK,EAAE,IAAI;AACb;AACA,EAAE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,OAAO,GAAG,EAAE;AAChB;AACA,GAAG,OAAO,CAAC,IAAI,CAAC,gDAAgD,EAAE,GAAG,EAAE,OAAO,EAAC;AAC/E,GAAG;AACH,EAAE;AACF;AACA,CAAC,OAAO;AACR;AACA,EAAE,KAAK;AACP;AACA,EAAE,IAAI;AACN,EAAE,KAAK;AACP,EAAE,cAAc;AAChB,EAAE,gBAAgB;AAClB,EAAE;AACF;;;;"}
1
+ {"version":3,"file":"useAiChatStream.js","sources":["../../../src/composables/useAiChatStream.js"],"sourcesContent":["/**\n * SPDX-FileCopyrightText: 2024 Conduction B.V. <info@conduction.nl>\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\n * useAiChatStream — Conversation transport composable for the AI Chat Companion.\n *\n * Owns the full SSE lifecycle:\n * - Attempts POST /index.php/apps/{chatAppId}/api/chat/stream via\n * @microsoft/fetch-event-source (handles POST body, abort signals, reconnect,\n * and SSE frame parsing).\n * - Handles the six-event envelope: token, tool_call, tool_result, heartbeat,\n * final, error.\n * - Falls back to POST /index.php/apps/{chatAppId}/api/chat/send via axios\n * when the streaming endpoint returns 404/501 or fails mid-handshake,\n * synthesising a single \"final\" event so rendering code does not branch.\n * - Sends the active cnAiContext snapshot in every outgoing request body.\n * - Tracks `state.conversationUuid`, the server-side Conversation the active\n * session is writing to (set from the `final` event's `conversationUuid` /\n * the fallback response's `conversation` field, both already on the wire).\n * Every send() echoes it back under both key spellings the two backend\n * controllers read (`conversation` / `conversationUuid`) so a multi-turn\n * session stays one Conversation row server-side instead of implicitly\n * starting a new one on every turn — previously neither key was ever sent.\n *\n * The backend app id (`chatAppId`) is a single configuration point — see\n * ./aiChatConfig.js. It defaults to `hermiq` (per hydra ADR-034 \"Amendment\n * 2026-07-05\"); pass `{ chatAppId }` to target another backend (e.g.\n * `openregister` during its compat window) without touching this file.\n */\n\nimport { fetchEventSource } from '@microsoft/fetch-event-source'\nimport axios from '@nextcloud/axios'\nimport { reactive } from 'vue'\nimport {\n\tchatSendUrl,\n\tchatStreamUrl,\n\tconversationMessagesUrl,\n\tDEFAULT_CHAT_APP_ID,\n\tsessionsUrl,\n} from './aiChatConfig.js'\nimport { useAiContext } from './useAiContext.js'\n\n/**\n * Factory that creates and returns a reactive AI chat stream state object.\n *\n * This follows the Vue 2 \"factory composable\" pattern — it returns a plain\n * reactive object (via Vue.observable) rather than Vue 3 refs. One instance\n * should be created per CnAiCompanion mount.\n *\n * @param {object} [contextInstance] Vue component instance to read cnAiContext from.\n * Pass the CnAiCompanion component instance so the outgoing request includes\n * the current page context.\n * @param {object} [options] Transport options.\n * @param {string} [options.chatAppId] Backend app id the chat/conversation URLs\n * resolve against. Defaults to {@link DEFAULT_CHAT_APP_ID} (`openregister`).\n * @returns {object} Reactive state + methods\n */\nexport function useAiChatStream(contextInstance, options = {}) {\n\t/** Backend app id for every URL this composable builds (see aiChatConfig.js) */\n\tconst chatAppId = options.chatAppId || DEFAULT_CHAT_APP_ID\n\tconst STREAM_URL = chatStreamUrl(chatAppId)\n\tconst SEND_URL = chatSendUrl(chatAppId)\n\t/** Stable reactive state object */\n\tconst state = reactive({\n\t\t/** Whether an SSE or fallback request is in-flight */\n\t\tisStreaming: false,\n\t\t/** Partial assistant text built from token events */\n\t\tcurrentText: '',\n\t\t/** Tool call entries: { toolId, arguments, result?, isError? } */\n\t\ttoolCalls: [],\n\t\t/**\n\t\t * Approvals the agent is waiting on, so they can be decided HERE.\n\t\t *\n\t\t * Deliberately generic: each entry carries its own `kind` and its own\n\t\t * `resolveUrl`, so a new approval type (fetching a URL, editing a file\n\t\t * that is not open) is rendered and resolved by this same code with no\n\t\t * change — the server says where the decision is posted.\n\t\t *\n\t\t * Shape: { id, kind, title, app, reach, reason, agentId, resolveUrl }\n\t\t */\n\t\tpendingApprovals: [],\n\t\t/** Error state: { code, message } | null */\n\t\terror: null,\n\t\t/** Full conversation message history for the current session */\n\t\tmessages: [],\n\t\t/** Whether the next send() should signal OR to start a new Conversation row */\n\t\t_newThread: false,\n\t\t/**\n\t\t * UUID of the conversation currently being written to, or null before the\n\t\t * first turn. Populated from the `final` SSE event's `conversationUuid`\n\t\t * field / the non-streaming fallback's `conversation` field (both already\n\t\t * on the wire — see finalise()) and echoed back on every subsequent send()\n\t\t * so the whole session stays one Conversation server-side instead of a new\n\t\t * one per turn. Reset by startNewThread(), set directly by loadConversation().\n\t\t */\n\t\tconversationUuid: null,\n\t})\n\n\t/** AbortController for the active fetchEventSource call */\n\tlet abortController = null\n\t/** Resolve/reject for the Promise returned by send() */\n\tlet _resolve = null\n\tlet _reject = null\n\n\t/**\n\t * Get the current cnAiContext snapshot for inclusion in request bodies.\n\t *\n\t * @returns {object}\n\t */\n\tfunction getContextSnapshot() {\n\t\t// An EXPLICIT context wins over the injected one.\n\t\t//\n\t\t// The injected path assumes a CnAppRoot ancestor provides the context.\n\t\t// A companion mounted standalone on a page that is not ours has no such\n\t\t// ancestor, so it falls back to `defaultContext` — whose `appId` is the\n\t\t// literal string 'unknown'. The agent then receives \"app context:\n\t\t// unknown\" and, correctly, refuses to act: measured, it answered a\n\t\t// document edit request with \"I don't have a clear app context\" while\n\t\t// the user was looking straight at the document.\n\t\t//\n\t\t// The host that mounted the companion is the one thing that DOES know\n\t\t// what page it is on, so it may state it.\n\t\tconst ctx = options.context || useAiContext(contextInstance)\n\n\t\treturn {\n\t\t\tappId: ctx.appId,\n\t\t\tpageKind: ctx.pageKind,\n\t\t\tobjectUuid: ctx.objectUuid,\n\t\t\tregisterSlug: ctx.registerSlug,\n\t\t\tschemaSlug: ctx.schemaSlug,\n\t\t\tfileId: ctx.fileId,\n\t\t\troute: ctx.route,\n\t\t}\n\t}\n\n\t/**\n\t * Handle an individual SSE message frame.\n\t *\n\t * @param {object} msg - { event, data } from fetchEventSource\n\t */\n\tfunction handleSseMessage(msg) {\n\t\tconst { event, data } = msg\n\t\tlet parsed\n\t\ttry {\n\t\t\tparsed = JSON.parse(data)\n\t\t} catch {\n\t\t\treturn\n\t\t}\n\n\t\tswitch (event) {\n\t\t\tcase 'token':\n\t\t\t\tstate.currentText += (parsed.delta || '')\n\t\t\t\tbreak\n\n\t\t\tcase 'tool_call':\n\t\t\t\tstate.toolCalls.push({\n\t\t\t\t\ttoolId: parsed.toolId,\n\t\t\t\t\targuments: parsed.arguments,\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\tisError: false,\n\t\t\t\t})\n\t\t\t\tbreak\n\n\t\t\tcase 'tool_result': {\n\t\t\t\tconst entry = state.toolCalls.find((tc) => tc.toolId === parsed.toolId)\n\t\t\t\tif (entry) {\n\t\t\t\t\tentry.result = parsed.result\n\t\t\t\t\tentry.isError = Boolean(parsed.isError)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'heartbeat':\n\t\t\t// Liveness signal only — no UI update\n\t\t\t\tbreak\n\n\t\t\tcase 'final':\n\t\t\t// Commit the streamed text as a finalised assistant message.\n\t\t\t// If no `token` events arrived (non-streaming-provider fallback path —\n\t\t\t// the contract allows the server to emit only the terminal `final`\n\t\t\t// event with `fullText` for providers that don't stream), seed\n\t\t\t// `currentText` from the payload so the assistant bubble renders.\n\t\t\t\tif (state.currentText === '' && typeof parsed.fullText === 'string') {\n\t\t\t\t\tstate.currentText = parsed.fullText\n\t\t\t\t}\n\t\t\t\tif (Array.isArray(parsed.pendingApprovals)) {\n\t\t\t\t\tstate.pendingApprovals = parsed.pendingApprovals\n\t\t\t\t}\n\t\t\t\tfinalise(parsed.messageId, parsed.conversationUuid, parsed)\n\t\t\t\tbreak\n\n\t\t\tcase 'error':\n\t\t\t\tfail(parsed.code || 'unknown', parsed.message || 'Unknown error')\n\t\t\t\tbreak\n\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\t/**\n\t * Push the completed assistant message into state.messages and resolve send().\n\t *\n\t * @param {string|undefined} messageId - Server-supplied id from the final event;\n\t * when empty/missing we synthesise a stable client-side id so Vue's :key\n\t * stays unique within the conversation.\n\t * @param {string|undefined} [conversationUuid] - The conversation this turn was\n\t * written to (SSE `final.conversationUuid` / fallback `.conversation`). Stored\n\t * on state so the *next* send() continues the same server-side Conversation\n\t * instead of implicitly starting a new one every turn.\n\t * @param {object} [extras] - The `final` frame (or JSON reply); its\n\t * `attachments` and `attachmentNotices` arrays are kept on the message.\n\t */\n\tfunction finalise(messageId, conversationUuid, extras) {\n\t\tconst assistantMessage = {\n\t\t\tid: (typeof messageId === 'string' && messageId !== '')\n\t\t\t\t? messageId\n\t\t\t\t: `client-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,\n\t\t\trole: 'assistant',\n\t\t\tcontent: state.currentText,\n\t\t\ttoolCalls: state.toolCalls.slice(),\n\t\t}\n\t\tif (Array.isArray(extras?.attachments)) {\n\t\t\tassistantMessage.attachments = extras.attachments\n\t\t}\n\t\tif (Array.isArray(extras?.attachmentNotices)) {\n\t\t\tassistantMessage.attachmentNotices = extras.attachmentNotices\n\t\t}\n\t\tstate.messages.push(assistantMessage)\n\t\tif (typeof conversationUuid === 'string' && conversationUuid !== '') {\n\t\t\tstate.conversationUuid = conversationUuid\n\t\t}\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tstate.isStreaming = false\n\t\tif (_resolve) {\n\t\t\t_resolve()\n\t\t\t_resolve = null\n\t\t\t_reject = null\n\t\t}\n\t}\n\n\t/**\n\t * Handle an error event or transport failure.\n\t *\n\t * @param {string} code - Machine-readable error code (e.g. 'rate_limited', 'connection_error')\n\t * @param {string} message - Human-readable error message for the UI\n\t */\n\tfunction fail(code, message) {\n\t\tstate.isStreaming = false\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tstate.error = { code, message }\n\t\tif (_reject) {\n\t\t\tconst err = new Error(message)\n\t\t\terr.code = code\n\t\t\t_reject(err)\n\t\t\t_resolve = null\n\t\t\t_reject = null\n\t\t}\n\t}\n\n\t/**\n\t * Non-streaming fallback: POST to /api/chat/send via axios, then synthesise\n\t * a single \"final\" event from the JSON response.\n\t *\n\t * @param {string} content - The user's message text\n\t * @param {object} body - Request body already built by send() (message, context, newThread)\n\t */\n\tasync function sendFallback(content, body) {\n\t\ttry {\n\t\t\tconst response = await axios.post(SEND_URL, body)\n\t\t\tconst data = response.data\n\t\t\t// Treat the response as a final event — populate currentText from the reply\n\t\t\tconst replyContent = data?.content || data?.message || data?.reply || ''\n\t\t\tstate.currentText = replyContent\n\t\t\t// Same two fields the SSE `final` event carries, so the fallback path\n\t\t\t// shows tool steps and approvals exactly as the streaming one does.\n\t\t\tif (Array.isArray(data?.toolCalls)) {\n\t\t\t\tstate.toolCalls = data.toolCalls\n\t\t\t}\n\t\t\tif (Array.isArray(data?.pendingApprovals)) {\n\t\t\t\tstate.pendingApprovals = data.pendingApprovals\n\t\t\t}\n\t\t\t// ChatController::sendMessage() echoes the conversation uuid back as\n\t\t\t// `conversation` (ChatStreamController's SSE `final` event uses\n\t\t\t// `conversationUuid` instead — see finalise() caller in handleSseMessage).\n\t\t\tfinalise(undefined, data?.conversation || data?.conversationUuid, data)\n\t\t} catch (err) {\n\t\t\tconst code = err.response?.status?.toString() || 'network_error'\n\t\t\tconst message = err.message || 'Fallback request failed'\n\t\t\tfail(code, message)\n\t\t}\n\t}\n\n\t/**\n\t * Send a user message. Attempts the SSE stream first; falls back to the\n\t * non-streaming endpoint on 404/501 or connection failure.\n\t *\n\t * @param {string} content - The user's message text\n\t * @param {object} [options] - Send options\n\t * @param {boolean} [options.newThread] - Force a new Conversation row on the server\n\t * @param {string} [options.agentUuid] - Agent to start a *new* conversation with\n\t * (agent-picker selection). Ignored server-side once a conversation uuid is\n\t * resolved — safe to pass on every call.\n\t * @param {Array<{path: string, name: string, fileId?: number}>} [options.attachments] - Files\n\t * already uploaded via the attachments endpoint (see aiChatConfig.js\n\t * `attachmentsUrl()`), to be read by the backend from `body.attachments`.\n\t * Omitted from the request body entirely when empty so existing backends\n\t * that don't yet read the key see no change to the payload shape.\n\t * @returns {Promise<void>} Resolves on \"final\", rejects on \"error\" or abort\n\t */\n\tfunction send(content, options = {}) {\n\t\tif (state.isStreaming) {\n\t\t\treturn Promise.reject(new Error('A stream is already in progress'))\n\t\t}\n\n\t\t// Push the user message into the local history immediately\n\t\tconst userMessage = { role: 'user', content }\n\t\tif (Array.isArray(options.attachments) && options.attachments.length > 0) {\n\t\t\tuserMessage.attachments = options.attachments\n\t\t}\n\t\tstate.messages.push(userMessage)\n\t\tstate.isStreaming = true\n\t\tstate.error = null\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\n\t\tconst newThread = options.newThread || state._newThread\n\t\tstate._newThread = false\n\n\t\t// The conversation this send() continues — '' (never sent) forces both\n\t\t// controllers to create a fresh Conversation row. Cleared on a new thread\n\t\t// so the *next* turn starts a new server-side conversation instead of\n\t\t// reusing the one that just ended.\n\t\tconst activeConversationUuid = newThread ? '' : (state.conversationUuid || '')\n\t\tif (newThread) {\n\t\t\tstate.conversationUuid = null\n\t\t}\n\n\t\t// OR's ChatStreamController reads `$body['message']` (matches the existing\n\t\t// non-streaming `/api/chat/send` request shape). We keep `content` as a\n\t\t// fallback alias for clients that already used the old field name — the\n\t\t// controller ignores unknown keys. Conversation continuity is likewise\n\t\t// duplicated under both key spellings the two backend endpoints read\n\t\t// (ChatController::extractMessageRequestParams() reads `conversation`,\n\t\t// ChatStreamController::stream() reads `conversationUuid`); `agentUuid` is\n\t\t// the same key on both and only consulted when no conversation is resolved.\n\t\tconst body = {\n\t\t\tmessage: content,\n\t\t\tcontent,\n\t\t\tcontext: getContextSnapshot(),\n\t\t\tnewThread,\n\t\t\tconversation: activeConversationUuid,\n\t\t\tconversationUuid: activeConversationUuid,\n\t\t\tagentUuid: options.agentUuid || '',\n\t\t}\n\t\t// Only add the key when there's something to send — keeps the payload\n\t\t// shape unchanged (and any backend not yet reading `attachments`\n\t\t// unaffected) for the common no-attachment turn.\n\t\tif (Array.isArray(options.attachments) && options.attachments.length > 0) {\n\t\t\tbody.attachments = options.attachments\n\t\t}\n\n\t\tabortController = new AbortController()\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\t_resolve = resolve\n\t\t\t_reject = reject\n\n\t\t\tfetchEventSource(STREAM_URL, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'X-Requested-With': 'XMLHttpRequest',\n\t\t\t\t\t// Nextcloud's CSRF middleware accepts either the\n\t\t\t\t\t// requesttoken header or X-Requested-With. We send\n\t\t\t\t\t// both so the SSE POST works whether or not the\n\t\t\t\t\t// app's controller opts out of CSRF (the orchestrator\n\t\t\t\t\t// keeps CSRF on; see ChatStreamController docblock).\n\t\t\t\t\trequesttoken: typeof OC !== 'undefined' ? OC.requestToken : '',\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\tsignal: abortController.signal,\n\n\t\t\t\tasync onopen(response) {\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\t// Happy path — SSE stream opened\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t// Treat 404/501 as \"streaming not available\" — fall back\n\t\t\t\t\tif (response.status === 404 || response.status === 501) {\n\t\t\t\t\t\t// Throw a custom error that onmessage/onerror won't catch\n\t\t\t\t\t\tthrow Object.assign(new Error('streaming_unavailable'), {\n\t\t\t\t\t\t\tisFallback: true,\n\t\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\t// Other HTTP errors — propagate\n\t\t\t\t\tthrow new Error(`SSE open failed: ${response.status}`)\n\t\t\t\t},\n\n\t\t\t\tonmessage(msg) {\n\t\t\t\t\thandleSseMessage(msg)\n\t\t\t\t},\n\n\t\t\t\tonerror(err) {\n\t\t\t\t\tif (err && err.isFallback) {\n\t\t\t\t\t\t// Signal to the catch block that we need the fallback\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}\n\t\t\t\t\t// fetchEventSource calls onerror for connection issues and will\n\t\t\t\t\t// automatically retry. We convert terminal errors to fail().\n\t\t\t\t\tfail('connection_error', err?.message || 'Connection error')\n\t\t\t\t\tthrow err // Stop retrying\n\t\t\t\t},\n\n\t\t\t\tonclose() {\n\t\t\t\t\t// Stream closed without a \"final\" event — treat as connection reset\n\t\t\t\t\tif (state.isStreaming) {\n\t\t\t\t\t\tfail('connection_closed', 'Stream closed unexpectedly')\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t}).catch((err) => {\n\t\t\t\tif (err && err.isFallback) {\n\t\t\t\t\t// Non-streaming fallback path\n\t\t\t\t\treturn sendFallback(content, body)\n\t\t\t\t}\n\t\t\t\tif (err && err.name === 'AbortError') {\n\t\t\t\t\t// Intentional abort — already handled by abort()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tfail(err?.code || 'unknown', err?.message || 'Unknown error')\n\t\t\t})\n\t\t})\n\t}\n\n\t/**\n\t * Abort the currently in-flight stream.\n\t * Rejects the send() Promise with a cancellation error.\n\t */\n\tfunction abort() {\n\t\tif (abortController) {\n\t\t\tabortController.abort()\n\t\t\tabortController = null\n\t\t}\n\t\tstate.isStreaming = false\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tif (_reject) {\n\t\t\tconst err = new Error('Reply was cancelled')\n\t\t\terr.code = 'cancelled'\n\t\t\t_reject(err)\n\t\t\t_resolve = null\n\t\t\t_reject = null\n\t\t}\n\t}\n\n\t/**\n\t * Discard current conversation state and signal OR to start a fresh\n\t * Conversation row on the next send() call.\n\t */\n\tfunction startNewThread() {\n\t\tif (state.isStreaming) {\n\t\t\tabort()\n\t\t}\n\t\tstate.messages = []\n\t\tstate.currentText = ''\n\t\tstate.toolCalls = []\n\t\tstate.error = null\n\t\tstate._newThread = true\n\t\tstate.conversationUuid = null\n\t}\n\n\t/**\n\t * Load an existing conversation's messages into the state.\n\t * Used by CnAiHistoryDialog when the user selects a past conversation.\n\t *\n\t * Fetches GET /api/conversations/{uuid}/messages (OR's conversation#messages\n\t * route), which returns { results: [...] } ordered oldest-first. Each OR\n\t * message carries { id, uuid, conversationId, role, content, sources,\n\t * context, created } — mapped here onto the { role, content, toolCalls }\n\t * shape the send/stream paths produce so CnAiMessageList renders resumed\n\t * conversations identically to live ones. OR does not persist tool calls\n\t * on messages, so toolCalls degrades to [].\n\t *\n\t * The approvals the agent still waits on come with the messages\n\t * (`pendingApprovals`, the shape of the stream's `final` event), so a\n\t * reopened conversation shows them as a live turn does.\n\t *\n\t * @param {string} conversationUuid - UUID of the conversation to resume\n\t * @returns {Promise<void>}\n\t * @spec openspec/changes/ai-chat-opens-the-subject-session/specs/ai-companion/spec.md#requirement-a-loaded-conversation-keeps-its-pending-approvals\n\t */\n\tasync function loadConversation(conversationUuid) {\n\t\ttry {\n\t\t\tconst response = await axios.get(\n\t\t\t\tconversationMessagesUrl(chatAppId, conversationUuid),\n\t\t\t\t// The backend controller defaults to 50 messages; raise the limit\n\t\t\t\t// so long threads resume fully.\n\t\t\t\t{ params: { limit: 200 } },\n\t\t\t)\n\t\t\tconst data = response.data\n\t\t\tconst messages = Array.isArray(data.results)\n\t\t\t\t? data.results\n\t\t\t\t: (Array.isArray(data.messages) ? data.messages : [])\n\t\t\tstate.messages = messages.map((m) => ({\n\t\t\t\trole: m.role || 'assistant',\n\t\t\t\tcontent: m.content || '',\n\t\t\t\ttoolCalls: m.toolCalls || m.tool_calls || [],\n\t\t\t}))\n\t\t\tstate.pendingApprovals = Array.isArray(data.pendingApprovals) ? data.pendingApprovals : []\n\t\t\t// Don't force a new thread — resume this conversation, and remember its\n\t\t\t// uuid so the next send() continues it instead of starting a new one.\n\t\t\tstate._newThread = false\n\t\t\tstate.conversationUuid = conversationUuid\n\t\t} catch (err) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.info('[useAiChatStream] Could not load conversation:', err?.message)\n\t\t}\n\t}\n\n\t/**\n\t * Open the user's most recent session about one record, if there is one.\n\t *\n\t * A session is accepted only when its subject is that record, so a backend\n\t * that ignores the `subject` filter leaves the thread empty instead of\n\t * opening a conversation about something else.\n\t *\n\t * @param {string} objectUuid The record the page is about.\n\t * @return {Promise<boolean>} Whether a session was opened.\n\t * @spec openspec/changes/ai-chat-opens-the-subject-session/specs/ai-companion/spec.md#requirement-an-embedded-chat-may-open-the-users-session-about-the-pages-record\n\t */\n\tasync function loadSubjectSession(objectUuid) {\n\t\tlet sessions\n\t\ttry {\n\t\t\tconst response = await axios.get(sessionsUrl(chatAppId), { params: { subject: objectUuid, limit: 1 } })\n\t\t\tsessions = Array.isArray(response.data?.results) ? response.data.results : []\n\t\t} catch (err) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.info('[useAiChatStream] Could not list the sessions about the record:', err?.message)\n\t\t\treturn false\n\t\t}\n\t\tconst session = sessions.find((candidate) => subjectOf(candidate) === objectUuid)\n\t\tif (!session) {\n\t\t\treturn false\n\t\t}\n\t\tawait loadConversation(session.uuid || session.id)\n\t\treturn state.conversationUuid !== null\n\t}\n\n\treturn {\n\t\t// Reactive state (accessed as state.isStreaming etc. from the component)\n\t\tstate,\n\t\t// Methods\n\t\tsend,\n\t\tabort,\n\t\tstartNewThread,\n\t\tloadConversation,\n\t\tloadSubjectSession,\n\t}\n}\n\n/**\n * The record a session is about: `subject.objectUuid`, or the same under its\n * `metadata`, where the session stores it.\n *\n * @param {object} session A session from the session list.\n * @return {string} The record's uuid, or '' when the session names none.\n * @spec openspec/changes/ai-chat-opens-the-subject-session/specs/ai-companion/spec.md#requirement-an-embedded-chat-may-open-the-users-session-about-the-pages-record\n */\nfunction subjectOf(session) {\n\tconst subject = session?.subject || session?.metadata?.subject\n\tif (typeof subject === 'string') {\n\t\treturn subject\n\t}\n\treturn (subject && typeof subject.objectUuid === 'string') ? subject.objectUuid : ''\n}\n"],"names":["axios"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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