Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

rename (#1751)

Eric Hayesd23433e1c3d1
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsx
index 3c2dd32be8..ac3cdc008e 100644
--- a/js/app/packages/app/component/SoupChatInput.tsx
+++ b/js/app/packages/app/component/SoupChatInput.tsx
@@ -1,4 +1,6 @@
import { useSoup } from '@app/component/next-soup/soup-context';
+import { withAnalytics } from '@coparse/analytics';
+import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';
import {
ChatInputProvider,
@@ -6,11 +8,9 @@ import {
} from '@core/component/AI/context';
import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';
import { setPendingSendData } from '@core/component/AI/signal/pendingSend';
-import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';
import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';
import { TOKENS } from '@core/hotkey/tokens';
import { isErr } from '@core/util/maybeResult';
-import { withAnalytics } from '@coparse/analytics';
import { cognitionApiServiceClient } from '@service-cognition/client';
import { ChatInput } from 'core/component/AI/component/input/ChatInput';
import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
@@ -56,13 +56,21 @@ function SoupChatInputInner() {
},
});
+ function deriveChatName(userQuery: string): string | undefined {
+ const MAX_LENGTH = 80;
+ const firstLine = userQuery
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0)[0];
+ return firstLine ? firstLine.slice(0, MAX_LENGTH) : undefined;
+ }
+
const handleSend = async (request: ChatSendInput) => {
// Create a new persistent chat
- const response = await cognitionApiServiceClient.createChat({
- isPersistent: true,
- });
+ const name = deriveChatName(request.content);
+
+ const response = await cognitionApiServiceClient.createChat({ name });
if (isErr(response)) {
- console.error('Failed to create chat', response);
return;
}
const [, { id: chatId }] = response;
diff --git a/js/app/packages/block-chat/component/Block.tsx b/js/app/packages/block-chat/component/Block.tsx
index bc9e4f7d60..93f8626838 100644
--- a/js/app/packages/block-chat/component/Block.tsx
+++ b/js/app/packages/block-chat/component/Block.tsx
@@ -2,26 +2,20 @@ import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import { DEFAULT_CHAT_NAME } from '@block-chat/definition';
import { useBlockId } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { DebouncedNotificationReadMarker } from '@notifications';
-import { createEffect, createSignal, Show } from 'solid-js';
+import { Show } from 'solid-js';
import { chatBlockData } from '../signal/chatBlockData';
import { Chat } from './Chat';
import { ModalsProvider } from './ModalsProvider';
export default function ChatBlock() {
- const [title, setTitle] = createSignal<string>(DEFAULT_CHAT_NAME);
const blockId = useBlockId();
const notificationSource = useGlobalNotificationSource();
-
- createEffect(() => {
- const data = chatBlockData();
- if (data) {
- setTitle(data.chat.name);
- }
- });
+ const name = useBlockDocumentName(DEFAULT_CHAT_NAME);
return (
- <DocumentBlockContainer title={title()}>
+ <DocumentBlockContainer title={name()}>
<DebouncedNotificationReadMarker
notificationSource={notificationSource}
entity={{ type: 'chat', id: blockId }}
diff --git a/js/app/packages/core/constant/servers.ts b/js/app/packages/core/constant/servers.ts
index 6ac4f9c443..584c58c523 100644
--- a/js/app/packages/core/constant/servers.ts
+++ b/js/app/packages/core/constant/servers.ts
@@ -48,9 +48,14 @@ function selectLocalServers(): Servers {
return serverHostLocal;
}
+ function assertValidName(name: string): name is keyof Servers {
+ if (!(name in serverHostRemote))
+ throw new Error(`unknown server name ${name}`);
+ return true;
+ }
const servers = selectedLocalServers
.split(',')
- .filter((name) => name in serverHostRemote)
+ .filter(assertValidName)
.reduce((acc: Servers, key: keyof Servers) => {
acc[key] = serverHostLocal[key];
console.log(`Using local server ${key}: ${acc}`);
diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.ts
index af2cb0cf4b..47e8295132 100644
--- a/js/app/packages/service-clients/service-cognition/client.ts
+++ b/js/app/packages/service-clients/service-cognition/client.ts
@@ -6,18 +6,18 @@ import {
fetchWithToken,
} from '@core/util/fetchWithToken';
import {
+ err,
isErr,
type MaybeError,
type MaybeResult,
mapOk,
- ok,
- err,
type ObjectLike,
+ ok,
} from '@core/util/maybeResult';
import { platformFetch } from '@core/util/platformFetch';
import type { SafeFetchInit } from '@core/util/safeFetch';
-import type OpenAI from 'openai';
import type { DocumentTextPart } from '@service-cognition/generated/schemas/documentTextPart';
+import type OpenAI from 'openai';
import type { CreateChatRequest } from './generated/schemas/createChatRequest';
import type { EmptyResponse } from './generated/schemas/emptyResponse';
import type { GetBatchPreviewRequest } from './generated/schemas/getBatchPreviewRequest';
diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.ts
index 73910795ab..88c1f4c86f 100644
--- a/js/app/packages/service-clients/service-cognition/generated/client.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts
@@ -19,6 +19,7 @@ import type {
GetChatsForAttachmentResponse,
GetModelsResponse,
HttpSendChatMessageRequest,
+ PatchChatRequestV2,
SendChatMessageResponse,
StringIDResponse,
SuccessResponse,
@@ -389,6 +390,67 @@ export const deleteChatHandler = async (
} as deleteChatHandlerResponse;
};
+export type patchChatHandlerResponse200 = {
+ data: void;
+ status: 200;
+};
+
+export type patchChatHandlerResponse400 = {
+ data: string;
+ status: 400;
+};
+
+export type patchChatHandlerResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type patchChatHandlerResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type patchChatHandlerResponseSuccess = patchChatHandlerResponse200 & {
+ headers: Headers;
+};
+export type patchChatHandlerResponseError = (
+ | patchChatHandlerResponse400
+ | patchChatHandlerResponse401
+ | patchChatHandlerResponse500
+) & {
+ headers: Headers;
+};
+
+export type patchChatHandlerResponse =
+ | patchChatHandlerResponseSuccess
+ | patchChatHandlerResponseError;
+
+export const getPatchChatHandlerUrl = (chatId: string) => {
+ return `/chats/${chatId}`;
+};
+
+export const patchChatHandler = async (
+ chatId: string,
+ patchChatRequestV2: PatchChatRequestV2,
+ options?: RequestInit
+): Promise<patchChatHandlerResponse> => {
+ const res = await fetch(getPatchChatHandlerUrl(chatId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchChatRequestV2),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: patchChatHandlerResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as patchChatHandlerResponse;
+};
+
export type copyChatHandlerResponse201 = {
data: StringIDResponse;
status: 201;
diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.json
index 19792bb28f..07ddb370fe 100644
--- a/js/app/packages/service-clients/service-cognition/openapi.json
+++ b/js/app/packages/service-clients/service-cognition/openapi.json
@@ -343,6 +343,66 @@
}
}
}
+ },
+ "patch": {
+ "tags": ["patch_chat"],
+ "operationId": "patch_chat_handler",
+ "parameters": [
+ {
+ "name": "chat_id",
+ "in": "path",
+ "description": "Chat ID",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PatchChatRequestV2"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Chat patched successfully"
+ },
+ "400": {
+ "description": "Cannot modify deleted chat",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
}
},
"/chats/{chat_id}/copy": {
diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs
index 81ed60ea29..50bd671f5e 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs
@@ -20,6 +20,20 @@ pub struct Params {
pub chat_id: String,
}
+#[utoipa::path(
+ patch,
+ path = "/chats/{chat_id}",
+ request_body = PatchChatRequestV2,
+ params(
+ ("chat_id" = String, Path, description = "Chat ID")
+ ),
+ responses(
+ (status = 200, description = "Chat patched successfully"),
+ (status = 400, body = String, description = "Cannot modify deleted chat"),
+ (status = 401, body = String),
+ (status = 500, body = String),
+ )
+)]
#[tracing::instrument(skip(user_context, state), fields(user_id=?user_context.user_id))]
pub async fn patch_chat_handler(
ChatAccessLevelExtractor { access_level, .. }: ChatAccessLevelExtractor<OwnerAccessLevel>,
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.rs
index 36f944d2f8..3d82962acc 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
@@ -8,7 +8,6 @@ use crate::api::utils::log;
use crate::core::constants::DEFAULT_CHAT_NAME;
use crate::core::model::FALLBACK_MODEL;
use crate::model::stream::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};
-use crate::service::ai::name::maybe_rename_chat;
use crate::service::get_chat::get_chat;
use crate::service::notification::notify;
use ai::tool::ToolLoop;
@@ -196,7 +195,6 @@ pub async fn send_chat_message(
}
};
- let is_first_message = chat.messages.is_empty();
let model = if request.model == Model::Claude45Opus {
Model::Claude45Opus
} else {
@@ -268,7 +266,6 @@ pub async fn send_chat_message(
user_message_id,
request.attachments.clone().unwrap_or_default(),
durable_stream_id,
- is_first_message,
);
Ok(Json(SendChatMessageResponse {
@@ -340,7 +337,6 @@ fn stream_and_save_message(
user_message_id: String,
user_message_attachments: Vec<ChatAttachmentWithName>,
durable_stream_id: StreamId,
- is_first_message: bool,
) {
tracing::trace!(request=?request, "streaming chat request");
@@ -521,15 +517,6 @@ fn stream_and_save_message(
);
}
- // Maybe rename chat if first message
- if is_first_message
- && let Ok(new_name) =
- maybe_rename_chat(&chat_id, &ctx, user_id.0.as_ref())
- .await
- .inspect_err(|err| tracing::error!(error=?err, "failed to rename chat"))
- {
- tracing::info!(chat_id, new_name, "chat renamed after first message");
- }
};
ctx_outer.stream_repo.clone().from_async_stream(
diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
index ef2ff81164..c4a48f95f3 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs
@@ -3,7 +3,7 @@ use crate::{
attachments::get_chats_for_attachment,
chats::{
chat_history, chat_history_batch_messages, copy_chat, create_user_chat, delete_chat,
- get_chat, get_chat_permissions, revert_delete_chat,
+ get_chat, get_chat_permissions, patch_chat, revert_delete_chat,
},
citations, health,
models::get_models,
@@ -72,6 +72,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,
+ patch_chat::patch_chat_handler
),
components(
schemas(
diff --git a/rust/cloud-storage/document_cognition_service/src/service/ai/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/ai/mod.rs
deleted file mode 100644
index c427f91ac7..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/service/ai/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-pub mod name;
diff --git a/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs b/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs
deleted file mode 100644
index efce846fd8..0000000000
--- a/rust/cloud-storage/document_cognition_service/src/service/ai/name.rs
+++ /dev/null
@@ -1,64 +0,0 @@
-use anyhow::{Context, Result};
-use std::fmt::Write;
-
-use crate::{
- api::context::ApiContext, core::constants::DEFAULT_MAX_TOKENS, service::get_chat::get_chat,
-};
-
-use ai::chat_completion::get_chat_completion_openai_request;
-use async_openai::types::{
- ChatCompletionRequestSystemMessageArgs, ChatCompletionRequestUserMessageArgs,
- CreateChatCompletionRequestArgs,
-};
-use macro_db_client::dcs::patch_chat::patch_chat;
-
-#[tracing::instrument(skip(text), err)]
-pub async fn get_recomended_chat_name(text: &str) -> anyhow::Result<String> {
- let system_message = ChatCompletionRequestSystemMessageArgs::default()
- .content("Given the following text from a conversation, please generate a 1-4 word title for the conversation. DO NOT USE MARKDOWN FORMATTING.")
- .build()
- .context("failed to build system message")?
- .into();
-
- let user_message = ChatCompletionRequestUserMessageArgs::default()
- .content(text)
- .build()
- .context("failed to build user message")?
- .into();
-
- let request = CreateChatCompletionRequestArgs::default()
- .model(ai::types::Model::Claude45Haiku.to_string())
- .max_tokens(DEFAULT_MAX_TOKENS)
- .messages(vec![system_message, user_message])
- .build()
- .context("failed to build chat completion request")?;
-
- let response = get_chat_completion_openai_request(request)
- .await
- .context("failed to create chat completion")?;
-
- Ok(response)
-}
-
-#[tracing::instrument(skip(ctx), err)]
-pub async fn maybe_rename_chat(chat_id: &str, ctx: &ApiContext, user_id: &str) -> Result<String> {
- let updated_messages = get_chat(ctx, chat_id, user_id)
- .await
- .context("failed to get chat")?
- .messages;
- // Double check that we have a system, user and assistant message
- let mut content = String::new();
-
- for message in updated_messages {
- if let Some(text) = message.conent_text_with_tools() {
- let _ = write!(content, "[{}]", message.role);
- let _ = writeln!(content, "{}", text);
- }
- }
-
- let new_name = get_recomended_chat_name(&content).await?;
- patch_chat(&ctx.db, chat_id, Some(&new_name), None, None, None)
- .await
- .context("failed to patch chat with new name")?;
- Ok(new_name)
-}
diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
index 2b33b36c17..a1b0d77854 100644
--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs
+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs
@@ -1,4 +1,3 @@
-pub mod ai;
pub mod attachment;
pub mod get_chat;
pub mod id_mapping;