refactor: pre-cleanup.
This commit is contained in:
1 parent
0ceab9d897
commit
e10cbbc92c
53 files changed
+3596
-648
No files matched your search
@@ -0,0 +1,51 @@
|
||||
import { el } from "../base/dom.js";
|
||||
import { sessionTitle } from "./chat-render.js";
|
||||
|
||||
export function renderSessions({ sessionList, sessionTools, sessions, currentSession, onSelect }) {
|
||||
sessionList.replaceChildren();
|
||||
sessionTools.hidden = !currentSession;
|
||||
if (!sessions.length) {
|
||||
sessionList.append(el("div.chat-empty", "Your conversations will appear here."));
|
||||
return;
|
||||
}
|
||||
for (const session of sessions) {
|
||||
sessionList.append(el(
|
||||
"button.chat-session",
|
||||
{ class: currentSession === session.session_id ? "active" : "", onclick: () => onSelect(session.session_id) },
|
||||
el("strong", sessionTitle(session)),
|
||||
el("span", new Date(session.last_active_at).toLocaleString()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
export function renderSelectors(refs, data, onDangerous) {
|
||||
refs.persona.replaceChildren(el("option", { value: "" }, "Personality"));
|
||||
for (const name of data.personas || []) refs.persona.append(el("option", { value: name }, name));
|
||||
refs.persona.value = data.active_persona || "";
|
||||
const providers = data.providers || [];
|
||||
refs.provider.hidden = providers.length === 0;
|
||||
refs.provider.replaceChildren(el("option", { value: "" }, "Provider"));
|
||||
for (const name of providers) refs.provider.append(el("option", { value: name }, name));
|
||||
refs.provider.value = data.active_provider || providers[0] || "";
|
||||
renderModels(refs, data, refs.provider.value);
|
||||
refs.restart.hidden = !data.restart_available;
|
||||
refs.dangerousPanel.hidden = !data.dangerous_available;
|
||||
if (data.dangerous_available) onDangerous();
|
||||
}
|
||||
|
||||
export function renderModels(refs, data, providerName) {
|
||||
const grouped = data.models_by_provider || {};
|
||||
const names = providerName && grouped[providerName] ? grouped[providerName] : data.models || [];
|
||||
refs.model.replaceChildren(el("option", { value: "" }, "Model"));
|
||||
for (const name of names) refs.model.append(el("option", { value: name }, name));
|
||||
refs.model.value = data.active_model || "";
|
||||
}
|
||||
|
||||
export function renderCommands(commandHelp, commands) {
|
||||
const specs = (commands || []).map((item) => typeof item === "string" ? { command: item, usage: item, description: "" } : item);
|
||||
const list = el("div.chat-command-list");
|
||||
if (!specs.length) list.append(el("span", "Send a message to begin."));
|
||||
for (const spec of specs) list.append(el("div.chat-command-item", el("code", spec.usage || spec.command), el("span", spec.description || "")));
|
||||
commandHelp.replaceChildren(el("summary", `Available commands (${specs.length})`), list);
|
||||
return specs;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { el } from "../base/dom.js";
|
||||
|
||||
export function renderUpdate(panel, data, { onDefer, onInstall }) {
|
||||
panel.replaceChildren();
|
||||
const snapshot = data?.snapshot || null;
|
||||
const available = data?.available || [];
|
||||
if (!available.length) {
|
||||
panel.append(el("span", snapshot?.deferred ? "Update deferred." : "Archie is up to date."));
|
||||
return;
|
||||
}
|
||||
panel.append(
|
||||
el("div", el("strong", "Update available"), el("span", available.map((component) => `${component.Label || component.label}: ${component.Available || component.available}`).join(" · "))),
|
||||
el("div.chat-update-actions",
|
||||
el("button.btn", { onclick: onDefer }, "Defer"),
|
||||
data.can_install ? el("button.btn.btn-primary", { onclick: onInstall }, "Install update") : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function renderDangerous(panel, data, { onRequest, onDecision }) {
|
||||
panel.replaceChildren();
|
||||
const checkpoints = data?.checkpoints || [];
|
||||
const pending = data?.pending || [];
|
||||
const checkpoint = el("select.chat-select", { "aria-label": "Checkpoint" },
|
||||
el("option", { value: "" }, "Select checkpoint"),
|
||||
...checkpoints.map((item) => el("option", { value: item.Number ?? item.number }, `${item.Number ?? item.number} — ${item.Label ?? item.label ?? "checkpoint"}`)),
|
||||
);
|
||||
const stopSpec = el("input.chat-dangerous-input", { placeholder: "Process name or id", "aria-label": "Process name or id" });
|
||||
const request = (kind, spec) => () => onRequest(kind, String(spec.value || spec).trim());
|
||||
const decisionButton = (id, decision, label) => el("button.btn", { onclick: () => onDecision(id, decision) }, label);
|
||||
const pendingRows = pending.length ? pending.map((action) => el("div.chat-dangerous-pending",
|
||||
el("span", action.description),
|
||||
el("div.chat-update-actions",
|
||||
decisionButton(action.id, "approve", "Approve"),
|
||||
decisionButton(action.id, "permanent", "Approve for 24h"),
|
||||
decisionButton(action.id, "deny", "Deny"),
|
||||
),
|
||||
)) : [el("span.chat-hint", "No pending dangerous actions.")];
|
||||
panel.append(
|
||||
el("div.chat-dangerous-head", el("strong", "Dangerous actions"), el("span.chat-hint", "Every action requires approval.")),
|
||||
el("div.chat-dangerous-controls",
|
||||
el("div", checkpoint, el("button.btn", { onclick: request("rollback", checkpoint) }, "Request rollback")),
|
||||
el("div", stopSpec, el("button.btn", { onclick: request("stop", stopSpec) }, "Request stop")),
|
||||
),
|
||||
el("div.chat-dangerous-pending-list", ...pendingRows),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { el } from "../base/dom.js";
|
||||
import { renderMarkdown } from "./markdown.js";
|
||||
|
||||
export function sessionTitle(session) {
|
||||
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
|
||||
}
|
||||
|
||||
export function chatBubble(message) {
|
||||
const from = message.from ?? message.From ?? "";
|
||||
const text = message.text ?? message.Text ?? "";
|
||||
const isAssistant = from !== "web";
|
||||
return el(
|
||||
`div.chat-bubble-row.${isAssistant ? "assistant" : "user"}`,
|
||||
el(
|
||||
"div.chat-bubble",
|
||||
el("div.chat-bubble-meta", isAssistant ? "Archie" : "You"),
|
||||
isAssistant ? renderMarkdown(text) : el("div.chat-bubble-text", text),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
const CHANNEL_KEY = "archie.web.chat.channel";
|
||||
|
||||
export function channelID() {
|
||||
let id = localStorage.getItem(CHANNEL_KEY);
|
||||
if (!id) {
|
||||
id = crypto.randomUUID();
|
||||
localStorage.setItem(CHANNEL_KEY, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { renderMarkdown } from "./markdown.js";
|
||||
|
||||
export function updateStreamingReply(current, text) {
|
||||
const next = renderMarkdown(text);
|
||||
if (typeof current?.replaceWith === "function") current.replaceWith(next);
|
||||
else if (current?.parentNode) current.parentNode.replaceChild(next, current);
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import template from "./chat.html?raw";
|
||||
|
||||
export function createChatView() {
|
||||
const holder = document.createElement("template");
|
||||
holder.innerHTML = template.trim();
|
||||
const root = holder.content.firstElementChild;
|
||||
const refs = {};
|
||||
for (const node of root.querySelectorAll("[data-chat-ref]")) refs[node.dataset.chatRef] = node;
|
||||
return { root, refs };
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<div class="chat-page">
|
||||
<div class="chat-page-content">
|
||||
<header class="chat-topbar">
|
||||
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
|
||||
<div class="chat-topbar-actions">
|
||||
<span class="chat-status" data-chat-ref="status">Ready</span>
|
||||
<button class="btn" data-chat-ref="restart" hidden>Reload Telegram</button>
|
||||
<button class="btn" data-chat-ref="checkUpdates">Check updates</button>
|
||||
<select class="chat-select" data-chat-ref="persona" aria-label="Personality"><option value="">Personality</option></select>
|
||||
<select class="chat-select" data-chat-ref="provider" aria-label="Provider" hidden><option value="">Provider</option></select>
|
||||
<select class="chat-select" data-chat-ref="model" aria-label="Model"><option value="">Model</option></select>
|
||||
</div>
|
||||
</header>
|
||||
<div class="chat-update-panel" data-chat-ref="updatePanel"></div>
|
||||
<div class="chat-dangerous-panel" data-chat-ref="dangerousPanel" hidden></div>
|
||||
<div class="chat-layout">
|
||||
<aside class="chat-sidebar">
|
||||
<div class="chat-sidebar-head">
|
||||
<strong>Conversations</strong>
|
||||
<button class="btn btn-primary" data-chat-ref="newChat" type="button">+ New chat</button>
|
||||
</div>
|
||||
<div class="chat-session-list" data-chat-ref="sessionList"></div>
|
||||
</aside>
|
||||
<section class="chat-workspace">
|
||||
<div class="chat-workspace-head">
|
||||
<span class="chat-workspace-label">PERSONAL ASSISTANT</span>
|
||||
<details class="chat-command-help" data-chat-ref="commandHelp"></details>
|
||||
<details class="chat-session-tools" data-chat-ref="sessionTools">
|
||||
<summary>Session actions</summary>
|
||||
<div class="chat-session-tool-list">
|
||||
<button class="btn" data-chat-action="retry" type="button">Retry</button>
|
||||
<button class="btn" data-chat-action="undo" type="button">Undo</button>
|
||||
<button class="btn" data-chat-action="title" type="button">Rename</button>
|
||||
<button class="btn" data-chat-action="branch" type="button">Branch</button>
|
||||
<button class="btn" data-chat-action="compress" type="button">Preview compression</button>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<div class="chat-transcript" data-chat-ref="transcript">
|
||||
<div class="chat-empty-state" data-chat-ref="emptyState">
|
||||
<span class="chat-empty-mark">A</span>
|
||||
<h2>What are we working on?</h2>
|
||||
<p>Ask Archie anything, or start with one of these prompts.</p>
|
||||
<div class="chat-prompt-grid">
|
||||
<button class="chat-prompt" data-chat-prompt="Summarise active tasks" type="button">Summarise active tasks</button>
|
||||
<button class="chat-prompt" data-chat-prompt="Show running agents" type="button">Show running agents</button>
|
||||
<button class="chat-prompt" data-chat-prompt="Check system status" type="button">Check system status</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chat-compose">
|
||||
<div class="chat-composer-shell">
|
||||
<textarea class="chat-composer" data-chat-ref="composer" rows="3" placeholder="Message Archie… (commands like /status and /new work here)" aria-label="Message Archie"></textarea>
|
||||
<div class="chat-command-menu" data-chat-ref="commandMenu" hidden role="listbox" aria-label="Commands"></div>
|
||||
<div class="chat-compose-actions">
|
||||
<span class="chat-hint">⌘/Ctrl + Enter to send</span>
|
||||
<button class="btn" data-chat-ref="stop" type="button" disabled>Stop</button>
|
||||
<button class="btn btn-primary" data-chat-ref="send" type="button">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
+86
-354
@@ -1,183 +1,19 @@
|
||||
import { el, mount } from "../base/dom.js";
|
||||
import { el } from "../base/dom.js";
|
||||
import { api } from "../base/api.js";
|
||||
import { createChatView } from "./chat-view.js";
|
||||
import { chatBubble } from "./chat-render.js";
|
||||
import { updateStreamingReply } from "./chat-stream.js";
|
||||
import { channelID } from "./chat-state.js";
|
||||
import { renderCommands, renderModels, renderSelectors, renderSessions } from "./chat-catalog.js";
|
||||
import { renderDangerous, renderUpdate } from "./chat-panels.js";
|
||||
|
||||
import "./chat.css";
|
||||
|
||||
const CHANNEL_KEY = "archie.web.chat.channel";
|
||||
|
||||
function channelID() {
|
||||
let id = localStorage.getItem(CHANNEL_KEY);
|
||||
if (!id) {
|
||||
id = crypto.randomUUID();
|
||||
localStorage.setItem(CHANNEL_KEY, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
function sessionTitle(session) {
|
||||
return session.title || session.branch_name || `Conversation ${session.session_id.slice(0, 8)}`;
|
||||
}
|
||||
|
||||
function inlineMarkdown(text) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const pattern = /(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > cursor) fragment.append(document.createTextNode(text.slice(cursor, match.index)));
|
||||
const value = match[0];
|
||||
if (value.startsWith("~~")) fragment.append(el("del", value.slice(2, -2)));
|
||||
else if (value.startsWith("**") || value.startsWith("__")) fragment.append(el("strong", value.slice(2, -2)));
|
||||
else if (value.startsWith("`")) fragment.append(el("code", value.slice(1, -1)));
|
||||
else if (value.startsWith("[")) {
|
||||
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);
|
||||
fragment.append(el("a", { href: link[2], target: "_blank", rel: "noreferrer" }, link[1]));
|
||||
} else fragment.append(el("em", value.slice(1, -1)));
|
||||
cursor = match.index + value.length;
|
||||
}
|
||||
if (cursor < text.length) fragment.append(document.createTextNode(text.slice(cursor)));
|
||||
return fragment;
|
||||
}
|
||||
|
||||
function renderMarkdown(text) {
|
||||
const root = el("div.chat-bubble-text");
|
||||
const lines = String(text || "").split("\n");
|
||||
let paragraph = [];
|
||||
let list = null;
|
||||
let code = null;
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length) {
|
||||
root.append(el("p", inlineMarkdown(paragraph.join(" "))));
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (list) root.append(list);
|
||||
list = null;
|
||||
};
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
if (line.startsWith("```")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) {
|
||||
root.append(el("pre", el("code", code.join("\n"))));
|
||||
code = null;
|
||||
} else code = [];
|
||||
continue;
|
||||
}
|
||||
if (code) {
|
||||
code.push(line);
|
||||
continue;
|
||||
}
|
||||
const headerCells = tableCells(line);
|
||||
const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
|
||||
if (headerCells && separatorCells && isTableSeparator(separatorCells) && headerCells.length === separatorCells.length) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
const rows = [];
|
||||
for (index += 2; index < lines.length; index++) {
|
||||
const cells = tableCells(lines[index]);
|
||||
if (!cells || cells.length !== headerCells.length) {
|
||||
index--;
|
||||
break;
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
const body = el("tbody");
|
||||
for (const row of rows) {
|
||||
body.append(el("tr", ...row.map((cell) => el("td", inlineMarkdown(cell)))));
|
||||
}
|
||||
root.append(el(
|
||||
"table",
|
||||
el("thead", el("tr", ...headerCells.map((cell) => el("th", inlineMarkdown(cell))))),
|
||||
body,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
continue;
|
||||
}
|
||||
const heading = line.match(/^(#{1,3})\s+(.+)$/);
|
||||
if (heading) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el(`h${heading[1].length}`, inlineMarkdown(heading[2])));
|
||||
continue;
|
||||
}
|
||||
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
|
||||
if (bullet || ordered) {
|
||||
flushParagraph();
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
if (!list || list.tagName.toLowerCase() !== tag) {
|
||||
flushList();
|
||||
list = el(tag);
|
||||
}
|
||||
list.append(el("li", inlineMarkdown((bullet || ordered)[1])));
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(">")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el("blockquote", inlineMarkdown(line.replace(/^>\s?/, ""))));
|
||||
continue;
|
||||
}
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) root.append(el("pre", el("code", code.join("\n"))));
|
||||
return root;
|
||||
}
|
||||
|
||||
function tableCells(line) {
|
||||
const value = String(line || "").trim();
|
||||
if (!value.includes("|")) return null;
|
||||
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
|
||||
const cells = unwrapped.split("|").map((cell) => cell.trim());
|
||||
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
|
||||
}
|
||||
|
||||
function isTableSeparator(cells) {
|
||||
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
|
||||
}
|
||||
|
||||
function chatBubble(message) {
|
||||
const from = message.from ?? message.From ?? "";
|
||||
const text = message.text ?? message.Text ?? "";
|
||||
const isAssistant = from !== "web";
|
||||
return el(
|
||||
`div.chat-bubble-row.${isAssistant ? "assistant" : "user"}`,
|
||||
el(
|
||||
"div.chat-bubble",
|
||||
el("div.chat-bubble-meta", isAssistant ? "Archie" : "You"),
|
||||
isAssistant ? renderMarkdown(text) : el("div.chat-bubble-text", text),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function chatPage() {
|
||||
const root = el("div.chat-page");
|
||||
const sessionList = el("div.chat-session-list");
|
||||
const transcript = el("div.chat-transcript");
|
||||
const composer = el("textarea.chat-composer", {
|
||||
rows: 3,
|
||||
placeholder: "Message Archie… (commands like /status and /new work here)",
|
||||
"aria-label": "Message Archie",
|
||||
});
|
||||
const send = el("button.btn.btn-primary", "Send");
|
||||
const stop = el("button.btn", { disabled: true }, "Stop");
|
||||
const status = el("span.chat-status", "Ready");
|
||||
const persona = el("select.chat-select", { "aria-label": "Personality" });
|
||||
const provider = el("select.chat-select", { "aria-label": "Provider", hidden: true });
|
||||
const model = el("select.chat-select", { "aria-label": "Model" });
|
||||
const restart = el("button.btn", { hidden: true, onclick: () => {
|
||||
if (!window.confirm("Reload the Telegram chat adapter?")) return;
|
||||
composer.value = "/restart";
|
||||
sendMessage();
|
||||
} }, "Reload Telegram");
|
||||
const { root, refs } = createChatView();
|
||||
const { sessionList, transcript, composer, send, stop, status, persona, provider, model,
|
||||
restart, emptyState, updatePanel, dangerousPanel, commandMenu, sessionTools, commandHelp,
|
||||
checkUpdates, newChat } = refs;
|
||||
let currentSession = "";
|
||||
let sessions = [];
|
||||
let sending = false;
|
||||
@@ -188,16 +24,15 @@ export function chatPage() {
|
||||
let commandMatches = [];
|
||||
let commandSelection = 0;
|
||||
|
||||
const emptyState = el(
|
||||
"div.chat-empty-state",
|
||||
el("span.chat-empty-mark", "A"),
|
||||
el("h2", "What are we working on?"),
|
||||
el("p", "Ask Archie anything, or start with one of these prompts."),
|
||||
el("div.chat-prompt-grid",
|
||||
...["Summarise active tasks", "Show running agents", "Check system status"].map((prompt) =>
|
||||
el("button.chat-prompt", { onclick: () => { composer.value = prompt; composer.focus(); } }, prompt)),
|
||||
),
|
||||
);
|
||||
restart.onclick = () => {
|
||||
if (!window.confirm("Reload the Telegram chat adapter?")) return;
|
||||
composer.value = "/restart";
|
||||
sendMessage();
|
||||
};
|
||||
newChat.onclick = () => { composer.value = "/new"; sendMessage(); };
|
||||
for (const prompt of root.querySelectorAll("[data-chat-prompt]")) {
|
||||
prompt.onclick = () => { composer.value = prompt.dataset.chatPrompt; composer.focus(); };
|
||||
}
|
||||
|
||||
function appendMessage(message) {
|
||||
emptyState.remove();
|
||||
@@ -205,65 +40,6 @@ export function chatPage() {
|
||||
transcript.scrollTop = transcript.scrollHeight;
|
||||
}
|
||||
|
||||
function renderSessions() {
|
||||
sessionList.replaceChildren();
|
||||
sessionTools.hidden = !currentSession;
|
||||
if (!sessions.length) {
|
||||
sessionList.append(el("div.chat-empty", "Your conversations will appear here."));
|
||||
return;
|
||||
}
|
||||
for (const session of sessions) {
|
||||
const item = el(
|
||||
"button.chat-session",
|
||||
{ class: currentSession === session.session_id ? "active" : "", onclick: () => selectSession(session.session_id) },
|
||||
el("strong", sessionTitle(session)),
|
||||
el("span", new Date(session.last_active_at).toLocaleString()),
|
||||
);
|
||||
sessionList.append(item);
|
||||
}
|
||||
}
|
||||
|
||||
function renderSelectors(data) {
|
||||
selectorData = data;
|
||||
persona.replaceChildren(el("option", { value: "" }, "Personality"));
|
||||
for (const name of data.personas || []) persona.append(el("option", { value: name }, name));
|
||||
persona.value = data.active_persona || "";
|
||||
const providers = data.providers || [];
|
||||
provider.hidden = providers.length === 0;
|
||||
provider.replaceChildren(el("option", { value: "" }, "Provider"));
|
||||
for (const name of providers) provider.append(el("option", { value: name }, name));
|
||||
provider.value = data.active_provider || providers[0] || "";
|
||||
renderModelsForProvider(provider.value);
|
||||
restart.hidden = !data.restart_available;
|
||||
dangerousPanel.hidden = !data.dangerous_available;
|
||||
if (data.dangerous_available) refreshDangerous();
|
||||
}
|
||||
|
||||
function renderModelsForProvider(providerName) {
|
||||
const grouped = selectorData.models_by_provider || {};
|
||||
const names = providerName && grouped[providerName] ? grouped[providerName] : selectorData.models || [];
|
||||
model.replaceChildren(el("option", { value: "" }, "Model"));
|
||||
for (const name of names) model.append(el("option", { value: name }, name));
|
||||
model.value = selectorData.active_model || "";
|
||||
}
|
||||
|
||||
function renderCommands(data) {
|
||||
const commands = data.commands || [];
|
||||
commandSpecs = commands.map((item) => typeof item === "string" ? { command: item, usage: item, description: "" } : item);
|
||||
const list = el("div.chat-command-list");
|
||||
if (!commands.length) list.append(el("span", "Send a message to begin."));
|
||||
for (const item of commands) {
|
||||
const spec = typeof item === "string" ? { command: item, usage: item, description: "" } : item;
|
||||
list.append(el("div.chat-command-item", el("code", spec.usage || spec.command), el("span", spec.description || "")));
|
||||
}
|
||||
commandHelp.replaceChildren(el("summary", `Available commands (${commands.length})`), list);
|
||||
}
|
||||
|
||||
const updatePanel = el("div.chat-update-panel");
|
||||
const dangerousPanel = el("div.chat-dangerous-panel", { hidden: true });
|
||||
const commandMenu = el("div.chat-command-menu", { hidden: true, role: "listbox", "aria-label": "Commands" });
|
||||
const sessionTools = el("details.chat-session-tools", { hidden: true });
|
||||
|
||||
function commandQuery() {
|
||||
const before = composer.value.slice(0, composer.selectionStart);
|
||||
const match = before.match(/(?:^|\s)\/([^\s]*)$/);
|
||||
@@ -320,79 +96,51 @@ export function chatPage() {
|
||||
composer.focus();
|
||||
}
|
||||
|
||||
function renderUpdate(data) {
|
||||
updatePanel.replaceChildren();
|
||||
updateSnapshot = data?.snapshot || null;
|
||||
const available = data?.available || [];
|
||||
if (!available.length) {
|
||||
updatePanel.append(el("span", data?.snapshot?.deferred ? "Update deferred." : "Archie is up to date."));
|
||||
return;
|
||||
}
|
||||
updatePanel.append(
|
||||
el("div", el("strong", "Update available"), el("span", available.map((component) => `${component.Label || component.label}: ${component.Available || component.available}`).join(" · "))),
|
||||
el("div.chat-update-actions",
|
||||
el("button.btn", { onclick: async () => { await api.chatUpdateDefer(updateSnapshot); renderUpdate({ snapshot: { deferred: true }, available: [] }); status.textContent = "Update deferred"; } }, "Defer"),
|
||||
data.can_install ? el("button.btn.btn-primary", { onclick: async () => { status.textContent = "Installing…"; await api.chatUpdateInstall(updateSnapshot); status.textContent = "Update started"; refreshUpdate(); } }, "Install update") : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function refreshUpdate() {
|
||||
try {
|
||||
renderUpdate(await api.chatUpdate());
|
||||
const data = await api.chatUpdate();
|
||||
updateSnapshot = data?.snapshot || null;
|
||||
renderUpdate(updatePanel, data, {
|
||||
onDefer: async () => {
|
||||
await api.chatUpdateDefer(updateSnapshot);
|
||||
renderUpdate(updatePanel, { snapshot: { deferred: true }, available: [] }, { onDefer: () => {}, onInstall: () => {} });
|
||||
status.textContent = "Update deferred";
|
||||
},
|
||||
onInstall: async () => {
|
||||
status.textContent = "Installing…";
|
||||
await api.chatUpdateInstall(updateSnapshot);
|
||||
status.textContent = "Update started";
|
||||
refreshUpdate();
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
updatePanel.replaceChildren(el("span", err.message || "Updates unavailable"));
|
||||
}
|
||||
}
|
||||
|
||||
function dangerousActionButton(id, decision, label) {
|
||||
return el("button.btn", { onclick: async () => {
|
||||
try {
|
||||
await api.chatDangerousDecision(id, decision);
|
||||
status.textContent = decision === "deny" ? "Action denied" : "Action approved";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Approval failed";
|
||||
}
|
||||
} }, label);
|
||||
}
|
||||
|
||||
function renderDangerous(data) {
|
||||
dangerousPanel.replaceChildren();
|
||||
const checkpoints = data?.checkpoints || [];
|
||||
const pending = data?.pending || [];
|
||||
const checkpoint = el("select.chat-select", { "aria-label": "Checkpoint" },
|
||||
el("option", { value: "" }, "Select checkpoint"),
|
||||
...checkpoints.map((item) => el("option", { value: item.Number ?? item.number }, `${item.Number ?? item.number} — ${item.Label ?? item.label ?? "checkpoint"}`)),
|
||||
);
|
||||
const stopSpec = el("input.chat-dangerous-input", { placeholder: "Process name or id", "aria-label": "Process name or id" });
|
||||
const request = (kind, spec) => async () => {
|
||||
if (!String(spec.value || spec).trim()) return;
|
||||
try {
|
||||
await api.chatDangerousRequest(kind, String(spec.value || spec).trim());
|
||||
status.textContent = "Approval requested";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Could not request action";
|
||||
}
|
||||
};
|
||||
const pendingRows = pending.length ? pending.map((action) => el("div.chat-dangerous-pending",
|
||||
el("span", action.description),
|
||||
el("div.chat-update-actions", dangerousActionButton(action.id, "approve", "Approve"), dangerousActionButton(action.id, "permanent", "Approve for 24h"), dangerousActionButton(action.id, "deny", "Deny")),
|
||||
)) : [el("span.chat-hint", "No pending dangerous actions.")];
|
||||
dangerousPanel.append(
|
||||
el("div.chat-dangerous-head", el("strong", "Dangerous actions"), el("span.chat-hint", "Every action requires approval.")),
|
||||
el("div.chat-dangerous-controls",
|
||||
el("div", checkpoint, el("button.btn", { onclick: request("rollback", checkpoint) }, "Request rollback")),
|
||||
el("div", stopSpec, el("button.btn", { onclick: request("stop", stopSpec) }, "Request stop")),
|
||||
),
|
||||
el("div.chat-dangerous-pending-list", ...pendingRows),
|
||||
);
|
||||
}
|
||||
|
||||
async function refreshDangerous() {
|
||||
try {
|
||||
renderDangerous(await api.chatDangerous());
|
||||
renderDangerous(dangerousPanel, await api.chatDangerous(), {
|
||||
onRequest: async (kind, spec) => {
|
||||
if (!spec) return;
|
||||
try {
|
||||
await api.chatDangerousRequest(kind, spec);
|
||||
status.textContent = "Approval requested";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Could not request action";
|
||||
}
|
||||
},
|
||||
onDecision: async (id, decision) => {
|
||||
try {
|
||||
await api.chatDangerousDecision(id, decision);
|
||||
status.textContent = decision === "deny" ? "Action denied" : "Action approved";
|
||||
await refreshDangerous();
|
||||
} catch (err) {
|
||||
status.textContent = err.message || "Approval failed";
|
||||
}
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
dangerousPanel.replaceChildren(el("span.chat-hint", err.message || "Dangerous actions unavailable"));
|
||||
}
|
||||
@@ -401,9 +149,10 @@ export function chatPage() {
|
||||
async function refreshSessions() {
|
||||
const data = await api.chatSessions();
|
||||
sessions = data.sessions || [];
|
||||
renderSelectors(data);
|
||||
renderCommands(data);
|
||||
renderSessions();
|
||||
selectorData = data;
|
||||
renderSelectors({ persona, provider, model, restart, dangerousPanel }, data, refreshDangerous);
|
||||
commandSpecs = renderCommands(commandHelp, data.commands);
|
||||
renderSessions({ sessionList, sessionTools, sessions, currentSession, onSelect: selectSession });
|
||||
if (!currentSession && sessions[0]) await selectSession(sessions[0].session_id);
|
||||
}
|
||||
|
||||
@@ -429,7 +178,7 @@ export function chatPage() {
|
||||
|
||||
async function selectSession(id) {
|
||||
currentSession = id;
|
||||
renderSessions();
|
||||
renderSessions({ sessionList, sessionTools, sessions, currentSession, onSelect: selectSession });
|
||||
transcript.replaceChildren();
|
||||
await api.chatMessage(channelID(), `/resume ${id}`);
|
||||
persona.value = selectorData.active_personas?.[id] || selectorData.active_persona || "";
|
||||
@@ -451,7 +200,8 @@ export function chatPage() {
|
||||
composer.value = "";
|
||||
const replyBubble = el("div.chat-bubble-row.assistant", el("div.chat-bubble", el("div.chat-bubble-meta", "Archie"), el("div.chat-bubble-text")));
|
||||
transcript.append(replyBubble);
|
||||
const replyText = replyBubble.querySelector(".chat-bubble-text");
|
||||
let replyText = replyBubble.querySelector(".chat-bubble-text");
|
||||
let streamedText = "";
|
||||
let timeout;
|
||||
try {
|
||||
activeController = new AbortController();
|
||||
@@ -476,22 +226,28 @@ export function chatPage() {
|
||||
if (!line) continue;
|
||||
const event = JSON.parse(line.slice(6));
|
||||
if (event.session_id) currentSession = event.session_id;
|
||||
if (event.type === "delta") replyText.textContent += event.text;
|
||||
if (event.type === "done" && !replyText.textContent) replyText.textContent = event.text;
|
||||
if (event.type === "delta") {
|
||||
streamedText += event.text;
|
||||
replyText = updateStreamingReply(replyText, streamedText);
|
||||
}
|
||||
if (event.type === "done" && !streamedText) {
|
||||
streamedText = event.text;
|
||||
replyText = updateStreamingReply(replyText, streamedText);
|
||||
}
|
||||
if (event.type === "error") throw new Error(event.text);
|
||||
}
|
||||
if (done) break;
|
||||
}
|
||||
if (replyText.isConnected) replyText.replaceWith(renderMarkdown(replyText.textContent));
|
||||
if (replyText.isConnected) replyText = updateStreamingReply(replyText, streamedText);
|
||||
status.textContent = "Ready";
|
||||
await refreshSessions();
|
||||
if (currentSession) await selectSession(currentSession);
|
||||
} catch (err) {
|
||||
if (err.name === "AbortError") {
|
||||
replyText.textContent = "Turn stopped.";
|
||||
replyText = updateStreamingReply(replyText, "Turn stopped.");
|
||||
status.textContent = "Stopped";
|
||||
} else {
|
||||
replyText.textContent = `Unable to complete that turn: ${err.message || err}`;
|
||||
replyText = updateStreamingReply(replyText, `Unable to complete that turn: ${err.message || err}`);
|
||||
status.textContent = "Error";
|
||||
}
|
||||
} finally {
|
||||
@@ -550,7 +306,7 @@ export function chatPage() {
|
||||
status.textContent = `Personality: ${persona.value}`;
|
||||
};
|
||||
provider.onchange = async () => {
|
||||
renderModelsForProvider(provider.value);
|
||||
renderModels({ model }, selectorData, provider.value);
|
||||
if (!provider.value) return;
|
||||
await applyModelCommand(`/model --provider ${provider.value}`);
|
||||
};
|
||||
@@ -567,41 +323,17 @@ export function chatPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const commandHelp = el("details.chat-command-help");
|
||||
const checkUpdates = el("button.btn", { onclick: refreshUpdate }, "Check updates");
|
||||
const sessionActions = el(
|
||||
"div.chat-session-tool-list",
|
||||
el("button.btn", { type: "button", onclick: () => runSessionCommand("/retry") }, "Retry"),
|
||||
el("button.btn", { type: "button", onclick: () => runSessionCommand("/undo") }, "Undo"),
|
||||
el("button.btn", { type: "button", onclick: () => promptSessionCommand("/title", "Session title") }, "Rename"),
|
||||
el("button.btn", { type: "button", onclick: () => promptSessionCommand("/branch", "Branch name (optional)") }, "Branch"),
|
||||
el("button.btn", { type: "button", onclick: () => runSessionCommand("/compress --preview") }, "Preview compression"),
|
||||
);
|
||||
sessionTools.append(el("summary", "Session actions"), sessionActions);
|
||||
const chatTopbar = el(
|
||||
"div.chat-topbar",
|
||||
el("div", el("span.chat-kicker", "ARCHIE WORKSPACE"), el("h1.page-title", "Chat")),
|
||||
el("div.chat-topbar-actions", el("span.chat-status", status), restart, checkUpdates, persona, provider, model),
|
||||
);
|
||||
const chatLayout = el(
|
||||
"div.chat-layout",
|
||||
el("aside.chat-sidebar", el("div.chat-sidebar-head", el("strong", "Conversations"), el("button.btn.btn-primary", { onclick: () => { composer.value = "/new"; sendMessage(); } }, "+ New chat")), sessionList),
|
||||
el(
|
||||
"section.chat-workspace",
|
||||
el("div.chat-workspace-head", el("span.chat-workspace-label", "PERSONAL ASSISTANT"), commandHelp, sessionTools),
|
||||
transcript,
|
||||
el("div.chat-compose", el("div.chat-composer-shell", composer, commandMenu, el("div.chat-compose-actions", el("span.chat-hint", "⌘/Ctrl + Enter to send"), stop, send))),
|
||||
),
|
||||
);
|
||||
mount(root, el(
|
||||
"div.chat-page-content",
|
||||
chatTopbar,
|
||||
updatePanel,
|
||||
dangerousPanel,
|
||||
chatLayout,
|
||||
));
|
||||
|
||||
transcript.append(emptyState);
|
||||
checkUpdates.onclick = refreshUpdate;
|
||||
const actionHandlers = {
|
||||
retry: () => runSessionCommand("/retry"),
|
||||
undo: () => runSessionCommand("/undo"),
|
||||
title: () => promptSessionCommand("/title", "Session title"),
|
||||
branch: () => promptSessionCommand("/branch", "Branch name (optional)"),
|
||||
compress: () => runSessionCommand("/compress --preview"),
|
||||
};
|
||||
for (const button of root.querySelectorAll("[data-chat-action]")) {
|
||||
button.onclick = actionHandlers[button.dataset.chatAction];
|
||||
}
|
||||
|
||||
refreshSessions().catch((err) => { status.textContent = err.message || "Chat unavailable"; });
|
||||
refreshUpdate();
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { el } from "../base/dom.js";
|
||||
|
||||
function inlineMarkdown(text) {
|
||||
const fragment = document.createDocumentFragment();
|
||||
const pattern = /(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
let cursor = 0;
|
||||
for (const match of text.matchAll(pattern)) {
|
||||
if (match.index > cursor) fragment.append(document.createTextNode(text.slice(cursor, match.index)));
|
||||
const value = match[0];
|
||||
if (value.startsWith("~~")) fragment.append(el("del", value.slice(2, -2)));
|
||||
else if (value.startsWith("**") || value.startsWith("__")) fragment.append(el("strong", value.slice(2, -2)));
|
||||
else if (value.startsWith("`")) fragment.append(el("code", value.slice(1, -1)));
|
||||
else if (value.startsWith("[")) {
|
||||
const link = value.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);
|
||||
fragment.append(el("a", { href: link[2], target: "_blank", rel: "noreferrer" }, link[1]));
|
||||
} else fragment.append(el("em", value.slice(1, -1)));
|
||||
cursor = match.index + value.length;
|
||||
}
|
||||
if (cursor < text.length) fragment.append(document.createTextNode(text.slice(cursor)));
|
||||
return fragment;
|
||||
}
|
||||
|
||||
export function renderMarkdown(text) {
|
||||
const root = el("div.chat-bubble-text");
|
||||
const lines = String(text || "").split("\n");
|
||||
let paragraph = [];
|
||||
let list = null;
|
||||
let code = null;
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length) {
|
||||
root.append(el("p", inlineMarkdown(paragraph.join(" "))));
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (list) root.append(list);
|
||||
list = null;
|
||||
};
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
if (line.startsWith("```")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) {
|
||||
root.append(el("pre", el("code", code.join("\n"))));
|
||||
code = null;
|
||||
} else code = [];
|
||||
continue;
|
||||
}
|
||||
if (code) {
|
||||
code.push(line);
|
||||
continue;
|
||||
}
|
||||
const headerCells = tableCells(line);
|
||||
const separatorCells = index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
|
||||
if (headerCells && separatorCells && isTableSeparator(separatorCells) && headerCells.length === separatorCells.length) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
const rows = [];
|
||||
for (index += 2; index < lines.length; index++) {
|
||||
const cells = tableCells(lines[index]);
|
||||
if (!cells || cells.length !== headerCells.length) {
|
||||
index--;
|
||||
break;
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
const body = el("tbody");
|
||||
for (const row of rows) body.append(el("tr", ...row.map((cell) => el("td", inlineMarkdown(cell)))));
|
||||
root.append(el("table", el("thead", el("tr", ...headerCells.map((cell) => el("th", inlineMarkdown(cell))))), body));
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
continue;
|
||||
}
|
||||
const heading = line.match(/^(#{1,3})\s+(.+)$/);
|
||||
if (heading) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el(`h${heading[1].length}`, inlineMarkdown(heading[2])));
|
||||
continue;
|
||||
}
|
||||
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
|
||||
if (bullet || ordered) {
|
||||
flushParagraph();
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
if (!list || list.tagName.toLowerCase() !== tag) {
|
||||
flushList();
|
||||
list = el(tag);
|
||||
}
|
||||
list.append(el("li", inlineMarkdown((bullet || ordered)[1])));
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(">")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
root.append(el("blockquote", inlineMarkdown(line.replace(/^>\s?/, ""))));
|
||||
continue;
|
||||
}
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) root.append(el("pre", el("code", code.join("\n"))));
|
||||
return root;
|
||||
}
|
||||
|
||||
function tableCells(line) {
|
||||
const value = String(line || "").trim();
|
||||
if (!value.includes("|")) return null;
|
||||
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
|
||||
const cells = unwrapped.split("|").map((cell) => cell.trim());
|
||||
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
|
||||
}
|
||||
|
||||
function isTableSeparator(cells) {
|
||||
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export function taskRowA11y(task, expanded) {
|
||||
const title = task.title || "untitled task";
|
||||
return {
|
||||
"aria-expanded": String(expanded),
|
||||
"aria-controls": `task-timeline-${task.id}`,
|
||||
"aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${title}`,
|
||||
};
|
||||
}
|
||||
@@ -36,6 +36,26 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.task-expand {
|
||||
width: 1.5rem;
|
||||
height: 1.5rem;
|
||||
margin-right: var(--sp-2);
|
||||
padding: 0;
|
||||
color: var(--fg-muted);
|
||||
background: transparent;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 50%;
|
||||
font: inherit;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.task-expand:hover,
|
||||
.task-expand:focus-visible {
|
||||
color: var(--fg);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.activity-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
+28
-5
@@ -2,6 +2,7 @@ import "./tasks.css";
|
||||
import { api } from "../base/api.js";
|
||||
import { ago, el, empty, mount, pill, statusKind } from "../base/dom.js";
|
||||
import { statTile } from "../base/statTile.js";
|
||||
import { taskRowA11y } from "./task-row.js";
|
||||
|
||||
/**
|
||||
* Plain-language status labels. One place, so "waiting_human" only ever
|
||||
@@ -199,16 +200,37 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
}
|
||||
|
||||
function taskRow(t) {
|
||||
const expanded = expandedId === t.id;
|
||||
const timelineID = `task-timeline-${t.id}`;
|
||||
const toggle = (event) => {
|
||||
event?.stopPropagation();
|
||||
expandedId = expandedId === t.id ? null : t.id;
|
||||
renderRows();
|
||||
if (expandedId === t.id) loadTimeline(t.id);
|
||||
};
|
||||
return el(
|
||||
"tr.task-row",
|
||||
{
|
||||
onclick: () => {
|
||||
expandedId = expandedId === t.id ? null : t.id;
|
||||
renderRows();
|
||||
if (expandedId === t.id) loadTimeline(t.id);
|
||||
...taskRowA11y(t, expanded),
|
||||
tabindex: "0",
|
||||
onkeydown: (event) => {
|
||||
if (event.key !== "Enter" && event.key !== " ") return;
|
||||
event.preventDefault();
|
||||
toggle(event);
|
||||
},
|
||||
onclick: toggle,
|
||||
},
|
||||
el("td.mono", repoLink(t) ?? `${t.owner}/${t.repo}`),
|
||||
el(
|
||||
"td.mono",
|
||||
el("button.task-expand", {
|
||||
type: "button",
|
||||
"aria-expanded": String(expanded),
|
||||
"aria-controls": timelineID,
|
||||
"aria-label": `${expanded ? "Collapse" : "Expand"} timeline for ${t.title || "untitled task"}`,
|
||||
onclick: toggle,
|
||||
}, expanded ? "−" : "+"),
|
||||
repoLink(t) ?? `${t.owner}/${t.repo}`,
|
||||
),
|
||||
el("td.mono", issueLink(t) ?? `#${t.issue_number}`),
|
||||
el("td.strong", t.title || "(untitled)"),
|
||||
el("td", pill(statusLabel(t.status), statusKind(t.status))),
|
||||
@@ -322,6 +344,7 @@ export function tasksPage(params = new URLSearchParams()) {
|
||||
const cached = eventCache.get(t.id);
|
||||
return el(
|
||||
"tr.task-timeline-row",
|
||||
{ id: `task-timeline-${t.id}` },
|
||||
el(
|
||||
"td",
|
||||
{ colspan: 8 },
|
||||
|
||||
Reference in new issue
Block a user