const {
plugin: { store, scoped },
ui: {
openModal,
Button,
ButtonColors,
ButtonLooks,
TextBox,
TextArea,
ModalRoot,
ModalHeader,
ModalBody,
ModalFooter,
Header,
HeaderTags,
Text,
TextTags,
Divider,
showToast,
ToastColors,
injectCss,
},
flux: { stores },
} = shelter;
const UNSLOTH_DEFAULT_URL = "http://localhost:8000";
const UNSLOTH_MODEL = "default";
// ── Default settings ────────────────────────────────────────────
store.apiUrl ??= UNSLOTH_DEFAULT_URL;
store.apiKey ??= "";
store.model ??= UNSLOTH_MODEL;
store.maxTokens ??= 1024;
store.temperature ??= 0.7;
// ── Injected CSS for the menu items ─────────────────────────────
const removeCss = injectCss(`
[data-unsloth-menu-item] {
display: flex !important;
align-items: center !important;
gap: 8px !important;
padding: 6px 10px !important;
margin: 2px 6px !important;
cursor: pointer !important;
border-radius: 3px !important;
color: var(--interactive-normal) !important;
font-size: 14px !important;
line-height: 18px !important;
font-weight: 500 !important;
}
[data-unsloth-menu-item]:hover {
background: var(--background-modifier-hover) !important;
color: var(--interactive-hover) !important;
}
[data-unsloth-menu-item] svg {
width: 18px !important;
height: 18px !important;
flex-shrink: 0 !important;
}
`);
scoped.onDispose(() => removeCss());
// ── SVG icons ───────────────────────────────────────────────────
const SPARKLE_ICON = ``;
const REPLY_ICON = ``;
// ── Helper: find and fill the message input ─────────────────────
function setMessageInput(text) {
// Broad selectors for Discord's chat input (textarea or contenteditable div)
const selectors = [
// Modern Discord: Slate-based contenteditable div
'[class*="channelTextArea"] div[role="textbox"][contenteditable="true"]',
'[class*="channelTextArea"] [data-slate-editor="true"]',
// Classic Discord: textarea inside channelTextArea
'[class*="channelTextArea"] textarea',
// Fallback: role="textbox" anywhere inside channelTextArea
'[class*="channelTextArea"] [role="textbox"]',
// Even broader fallbacks (no main/chat prefix)
'main [class*="channelTextArea"] textarea',
'main [class*="channelTextArea"] [role="textbox"]',
'[class*="chat"] [class*="channelTextArea"] textarea',
'[class*="chat"] [class*="channelTextArea"] [role="textbox"]',
];
let editorEl = null;
for (const sel of selectors) {
editorEl = document.querySelector(sel);
if (editorEl) break;
}
if (!editorEl) return false;
// Determine the native input element
let nativeInput;
const isContentEditable =
editorEl.tagName !== "TEXTAREA" &&
(editorEl.isContentEditable || editorEl.getAttribute("contenteditable") === "true");
if (editorEl.tagName === "TEXTAREA") {
// Classic Discord: direct textarea element
nativeInput = editorEl;
} else if (isContentEditable) {
// Modern Discord: Slate/contenteditable div - use it directly
nativeInput = editorEl;
} else {
// Look for a nested textarea (older layout)
nativeInput = editorEl.querySelector("textarea");
}
if (!nativeInput) return false;
// ── Set the value ───────────────────────────────────────────
nativeInput.focus();
if (nativeInput.tagName === "TEXTAREA") {
// Classic textarea input
nativeInput.value = text;
nativeInput.dispatchEvent(new Event("input", { bubbles: true, cancelable: true }));
} else {
// ContentEditable div — modern Discord Slate editor
// Slate listens for "beforeinput" events, not plain DOM mutations.
// We select all existing content, then dispatch beforeinput so
// Slate handles the replacement through its own React pipeline.
// 1. Select all existing content so the insert replaces everything
const sel = window.getSelection();
if (sel) {
try {
const range = document.createRange();
range.selectNodeContents(nativeInput);
sel.removeAllRanges();
sel.addRange(range);
} catch (_) { /* selection API may fail on some elements */ }
}
// 2. Dispatch beforeinput — this is what Slate's withReact
// plugin hooks into to update the editor's React state.
// dispatchEvent returns FALSE when the event was cancelled
// (Slate calls preventDefault when it handles the event).
// TRUE means nobody cancelled -> we need the fallback.
let needsFallback = true;
try {
const notCancelled = nativeInput.dispatchEvent(new InputEvent("beforeinput", {
inputType: "insertText",
data: text,
bubbles: true,
cancelable: true,
}));
needsFallback = notCancelled;
} catch (_) {
// InputEvent constructor may not be available (old Electron)
}
// 3. Fallback: if beforeinput wasn't cancelled by any handler
// use execCommand which works on older Discord layouts.
if (needsFallback) {
try {
document.execCommand("selectAll", false, null);
document.execCommand("insertText", false, text);
} catch (_) {
// Last resort: set textContent directly
nativeInput.textContent = text;
}
}
// 4. Always dispatch input — React-controlled components often
// listen for this in addition to beforeinput.
nativeInput.dispatchEvent(new Event("input", { bubbles: true }));
}
return true;
}
// ── API call ────────────────────────────────────────────────────
async function callUnsloth(prompt) {
const url = `${store.apiUrl.replace(/\/+$/, "")}/v1/chat/completions`;
const headers = { "Content-Type": "application/json" };
if (store.apiKey) {
headers["Authorization"] = `Bearer ${store.apiKey}`;
}
const body = {
model: store.model,
messages: [{ role: "user", content: prompt }],
stream: false,
max_tokens: store.maxTokens,
temperature: store.temperature,
};
let res;
let fetchError = null;
try {
res = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify(body),
});
} catch (e) {
fetchError = e;
}
if (fetchError) {
// Network-level error (e.g. Failed to fetch, CORS, DNS, etc.)
throw new DetailedApiError({
message: fetchError.message || "Failed to fetch",
url,
prompt,
model: store.model,
apiUrl: store.apiUrl,
status: null,
responseBody: null,
timestamp: new Date().toISOString(),
cause: fetchError,
});
}
if (!res.ok) {
let responseBody = null;
let detail = `API returned ${res.status}`;
try {
responseBody = await res.text();
try {
const err = JSON.parse(responseBody);
detail = err.error?.message || err.detail || detail;
} catch {}
} catch {}
throw new DetailedApiError({
message: detail,
url,
prompt,
model: store.model,
apiUrl: store.apiUrl,
status: res.status,
responseBody,
timestamp: new Date().toISOString(),
cause: null,
});
}
const data = await res.json();
const text = data?.choices?.[0]?.message?.content || "";
return text;
}
// ── Detailed error class ─────────────────────────────────────────
class DetailedApiError extends Error {
constructor(details) {
super(details.message);
this.name = "DetailedApiError";
this.url = details.url;
this.prompt = details.prompt;
this.model = details.model;
this.apiUrl = details.apiUrl;
this.status = details.status;
this.responseBody = details.responseBody;
this.timestamp = details.timestamp;
this.cause = details.cause;
}
}
// ── Error detail modal ──────────────────────────────────────────
const ERROR_MODAL_CLASS = "uns-errmodal";
// Injected CSS for the error modal — wider modal so all detail fits
const removeErrCss = injectCss(`
.${ERROR_MODAL_CLASS} {
width: 620px !important;
max-width: 90vw !important;
}
`);
scoped.onDispose(() => removeErrCss());
function ErrorDetailModal(props) {
const error = props.error;
return (