Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Delete chat message action to the Obsidian Plugin #1076

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 106 additions & 10 deletions src/interface/obsidian/src/chat_view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ interface Location {
timezone: string;
}

interface RenderMessageOptions {
chatBodyEl: Element;
message: string;
sender: string;
dt?: Date;
raw?: boolean;
willReplace?: boolean;
isSystemMessage?: boolean;
}

export class KhojChatView extends KhojPaneView {
result: string;
setting: KhojSetting;
Expand Down Expand Up @@ -498,9 +508,19 @@ export class KhojChatView extends KhojPaneView {
(images && images.length > 0) ||
excalidrawDiagram) {
let imageMarkdown = this.generateImageMarkdown(message, intentType ?? "", inferredQueries, conversationId, images, excalidrawDiagram);
chatMessageEl = this.renderMessage(chatEl, imageMarkdown, sender, dt);
chatMessageEl = this.renderMessage({
chatBodyEl: chatEl,
message: imageMarkdown,
sender,
dt
});
} else {
chatMessageEl = this.renderMessage(chatEl, message, sender, dt);
chatMessageEl = this.renderMessage({
chatBodyEl: chatEl,
message,
sender,
dt
});
}

// If no document or online context is provided, skip rendering the reference section
Expand Down Expand Up @@ -550,7 +570,7 @@ export class KhojChatView extends KhojPaneView {
return imageMarkdown;
}

renderMessage(chatBodyEl: Element, message: string, sender: string, dt?: Date, raw: boolean = false, willReplace: boolean = true): Element {
renderMessage({ chatBodyEl, message, sender, dt, raw = false, willReplace = true, isSystemMessage = false }: RenderMessageOptions): Element {
let message_time = this.formatDate(dt ?? new Date());

// Append message to conversation history HTML element.
Expand All @@ -577,7 +597,7 @@ export class KhojChatView extends KhojPaneView {

// Add action buttons to each chat message element
if (willReplace === true) {
this.renderActionButtons(message, chatMessageBodyTextEl);
this.renderActionButtons(message, chatMessageBodyTextEl, isSystemMessage);
}

// Remove user-select: none property to make text selectable
Expand Down Expand Up @@ -621,7 +641,7 @@ export class KhojChatView extends KhojPaneView {
this.scrollChatToBottom();
}

renderActionButtons(message: string, chatMessageBodyTextEl: HTMLElement) {
renderActionButtons(message: string, chatMessageBodyTextEl: HTMLElement, isSystemMessage: boolean = false) {
let copyButton = this.contentEl.createEl('button');
copyButton.classList.add("chat-action-button");
copyButton.title = "Copy Message to Clipboard";
Expand All @@ -635,6 +655,25 @@ export class KhojChatView extends KhojPaneView {
setIcon(pasteToFile, "clipboard-paste");
pasteToFile.addEventListener('click', (event) => { pasteTextAtCursor(createCopyParentText(message, 'clipboard-paste')(event)); });


// Add delete button
let deleteButton = null;
if (!isSystemMessage) {
deleteButton = this.contentEl.createEl('button');
deleteButton.classList.add("chat-action-button");
deleteButton.title = "Delete Message";
setIcon(deleteButton, "trash-2");
deleteButton.addEventListener('click', () => {
const messageEl = chatMessageBodyTextEl.closest('.khoj-chat-message');
if (messageEl) {
// Ask for confirmation before deleting
if (confirm('Are you sure you want to delete this message?')) {
this.deleteMessage(messageEl as HTMLElement);
}
}
});
}

// Only enable the speech feature if the user is subscribed
let speechButton = null;

Expand All @@ -649,7 +688,9 @@ export class KhojChatView extends KhojPaneView {

// Append buttons to parent element
chatMessageBodyTextEl.append(copyButton, pasteToFile);

if (deleteButton) {
chatMessageBodyTextEl.append(deleteButton);
}
if (speechButton) {
chatMessageBodyTextEl.append(speechButton);
}
Expand All @@ -675,7 +716,7 @@ export class KhojChatView extends KhojPaneView {
if (chatInput) {
chatInput.placeholder = this.startingMessage;
}
this.renderMessage(chatBodyEl, "Hey 👋🏾, what's up?", "khoj");
this.renderMessage({chatBodyEl, message: "Hey 👋🏾, what's up?", sender: "khoj", isSystemMessage: true});
}

async toggleChatSessions(forceShow: boolean = false): Promise<boolean> {
Expand Down Expand Up @@ -886,7 +927,12 @@ export class KhojChatView extends KhojPaneView {
if (responseJson.detail) {
// If the server returns error details in response, render a setup hint.
let setupMsg = "Hi 👋🏾, to start chatting add available chat models options via [the Django Admin panel](/server/admin) on the Server";
this.renderMessage(chatBodyEl, setupMsg, "khoj", undefined);
this.renderMessage({
chatBodyEl,
message: setupMsg,
sender: "khoj",
isSystemMessage: true
});

return false;
} else if (responseJson.response) {
Expand Down Expand Up @@ -929,7 +975,12 @@ export class KhojChatView extends KhojPaneView {
}
} catch (err) {
let errorMsg = "Unable to get response from Khoj server ❤️‍🩹. Ensure server is running or contact developers for help at [[email protected]](mailto:[email protected]) or in [Discord](https://discord.gg/BDgyabRM6e)";
this.renderMessage(chatBodyEl, errorMsg, "khoj", undefined);
this.renderMessage({
chatBodyEl,
message: errorMsg,
sender: "khoj",
isSystemMessage: true
});
return false;
}
return true;
Expand Down Expand Up @@ -1067,7 +1118,7 @@ export class KhojChatView extends KhojPaneView {

// Render user query as chat message
let chatBodyEl = this.contentEl.getElementsByClassName("khoj-chat-body")[0] as HTMLElement;
this.renderMessage(chatBodyEl, query, "you");
this.renderMessage({chatBodyEl, message: query, sender: "you"});

let conversationId = chatBodyEl.dataset.conversationId;
if (!conversationId) {
Expand Down Expand Up @@ -1487,4 +1538,49 @@ export class KhojChatView extends KhojPaneView {
}
}
}

// Add this new method to handle message deletion
async deleteMessage(messageEl: HTMLElement) {
const chatBodyEl = this.contentEl.getElementsByClassName("khoj-chat-body")[0] as HTMLElement;
const conversationId = chatBodyEl.dataset.conversationId;

// Get the turn_id from the message's data-meta attribute
const turnId = messageEl.getAttribute("data-meta");
if (!turnId || !conversationId) return;

try {
const response = await fetch(`${this.setting.khojUrl}/api/chat/conversation/message`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${this.setting.khojApiKey}`
},
body: JSON.stringify({
conversation_id: conversationId,
turn_id: turnId
})
});

if (response.ok) {
// Remove both the user message and Khoj response (the conversation turn)
const isKhojMessage = messageEl.classList.contains("khoj");
const messages = Array.from(chatBodyEl.getElementsByClassName("khoj-chat-message"));
const messageIndex = messages.indexOf(messageEl);

if (isKhojMessage && messageIndex > 0) {
// If it is a Khoj message, remove the previous user message too
messages[messageIndex - 1].remove();
} else if (!isKhojMessage && messageIndex < messages.length - 1) {
// If it is a user message, remove the next Khoj message too
messages[messageIndex + 1].remove();
}
messageEl.remove();
} else {
this.flashStatusInChatInput("Failed to delete message");
}
} catch (error) {
console.error("Error deleting message:", error);
this.flashStatusInChatInput("Error deleting message");
}
}
}