Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): cancel stream button (#2543)
Eric Hayes8ff249c99dba
diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex c008248ce5..26da10ead9 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -43,6 +43,7 @@ import { useAnalytics } from '@app/component/analytics-context';import { deriveChatName } from '@core/component/AI/util/deriveName';import { createRenameDssEntityMutation } from '@macro-entity';import { invalidateUserQuota } from '@queries/auth';+import { cognitionApiServiceClient } from '@service-cognition/client';import { createCallback } from '@solid-primitives/rootless';import { ChatInput } from 'core/component/AI/component/input/ChatInput';import { createEffect, createSignal, getOwner, Show } from 'solid-js';@@ -165,6 +166,16 @@ function ChatInner(props: {invalidateUserQuota();});+ const onStop = async () => {+ if (!chat.isGenerating()) return;+ const streamId = chat.stream()?.id()?.stream_id;+ if (!streamId) return;+ await cognitionApiServiceClient.stopChatStream({+ chat_id: chat.chatId(),+ stream_id: streamId,+ });+ };+const saveChatState = (state: StoredStuff) => {storeChatState(props.data.chat.id, state);};@@ -214,6 +225,18 @@ function ChatInner(props: {hide: true,});+ // Ctrl+C while AI is generating stops the stream.+ registerScopeSignalHotkey(scopeId, {+ hotkey: 'ctrl+c',+ description: 'Stop AI response',+ condition: () => chat.isGenerating(),+ keyDownHandler: () => {+ void onStop();+ return true;+ },+ hotkeyToken: TOKENS.chat.stop,+ });+// In preview mode, switching between Soup tabs was causing this createEffect to overflow the stack. We should figure out that root cause, this flag fixes it for now.let hasRun = false;createEffect(() => {@@ -275,6 +298,7 @@ function ChatInner(props: {onChange={setMarkdownText}chatId={chat.chatId()}onSend={onSend}+ onStop={onStop}autoFocusOnMount={true}/></div>diff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsxindex 5bb3c10d5b..bd122351ff 100644--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx@@ -142,19 +142,39 @@ export function ChatInput(props: ChatInputComponentProps) {</div>);+ const StopButton = () => (+ <DeprecatedIconButton+ icon={Stop}+ theme="base"+ size="sm"+ iconSize={14}+ tooltip={{ label: 'Stop generating', shortcut: 'ctrl+c' }}+ onClick={() => props.onStop?.()}+ />+ );+const RightControls = () => (<Switch><Match when={!isTouchDevice()}>- <div class="flex flex-row items-center gap-3 text-xs text-ink-disabled opacity-70 shrink-0">- {props.extraRightControls?.()}- <Tooltip tooltip="Enter to send" placement="top">- <div class="flex items-center">- <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1 py-0.5">- <Hotkey shortcut="Enter" />- </div>+ <Show+ when={generating() && props.onStop}+ fallback={+ <div class="flex flex-row items-center gap-3 text-xs text-ink-disabled opacity-70 shrink-0">+ {props.extraRightControls?.()}+ <Tooltip tooltip="Enter to send" placement="top">+ <div class="flex items-center">+ <div class="flex border border-edge-muted text-[0.625rem] rounded-xs items-center px-1 py-0.5">+ <Hotkey shortcut="Enter" />+ </div>+ </div>+ </Tooltip></div>- </Tooltip>- </div>+ }+ >+ <div class="flex flex-row items-center gap-1 shrink-0">+ <StopButton />+ </div>+ </Show></Match><Match when={isTouchDevice()}><div class="flex flex-row gap-1 items-center shrink-0">@@ -168,14 +188,7 @@ export function ChatInput(props: ChatInputComponentProps) {</Button></Show><Show when={generating()}>- <Button- onClick={() => (props.onStop ? props.onStop() : [])}- class="text-ink-muted hover:scale-115 transition ease-in-out flex-col items-center rounded-full p-[0.25lh] hover:bg-transparent"- >- <div class="group hover:bg-accent transition ease-in-out size-6 border border-accent rounded-full flex items-center justify-center p-0">- <Stop class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />- </div>- </Button>+ <StopButton /></Show></div></Match>diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.tsindex 440c980057..193b6e6998 100644--- a/js/app/packages/core/hotkey/tokens.ts+++ b/js/app/packages/core/hotkey/tokens.ts@@ -244,6 +244,7 @@ export const TOKENS = {close: 'chat-spotlight-close',},new: 'chat-new',+ stop: 'chat-stop',},} as const;diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.tsindex 1c17ff54ff..d007e17af6 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -27,6 +27,8 @@ import type { GetChatsForAttachmentResponse } from './generated/schemas/getChatsimport type { HttpSendChatMessageRequest } from './generated/schemas/httpSendChatMessageRequest';import type { PatchChatRequest } from './generated/schemas/patchChatRequest';import type { SendChatMessageResponse } from './generated/schemas/sendChatMessageResponse';+import type { StopChatStreamRequest } from './generated/schemas/stopChatStreamRequest';+import type { StopChatStreamResponse } from './generated/schemas/stopChatStreamResponse';import type { StringIDResponse } from './generated/schemas/stringIDResponse';import type * as toolTypes from './generated/tools/tool.ts';@@ -314,6 +316,18 @@ export const cognitionApiServiceClient = {(result) => result);},++ /** Stops an in-flight AI chat stream. The streaming task persists whatever+ * the user has already seen and emits StreamEnd. */+ async stopChatStream(args: StopChatStreamRequest) {+ return mapOk(+ await dcsFetch<StopChatStreamResponse>(`/stream/chat/message/stop`, {+ method: 'POST',+ body: JSON.stringify(args),+ }),+ (result) => result+ );+ },};export async function generateTitle(text: string): Promise<string | undefined> {diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex edf063ec11..c2b729e6d3 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -24,6 +24,9 @@ import type {PatchChatRequest,RejectToolCallRequest,SendChatMessageResponse,+ StopChatStreamError,+ StopChatStreamRequest,+ StopChatStreamResponse,StringIDResponse,UpdateToolCallRequest,UpdateToolResponseRequest,@@ -1208,3 +1211,55 @@ export const sendChatMessage = async (headers: res.headers,} as sendChatMessageResponse;};++/**+ * Cancels the streaming task associated with the given `stream_id`, causing+it to persist whatever has been generated so far and emit `StreamEnd`.+The caller must have at least `Edit` access to the chat.+ * @summary Stop an in-flight AI chat stream.+ */+export type stopChatStreamResponse200 = {+ data: StopChatStreamResponse;+ status: 200;+};++export type stopChatStreamResponse403 = {+ data: StopChatStreamError;+ status: 403;+};++export type stopChatStreamResponseSuccess = stopChatStreamResponse200 & {+ headers: Headers;+};+export type stopChatStreamResponseError = stopChatStreamResponse403 & {+ headers: Headers;+};++export type stopChatStreamResponse =+ | stopChatStreamResponseSuccess+ | stopChatStreamResponseError;++export const getStopChatStreamUrl = () => {+ return `/stream/chat/message/stop`;+};++export const stopChatStream = async (+ stopChatStreamRequest: StopChatStreamRequest,+ options?: RequestInit+): Promise<stopChatStreamResponse> => {+ const res = await fetch(getStopChatStreamUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(stopChatStreamRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: stopChatStreamResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as stopChatStreamResponse;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.tsindex d23677c43b..b5dd28d0b8 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts@@ -164,6 +164,9 @@ export * from './sendChatMessageResponse';export * from './sharePermissionV2';export * from './sharePermissionV2ChannelSharePermissions';export * from './sharePermissionV2PublicAccessLevel';+export * from './stopChatStreamError';+export * from './stopChatStreamRequest';+export * from './stopChatStreamResponse';export * from './streamError';export * from './streamErrorOneOf';export * from './streamErrorOneOfFive';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamError.tsnew file mode 100644index 0000000000..e73822db7c--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamError.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Error response for the stop endpoint.+ */+export interface StopChatStreamError {+ /** Human-readable error message. */+ error: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamRequest.tsnew file mode 100644index 0000000000..10920d09b2--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamRequest.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Request body for stopping an in-flight chat stream.+ */+export interface StopChatStreamRequest {+ /** The chat the stream belongs to. Used to verify the caller has+permission to stop the stream. */+ chat_id: string;+ /** The stream/message ID to stop. */+ stream_id: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamResponse.tsnew file mode 100644index 0000000000..53563fac48--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/stopChatStreamResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Response from a stop request.+ */+export interface StopChatStreamResponse {+ /** `true` if a matching in-flight stream was found and cancellation was+triggered, `false` if the stream had already finished or was unknown. */+ stopped: boolean;+}diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex a61b8dc46d..4514a1aa6a 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -1033,6 +1033,46 @@}}}+ },+ "/stream/chat/message/stop": {+ "post": {+ "tags": ["stream_stop"],+ "summary": "Stop an in-flight AI chat stream.",+ "description": "Cancels the streaming task associated with the given `stream_id`, causing\nit to persist whatever has been generated so far and emit `StreamEnd`.\nThe caller must have at least `Edit` access to the chat.",+ "operationId": "stop_chat_stream",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StopChatStreamRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Stop signal sent (or stream already finished)",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StopChatStreamResponse"+ }+ }+ }+ },+ "403": {+ "description": "Forbidden",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/StopChatStreamError"+ }+ }+ }+ }+ }+ }}},"components": {@@ -2934,6 +2974,43 @@}}},+ "StopChatStreamError": {+ "type": "object",+ "description": "Error response for the stop endpoint.",+ "required": ["error"],+ "properties": {+ "error": {+ "type": "string",+ "description": "Human-readable error message."+ }+ }+ },+ "StopChatStreamRequest": {+ "type": "object",+ "description": "Request body for stopping an in-flight chat stream.",+ "required": ["chat_id", "stream_id"],+ "properties": {+ "chat_id": {+ "type": "string",+ "description": "The chat the stream belongs to. Used to verify the caller has\npermission to stop the stream."+ },+ "stream_id": {+ "type": "string",+ "description": "The stream/message ID to stop."+ }+ }+ },+ "StopChatStreamResponse": {+ "type": "object",+ "description": "Response from a stop request.",+ "required": ["stopped"],+ "properties": {+ "stopped": {+ "type": "boolean",+ "description": "`true` if a matching in-flight stream was found and cancellation was\ntriggered, `false` if the stream had already finished or was unknown."+ }+ }+ },"StreamError": {"oneOf": [{diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rsindex 9f800e2373..6b7532e853 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs@@ -1,4 +1,5 @@use crate::config::Config;+use crate::service::ai_stream_registry::AiStreamRegistry;use ai_tools::{AiToolSet, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,ToolPropertiesToolContext, ToolServiceContext, ToolSoupService,@@ -62,6 +63,7 @@ pub struct ApiContext {pub all_tools: Arc<AiToolSet>,pub all_tools_prompt: &'static str,pub entity_access_service: Arc<DcsEntityAccessService>,+ pub ai_stream_registry: AiStreamRegistry,}pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 34a1d47d1f..a811e0cc10 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -326,6 +326,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arall_tools: all_tools_toolset,all_tools_prompt,entity_access_service,+ ai_stream_registry: crate::service::ai_stream_registry::AiStreamRegistry::new(Arc::new(+ redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"),+ )),};Arc::new(api_context)}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex 8a3c49e3e8..d932967fc7 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -7,11 +7,12 @@ use crate::api::context::ApiContext;use crate::api::utils::log;use crate::core::constants::DEFAULT_CHAT_NAME;use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};+use crate::service::ai_stream_registry::CancellationSubscription;use crate::service::get_chat::get_chat;use crate::service::notification::notify;use ai::tool::ToolLoop;use ai::tool::types::StreamPart;-use ai::types::{AssistantMessagePart, Model};+use ai::types::{AssistantMessagePart, ChatMessageContent, Model};use ai_tools::RequestContext;use async_stream::stream;use axum::Json;@@ -276,6 +277,10 @@ pub async fn send_chat_message(stream_id: stream_id.clone(),};+ // Subscribe to cross-instance cancellation signals. The subscription is+ // moved into the spawned stream task and dropped when it finishes.+ let cancellation_sub = ctx.ai_stream_registry.register(stream_id.clone()).await;+// Stream the AI response, save messages when completestream_and_save_message(ctx.clone(),@@ -291,6 +296,7 @@ pub async fn send_chat_message(user_message_id,request.attachments.clone().unwrap_or_default(),durable_stream_id,+ cancellation_sub,);Ok(Json(SendChatMessageResponse {@@ -344,12 +350,56 @@ async fn create_new_chat(Ok((chat, new_chat_id))}+/// For every `ToolCall` in `parts` that has no matching response, insert a+/// synthetic `ToolCallErr { description: "cancelled", .. }` immediately after+/// it. Used on cancellation so the persisted assistant message stays+/// well-formed: every tool call has a matching response (so future+/// conversation turns don't break on an unmatched `tool_call_id`) and the UI+/// can render the cancellation via the existing `ToolCallErr` variant.+fn resolve_pending_tool_calls(parts: Vec<AssistantMessagePart>) -> Vec<AssistantMessagePart> {+ use std::collections::HashSet;+ let mut pending: HashSet<String> = HashSet::new();+ for part in &parts {+ match part {+ AssistantMessagePart::ToolCall { id, .. } => {+ pending.insert(id.clone());+ }+ AssistantMessagePart::ToolCallResponseJson { id, .. }+ | AssistantMessagePart::ToolCallErr { id, .. } => {+ pending.remove(id);+ }+ _ => {}+ }+ }+ if pending.is_empty() {+ return parts;+ }+ let mut out: Vec<AssistantMessagePart> = Vec::with_capacity(parts.len() + pending.len());+ for part in parts {+ let synthetic = match &part {+ AssistantMessagePart::ToolCall { id, name, .. } if pending.contains(id) => {+ Some(AssistantMessagePart::ToolCallErr {+ name: name.clone(),+ id: id.clone(),+ description: "cancelled".to_string(),+ })+ }+ _ => None,+ };+ out.push(part);+ if let Some(s) = synthetic {+ out.push(s);+ }+ }+ out+}+/// Streams the AI response and saves conversation messages when complete.////// Creates a payload stream, publishes it via `from_async_stream`, and stores/// the conversation messages after the stream finishes.#[expect(clippy::too_many_arguments, reason = "matches WS handler signature")]-#[tracing::instrument(skip(ctx, request, user_message_content))]+#[tracing::instrument(skip(ctx, request, user_message_content, cancellation_sub))]fn stream_and_save_message(ctx: Arc<ApiContext>,request: ai::types::ChatCompletionRequest,@@ -364,6 +414,7 @@ fn stream_and_save_message(user_message_id: String,user_message_attachments: Vec<ChatAttachmentWithName>,durable_stream_id: StreamId,+ cancellation_sub: CancellationSubscription,) {tracing::trace!(request=?request, "streaming chat request");let model = Model::Claude45Haiku;@@ -374,8 +425,18 @@ fn stream_and_save_message(user_id: user_id.clone(),};let ctx_outer = ctx.clone();+ // Pull the token out so the select below can reference it without moving+ // the whole subscription; the subscription itself is moved into the+ // stream closure so the Redis subscriber task is aborted when the stream+ // finishes.+ let cancellation_token = cancellation_sub.token.clone();let payload_stream = stream! {+ // Keep the subscription alive for the duration of the stream. When+ // the stream closure drops, `cancellation_sub` drops, and its `Drop`+ // impl aborts the Redis subscriber task.+ let _cancellation_sub = cancellation_sub;+// Yield the user message as the first item so other clients can display itlet user_msg = ChatStream::ChatUserMessage {stream_id: stream_id.clone(),@@ -418,20 +479,40 @@ fn stream_and_save_message(let mut is_first_token = false;let idle_timeout = std::time::Duration::from_secs(3 * 60);-- while let Some(response) = match tokio::time::timeout(idle_timeout, ai_stream.next()).await {- Ok(item) => item,- Err(_) => {- tracing::error!(chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "AI stream idle timeout: no token received within {idle_timeout:?}");- let stream_error = StreamError::InternalError {- stream_id: stream_id.clone(),- };- if let Ok(json) = serde_json::to_value(&stream_error) {- yield json;+ let mut was_cancelled = false;+ // Track every AssistantMessagePart we yield so we can persist the+ // exact partial response if the stream is cancelled. The ToolLoop's+ // internal conversation state is only flushed after its inner stream+ // completes, so on cancellation `chat.get_new_conversation_messages()`+ // returns empty — we build the partial message from this buffer instead.+ let mut yielded_parts: Vec<AssistantMessagePart> = Vec::new();++ loop {+ let next_item = tokio::select! {+ biased;+ _ = cancellation_token.cancelled() => {+ tracing::info!(chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "AI stream cancelled by user");+ was_cancelled = true;+ None}- None- }- } {+ timed = tokio::time::timeout(idle_timeout, ai_stream.next()) => {+ match timed {+ Ok(item) => item,+ Err(_) => {+ tracing::error!(chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "AI stream idle timeout: no token received within {idle_timeout:?}");+ let stream_error = StreamError::InternalError {+ stream_id: stream_id.clone(),+ };+ if let Ok(json) = serde_json::to_value(&stream_error) {+ yield json;+ }+ None+ }+ }+ }+ };++ let Some(response) = next_item else { break; };tracing::trace!("{:#?}", response);// Log time to first token@@ -474,6 +555,8 @@ fn stream_and_save_message(},};+ yielded_parts.push(message_part.clone());+let response = ChatStream::ChatMessageResponse {stream_id: stream_id.clone(),chat_id: chat_id.clone(),@@ -516,7 +599,34 @@ fn stream_and_save_message(if let Ok(json) = serde_json::to_value(&end_msg) {yield json;}- let new_messages = chat.get_new_conversation_messages();+ // Build the set of messages to persist.+ //+ // Natural completion: the ToolLoop has flushed its in-progress stream+ // into its own `self.messages`, so `get_new_conversation_messages`+ // returns the full assistant (+ any tool) messages. Use those.+ //+ // Cancellation: the ToolLoop never flushed, so that call returns+ // empty. Build a ChatMessage from the parts we actually yielded —+ // that's exactly what the user saw in the chunks pushed to the+ // durable stream, so the saved message matches the UI deterministically.+ let new_messages = if was_cancelled {+ // Any tool calls that didn't get a response before cancellation+ // are closed out with a synthetic "cancelled" error so the saved+ // message has no dangling tool_call_ids.+ let resolved_parts = resolve_pending_tool_calls(yielded_parts);+ if resolved_parts.is_empty() {+ vec![]+ } else {+ vec![ai::types::ChatMessage {+ role: ai::types::Role::Assistant,+ content: ChatMessageContent::AssistantMessageParts(resolved_parts),+ image_urls: None,+ }]+ }+ } else {+ chat.get_new_conversation_messages()+ };+// Extract assistant response text before moving new_messages into storelet assistant_text = new_messages.iter()@@ -533,11 +643,15 @@ fn stream_and_save_message().await{- tracing::error!(error=?err, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, "failed to store conversation messages");+ tracing::error!(error=?err, chat_id = %chat_id, user_id = %user_id, stream_id = %stream_id, was_cancelled = was_cancelled, "failed to store conversation messages");}- // Summarize and send notification in a background task- if let Some(text) = assistant_text {+ // Summarize and send notification in a background task. Skip if the+ // stream was cancelled — the user already knows the response stopped+ // and we don't want to notify on a partial reply.+ if !was_cancelled+ && let Some(text) = assistant_text+ {notify(ctx.connection_repo.clone(),ctx.notification_ingress_service.clone(),@@ -556,3 +670,110 @@ fn stream_and_save_message(Some(std::time::Duration::from_secs(30 * 60)),);}++#[cfg(test)]+mod resolve_pending_tool_calls_tests {+ use super::*;++ fn text(s: &str) -> AssistantMessagePart {+ AssistantMessagePart::Text { text: s.into() }+ }+ fn call(id: &str) -> AssistantMessagePart {+ AssistantMessagePart::ToolCall {+ name: "t".into(),+ json: serde_json::json!({}),+ id: id.into(),+ }+ }+ fn resp(id: &str) -> AssistantMessagePart {+ AssistantMessagePart::ToolCallResponseJson {+ name: "t".into(),+ json: serde_json::json!({}),+ id: id.into(),+ }+ }+ fn cancelled_err(id: &str) -> AssistantMessagePart {+ AssistantMessagePart::ToolCallErr {+ name: "t".into(),+ id: id.into(),+ description: "cancelled".to_string(),+ }+ }++ #[test]+ fn noop_when_no_tool_calls() {+ let parts = vec![text("a"), text("b")];+ assert_eq!(resolve_pending_tool_calls(parts.clone()), parts);+ }++ #[test]+ fn noop_when_all_tool_calls_resolved() {+ let parts = vec![text("a"), call("1"), resp("1"), text("b")];+ assert_eq!(resolve_pending_tool_calls(parts.clone()), parts);+ }++ #[test]+ fn inserts_cancelled_err_after_trailing_unmatched_call() {+ let parts = vec![text("a"), call("1")];+ let out = resolve_pending_tool_calls(parts);+ assert_eq!(out, vec![text("a"), call("1"), cancelled_err("1")]);+ }++ #[test]+ fn inserts_cancelled_err_immediately_after_unmatched_call() {+ // Cancel between tool call emission and its response: inject the+ // synthetic err right after the call, keep any later yielded parts.+ let parts = vec![text("a"), call("1"), text("b")];+ let out = resolve_pending_tool_calls(parts);+ assert_eq!(+ out,+ vec![text("a"), call("1"), cancelled_err("1"), text("b")]+ );+ }++ #[test]+ fn leaves_resolved_calls_alone_resolves_pending_ones() {+ let parts = vec![+ text("a"),+ call("1"),+ resp("1"),+ text("b"),+ call("2"),+ text("c"),+ ];+ let out = resolve_pending_tool_calls(parts);+ assert_eq!(+ out,+ vec![+ text("a"),+ call("1"),+ resp("1"),+ text("b"),+ call("2"),+ cancelled_err("2"),+ text("c"),+ ]+ );+ }++ #[test]+ fn resolves_multiple_unmatched_calls() {+ let parts = vec![call("1"), text("x"), call("2")];+ let out = resolve_pending_tool_calls(parts);+ assert_eq!(+ out,+ vec![+ call("1"),+ cancelled_err("1"),+ text("x"),+ call("2"),+ cancelled_err("2"),+ ]+ );+ }++ #[test]+ fn empty_input_stays_empty() {+ assert!(resolve_pending_tool_calls(vec![]).is_empty());+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rsindex b1e3fbd1f6..e554d98952 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs@@ -4,6 +4,7 @@//! that publish to a durable stream. The connection_gateway handles delivery to clients.pub mod chat_message;+pub mod stop;mod util;use axum::{Router, routing::post};@@ -15,6 +16,7 @@ use crate::api::context::ApiContext;pub fn router(state: ApiContext) -> Router<ApiContext> {Router::new().route("/chat/message", post(chat_message::send_chat_message))+ .route("/chat/message/stop", post(stop::stop_chat_stream)).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/stop.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/stop.rsnew file mode 100644index 0000000000..c7452975e3--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/stop.rs@@ -0,0 +1,110 @@+//! HTTP endpoint for stopping an in-flight AI chat stream.+//!+//! The request fires the `CancellationToken` registered when the stream+//! started. The streaming task notices, breaks out of its loop, persists+//! whatever the user has already seen, and emits `StreamEnd` over the+//! durable stream.++use crate::api::context::ApiContext;+use crate::api::stream::util::chat_permissions;+use axum::Json;+use axum::extract::{Extension, State};+use axum::http::StatusCode;+use axum::response::IntoResponse;+use model::user::UserContext;+use models_permissions::share_permission::access_level::AccessLevel;+use serde::{Deserialize, Serialize};+use std::fmt;+use utoipa::ToSchema;++/// Request body for stopping an in-flight chat stream.+#[derive(Debug, Serialize, Deserialize, ToSchema, Clone)]+pub struct StopChatStreamRequest {+ /// The chat the stream belongs to. Used to verify the caller has+ /// permission to stop the stream.+ pub chat_id: String,+ /// The stream/message ID to stop.+ pub stream_id: String,+}++/// Response from a stop request.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct StopChatStreamResponse {+ /// `true` if a matching in-flight stream was found and cancellation was+ /// triggered, `false` if the stream had already finished or was unknown.+ pub stopped: bool,+}++/// Error response for the stop endpoint.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct StopChatStreamError {+ /// Human-readable error message.+ pub error: String,+}++impl fmt::Display for StopChatStreamError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.error)+ }+}++impl IntoResponse for StopChatStreamError {+ fn into_response(self) -> axum::response::Response {+ (StatusCode::FORBIDDEN, Json(self)).into_response()+ }+}++/// Stop an in-flight AI chat stream.+///+/// Cancels the streaming task associated with the given `stream_id`, causing+/// it to persist whatever has been generated so far and emit `StreamEnd`.+/// The caller must have at least `Edit` access to the chat.+#[utoipa::path(+ post,+ path = "/stream/chat/message/stop",+ request_body = StopChatStreamRequest,+ responses(+ (status = 200, description = "Stop signal sent (or stream already finished)", body = StopChatStreamResponse),+ (status = 403, description = "Forbidden", body = StopChatStreamError),+ )+)]+#[tracing::instrument(skip(state, user_context), fields(chat_id = %request.chat_id, stream_id = %request.stream_id, user_id = %user_context.user_id), err)]+pub async fn stop_chat_stream(+ State(state): State<ApiContext>,+ Extension(user_context): Extension<UserContext>,+ Json(request): Json<StopChatStreamRequest>,+) -> Result<Json<StopChatStreamResponse>, StopChatStreamError> {+ let access = chat_permissions::chat_access(+ &state,+ &user_context,+ &request.chat_id,+ request.stream_id.clone(),+ )+ .await+ .map_err(|e| StopChatStreamError {+ error: format!("Permission check failed: {e:?}"),+ })?;++ match access {+ AccessLevel::View | AccessLevel::Comment => {+ return Err(StopChatStreamError {+ error: "Insufficient permissions to stop chat stream".to_string(),+ });+ }+ _ => (),+ }++ // Publish over Redis pub/sub — reaches whichever DCS instance is running+ // the stream. `received` is the subscriber count (0 if the stream already+ // finished or the running instance is gone).+ let received = state+ .ai_stream_registry+ .cancel(&request.stream_id)+ .await+ .map_err(|e| StopChatStreamError {+ error: format!("failed to publish cancel: {e:?}"),+ })?;+ Ok(Json(StopChatStreamResponse {+ stopped: received > 0,+ }))+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex 4c8d8cabba..c3b9ea12b5 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -7,6 +7,9 @@ use crate::api::{stream::chat_message::{self, ChatMessageError, HttpSendChatMessageRequest, SendChatMessageResponse,},+ stream::stop::{+ self as stream_stop, StopChatStreamError, StopChatStreamRequest, StopChatStreamResponse,+ },};use crate::model::{response::{@@ -72,6 +75,7 @@ use utoipa::OpenApi;chat_history::get_chat_history_handler,chat_history_batch_messages::get_chat_history_batch_messages_handler,chat_message::send_chat_message,+ stream_stop::stop_chat_stream,memory_api::get_memory_handler),components(@@ -145,6 +149,9 @@ use utoipa::OpenApi;HttpSendChatMessageRequest,SendChatMessageResponse,ChatMessageError,+ StopChatStreamRequest,+ StopChatStreamResponse,+ StopChatStreamError,StreamError,ToolSet,diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 3c9b68dd37..508b8e86e5 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -347,6 +347,9 @@ async fn main() -> anyhow::Result<()> {all_tools: all_tools_toolset,all_tools_prompt,entity_access_service,+ ai_stream_registry: service::ai_stream_registry::AiStreamRegistry::new(+ redis_client.clone(),+ ),}).await.context("failed to setup and serve api")?;diff --git a/rust/cloud-storage/document_cognition_service/src/service/ai_stream_registry.rs b/rust/cloud-storage/document_cognition_service/src/service/ai_stream_registry.rsnew file mode 100644index 0000000000..23cdcaf6a3--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/service/ai_stream_registry.rs@@ -0,0 +1,124 @@+//! Cross-instance cancellation signalling for in-flight AI chat streams.+//!+//! DCS runs as multiple replicas. A stop request can land on any instance,+//! not necessarily the one running the stream. We signal cancellation over+//! Redis pub/sub on a per-`stream_id` channel: the instance running the+//! stream subscribes at start, any instance can publish a cancel, and the+//! running task sees the message and fires its local `CancellationToken`.+//!+//! The token's lifetime is tied to `CancellationSubscription` — drop it and+//! the background subscriber task is aborted.++use anyhow::Context;+use futures::StreamExt;+use redis::{AsyncCommands, Client};+use std::sync::Arc;+use std::time::Duration;+use tokio::task::JoinHandle;+use tokio_util::sync::CancellationToken;++const CANCEL_CHANNEL_PREFIX: &str = "ai_stream_cancel:";+/// Max time we'll wait for the subscription to become live before returning+/// from `register`. If we time out we still return a (non-firing) token so+/// the stream isn't blocked by a flaky Redis.+const SUBSCRIBE_READY_TIMEOUT: Duration = Duration::from_secs(1);++fn channel_for(stream_id: &str) -> String {+ format!("{CANCEL_CHANNEL_PREFIX}{stream_id}")+}++/// Publishes and subscribes cancellation signals to Redis pub/sub. Cheap to+/// clone — the Redis client is already shared.+#[derive(Clone)]+pub struct AiStreamRegistry {+ redis: Arc<Client>,+}++/// Subscription handle kept alive for the lifetime of a streaming task.+/// The held `token` fires when a cancellation is published. Dropping the+/// subscription aborts the background subscriber task.+pub struct CancellationSubscription {+ pub token: CancellationToken,+ task: JoinHandle<()>,+}++impl Drop for CancellationSubscription {+ fn drop(&mut self) {+ self.task.abort();+ }+}++impl AiStreamRegistry {+ /// Construct a new registry backed by the given Redis client.+ pub fn new(redis: Arc<Client>) -> Self {+ Self { redis }+ }++ /// Subscribe to cancel events for `stream_id`. The returned+ /// [`CancellationSubscription`] must be held for the lifetime of the+ /// stream; dropping it unsubscribes. The inner token fires when any+ /// instance publishes a cancel.+ ///+ /// This is a best-effort registration: if Redis is unreachable we log+ /// and return a token that will never fire, so the stream still runs+ /// (it just can't be stopped remotely).+ pub async fn register(&self, stream_id: String) -> CancellationSubscription {+ let token = CancellationToken::new();+ let client = self.redis.clone();+ let task_token = token.clone();+ let (ready_tx, ready_rx) = tokio::sync::oneshot::channel::<()>();++ let task = tokio::spawn(async move {+ let channel = channel_for(&stream_id);+ let mut pubsub = match client.get_async_pubsub().await {+ Ok(p) => p,+ Err(e) => {+ tracing::error!(error=?e, stream_id=%stream_id, "failed to connect pubsub for ai_stream_cancel");+ return;+ }+ };+ if let Err(e) = pubsub.subscribe(&channel).await {+ tracing::error!(error=?e, stream_id=%stream_id, "failed to subscribe to ai_stream_cancel channel");+ return;+ }+ // Signal readiness *after* subscribe() completes, so a publish+ // racing us on another instance won't be missed.+ let _ = ready_tx.send(());++ let mut msgs = pubsub.on_message();+ if msgs.next().await.is_some() {+ tracing::info!(stream_id=%stream_id, "received cancellation signal");+ task_token.cancel();+ }+ });++ // Wait for the subscribe() to land on Redis. If it times out we still+ // hand back a token — it just won't fire.+ if tokio::time::timeout(SUBSCRIBE_READY_TIMEOUT, ready_rx)+ .await+ .is_err()+ {+ tracing::warn!(+ "ai_stream_cancel subscribe did not become ready within {SUBSCRIBE_READY_TIMEOUT:?}"+ );+ }++ CancellationSubscription { token, task }+ }++ /// Publish a cancel request for `stream_id`. Returns the number of+ /// subscribers that received the message — 0 means the stream has+ /// already finished or was on an instance that's no longer running.+ pub async fn cancel(&self, stream_id: &str) -> anyhow::Result<u32> {+ let mut conn = self+ .redis+ .get_multiplexed_async_connection()+ .await+ .context("failed to get redis connection for ai_stream_cancel publish")?;+ let n: u32 = conn+ .publish(channel_for(stream_id), "1")+ .await+ .context("failed to publish ai_stream_cancel")?;+ Ok(n)+ }+}diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rsindex a1b0d77854..7520c80e28 100644--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs@@ -1,3 +1,4 @@+pub mod ai_stream_registry;pub mod attachment;pub mod get_chat;pub mod id_mapping;