Skip to content

Commit

Permalink
Add frontend support for cancellation
Browse files Browse the repository at this point in the history
  • Loading branch information
willcrichton committed Sep 4, 2024
1 parent 61cf0bc commit 2385b9a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion crates/chatbot/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ impl Chatbot {
///
/// Warning: may take a few seconds!
pub async fn query_chat(&mut self, messages: &[String], docs: &[String]) -> Vec<String> {
std::thread::sleep(Duration::from_secs(2));
tokio::time::sleep(Duration::from_secs(2)).await;
let most_recent = messages.last().unwrap();
let emoji = &self.emojis[self.emoji_counter];
self.emoji_counter = (self.emoji_counter + 1) % self.emojis.len();
Expand Down
12 changes: 11 additions & 1 deletion crates/server/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ <h1>ChatABC</h1>
<form id="input">
<input type="text" />
<input type="submit" />
<button id="cancel" type="button">Cancel</button>
<span id="spinner"></span>
</form>
<div id="messages"></div>
Expand All @@ -35,6 +36,7 @@ <h1>ChatABC</h1>
let msgContainer = document.getElementById("messages");
let textEl = document.querySelector("form input[type=text]");
let spinnerEl = document.getElementById("spinner");
let cancelEl = document.getElementById("cancel");

async function fetchChat(chat) {
spinnerEl.classList.add("active");
Expand All @@ -46,7 +48,13 @@ <h1>ChatABC</h1>
body: JSON.stringify(chat)
});
if (!response.ok) throw new Error(response.statusText);
return await response.json();
let json = await response.json();
if (json.type === "Success") {
return json;
} else {
alert("Cancelled");
throw new Error("Cancelled");
}
} finally {
spinnerEl.classList.remove("active");
textEl.removeAttribute("disabled");
Expand All @@ -65,11 +73,13 @@ <h1>ChatABC</h1>
event.preventDefault();
chat.messages.push(textEl.value);
textEl.value = "";
updateChat(chat);
fetchChat(chat).then(updateChat);
}

function main() {
document.getElementById("input").addEventListener("submit", onSubmit);
cancelEl.addEventListener("click", () => fetch("/cancel", {method: "post"}));
}

main();
Expand Down

0 comments on commit 2385b9a

Please sign in to comment.