Skip to content
35 changes: 35 additions & 0 deletions src/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,37 @@ body {
-webkit-user-select: text;
}

/* Send is hidden beside the link, so this stands in for its 28px height and
evens the right padding with the left 13px. */
.quick-message-connect {
grid-area: 1 / 1;
padding-right: 5px;
line-height: 28px;
color: #8b93a7;
}

.quick-message-open {
display: inline;
margin: 0;
padding: 0;
border: 0;
appearance: none;
background: none;
font: inherit;
color: var(--shared-accent);
text-decoration: underline;
text-underline-offset: 2px;
cursor: pointer;
}

.quick-message-connect[hidden] {
display: none;
}

.quick-message-connect:not([hidden]) ~ .quick-message-field {
visibility: hidden;
}

.quick-message-field::placeholder {
color: #8b93a7;
}
Expand All @@ -310,6 +341,10 @@ body {
cursor: pointer;
}

.quick-message-send[hidden] {
display: none;
}

.quick-message-send svg {
display: block;
width: 12px;
Expand Down
30 changes: 28 additions & 2 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from "./bubble.js";
import { createCueMachine, cueAnchor, cueIo } from "./cue.js";
import {
CONNECT_HINT,
applyQuickMessageGate,
createQuickMessage,
crossedDrag,
Expand Down Expand Up @@ -344,6 +345,29 @@ function attachQuickMessage(view, id) {
field.disabled = true;
field.autocomplete = "off";
field.setAttribute("aria-label", "Quick message");
// Only where a click off the art lands. Elsewhere the hint stays text.
// A muted hint whose last words are the control, as the ask bubble does.
let link = null;
if (clickableOffArt) {
link = document.createElement("span");
link.className = "quick-message-connect";
link.hidden = true;
const openChat = document.createElement("button");
openChat.type = "button";
openChat.className = "quick-message-open";
openChat.textContent = "Open chat";
const swallow = (event) => event.stopPropagation();
openChat.addEventListener("pointerdown", swallow);
openChat.addEventListener("pointerup", swallow);
openChat.addEventListener("click", (event) => {
event.stopPropagation();
view.quickMachine.summon();
window.__TAURI__.core.invoke("overlay_open_chat", { id }).catch((err) => {
console.error("overlay_open_chat", err);
});
});
link.append(`${CONNECT_HINT} `, openChat);
}
const send = document.createElement("button");
send.type = "button";
send.className = "quick-message-send";
Expand All @@ -357,7 +381,9 @@ function attachQuickMessage(view, id) {
point.setAttribute("fill", "#14171e");
icon.append(point);
send.append(icon);
row.append(mirror, field);
// Before the field, so the sibling rule in main.css can hide the
// placeholder that would otherwise draw under the link.
row.append(mirror, ...(link ? [link] : []), field);
quick.append(row, send);
stage.append(quick);

Expand Down Expand Up @@ -395,7 +421,7 @@ function attachQuickMessage(view, id) {
},
});
view.quickMachine = machine;
view.quickGate = { field, send, machine };
view.quickGate = { field, send, link, machine };
view.quickMirror.textContent = "\u200b";
paintQuickGate(view, null);
refreshQuickGate(view, id);
Expand Down
20 changes: 16 additions & 4 deletions src/quick-message.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,36 @@
import { placeBubble } from "./bubble.js";
import { canAnswer, composerPlaceholder } from "./chat-connect.js";

// Ready keeps this pill's own prompt. Unavailable uses the Chat composer's
// sentence, including before the first opening arrives, so the two surfaces
// cannot disagree about why nothing will answer.
export const CONNECT_PROMPT = "Connect an AI to talk to me";
// Shorter than the prompt, so the hint and Open chat fit on one line.
export const CONNECT_HINT = "No AI connected yet.";

// Every unavailable state is fixed in Chat's landing, so the pill links there.
// A Harness still starting clears on its own and keeps Chat's sentence.
export function quickMessageConnects(opening) {
return !canAnswer(opening) && !opening?.harness?.initializing;
}

export function quickMessagePrompt(opening) {
if (canAnswer(opening)) return "talk to me";
if (quickMessageConnects(opening)) return CONNECT_PROMPT;
return composerPlaceholder(opening);
}

// `field` and `send` are the overlay's controls. `machine` is this module.
// One opening, the same one Chat paints from.
export function applyQuickMessageGate({ field, send, machine }, opening) {
// `link` is absent where the overlay cannot take a click off the art.
export function applyQuickMessageGate({ field, send, link, machine }, opening) {
const ready = canAnswer(opening);
// Enable before the machine claims the caret. focus() on a still-disabled
// field is dropped, and the pill would thaw with nowhere to type.
field.disabled = !ready;
send.disabled = !ready;
field.placeholder = quickMessagePrompt(opening);
field.setAttribute("aria-label", ready ? "Quick message" : field.placeholder);
if (link) link.hidden = !quickMessageConnects(opening);
// A disabled Send beside the link would read as a second, dead control.
send.hidden = Boolean(link) && !link.hidden;
machine.setAvailable(ready);
}

Expand Down
158 changes: 158 additions & 0 deletions tests/quick-message-connect.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// The unavailable pill's Open chat link opens Chat and is not a Poke. Drives the
// real src/index.html and main.js the way chat-elicit-link.test.js drives Chat.

import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { test } from "node:test";

const SRC = fileURLToPath(new URL("../src/", import.meta.url));

function chromeBin() {
if (process.env.FIDGET_CHROME) {
return process.env.FIDGET_CHROME;
}
for (const name of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]) {
const found = spawnSync("bash", ["-lc", `command -v ${name}`], { encoding: "utf8" });
const path = found.stdout.trim();
if (found.status === 0 && path) {
return path;
}
}
return null;
}

const chrome = chromeBin();

// Nothing configured, so nothing can answer and nothing is starting.
const opening = { configured: false, enabled: true, harness: null, login: "" };

const frame = {
sprites: [
{
id: "bmo",
character: "Buddy Bot",
animation: "idle",
frame_index: 0,
x: 200,
y: 200,
width: 64,
height: 64,
mirror: 1,
bubble: true,
},
],
visible: true,
fade_ms: 0,
sound: false,
};

function press() {
const stub = `
<script type="module">
const handlers = {};
window.__invoked = [];
window.__TAURI__ = {
core: {
invoke(name, args) {
window.__invoked.push({ name, args });
if (name === "character") return Promise.resolve({ characters: {} });
if (name === "overlay_hit_tests_hotspots") return Promise.resolve(true);
if (name === "chat_opening") return Promise.resolve(${JSON.stringify(opening)});
return Promise.resolve();
},
},
event: {
listen(name, handler) {
handlers[name] = handler;
return Promise.resolve(() => {});
},
},
webviewWindow: { getCurrentWebviewWindow: () => ({ label: "overlay-test" }) },
};
const tick = () => new Promise((r) => setTimeout(r, 50));
async function drive() {
while (!handlers.frame) await tick();
handlers.frame({ payload: ${JSON.stringify(frame)} });
await tick();
const quick = document.querySelector('.quick-message[data-instance="bmo"]');
document.querySelector('.sprite[data-instance="bmo"]').dispatchEvent(new PointerEvent("pointerenter"));
while (!quick.classList.contains("visible")) await tick();
const link = quick.querySelector(".quick-message-connect");
const openChat = link.querySelector(".quick-message-open");
const send = quick.querySelector(".quick-message-send");
const shown = {
hint: link.firstChild.textContent.trim(),
control: openChat.textContent,
linkShown: !link.hidden,
sendShown: !send.hidden && getComputedStyle(send).display !== "none",
oneLine: Math.abs(openChat.getBoundingClientRect().top - link.getBoundingClientRect().top) < 2,
};
const before = window.__invoked.length;
const at = { bubbles: true, button: 0, pointerId: 1, isPrimary: true };
openChat.dispatchEvent(new PointerEvent("pointerdown", at));
openChat.dispatchEvent(new PointerEvent("pointerup", at));
openChat.click();
for (let i = 0; i < 5; i += 1) await tick();
const out = document.createElement("pre");
out.id = "probe";
out.textContent = JSON.stringify({
...shown,
clicks: window.__invoked
.slice(before)
.filter((c) => ["overlay_primary", "overlay_secondary", "overlay_open_chat"].includes(c.name)),
open: quick.classList.contains("visible"),
});
document.body.append(out);
}
window.addEventListener("load", drive);
</script>`;

const dir = mkdtempSync(join(tmpdir(), "quick-message-connect-"));
const page = join(dir, "harness.html");
const html = readFileSync(join(SRC, "index.html"), "utf8").replace(
"<head>",
`<head><base href="${pathToFileURL(SRC).href}">${stub}`,
);
writeFileSync(page, html);

const run = spawnSync(
chrome,
[
"--headless",
"--disable-gpu",
"--no-sandbox",
"--disable-dev-shm-usage",
`--user-data-dir=${join(dir, "profile")}`,
"--allow-file-access-from-files",
"--virtual-time-budget=8000",
"--dump-dom",
pathToFileURL(page).href,
],
{ encoding: "utf8", maxBuffer: 1 << 24, timeout: 40000, killSignal: "SIGKILL" },
);
const match = run.stdout.match(/<pre id="probe"[^>]*>(.*?)<\/pre>/s);
assert.ok(match, `the overlay did not report. ${run.stderr?.slice(-500) ?? ""}`);
const json = match[1]
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">");
return JSON.parse(json);
}

const skip = chrome ? false : "headless Chromium is not installed";

test("a click on Open chat opens Chat, closes the pill, and is no Poke", { skip, timeout: 60000 }, () => {
const report = press();
assert.equal(report.hint, "No AI connected yet.");
assert.equal(report.control, "Open chat");
assert.equal(report.oneLine, true, "the hint and Open chat share one line");
assert.equal(report.linkShown, true);
assert.equal(report.sendShown, false, "Send is hidden while the link is up");
assert.deepEqual(report.clicks, [{ name: "overlay_open_chat", args: { id: "bmo" } }]);
assert.equal(report.open, false);
});
Loading
Loading