Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md
- luxe remote puts the sessions on your computer in reach of your own phone or tablet over Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a paired device and your own Tailscale login. - luxe join lets another program on the same machine join a running session over the RPC protocol. - An AGENTS.md in a subfolder reaches the model the first time it works there. - Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing. - A session is open in one Luxe at a time, web_search shares results across its phrasings, and a grep glob starting with ! excludes. The CHANGELOG has the full list.
This commit is contained in:
57
crates/luxe-remote/Cargo.toml
Normal file
57
crates/luxe-remote/Cargo.toml
Normal file
@@ -0,0 +1,57 @@
|
||||
[package]
|
||||
name = "luxe-remote"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "The bridge that lets your own phone or tablet drive Luxe sessions running on this machine"
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
# The app's checks run from the repository, with npm; nothing in them builds the crate
|
||||
exclude = ["app-tests/"]
|
||||
|
||||
# Allowed edges: depends on luxe-core only, like the TUI. It is a front end over the published
|
||||
# protocol: each phone connection joins a session through core's local endpoint, and nothing here
|
||||
# reaches a provider or a tool directly.
|
||||
#
|
||||
# Network I/O lives here. It answers on the loopback interface only: Tailscale Serve is what puts
|
||||
# it on the tailnet, and does the TLS for it. The one call it makes, Web Push, goes out through
|
||||
# reqwest and the workspace's rustls.
|
||||
|
||||
[dependencies]
|
||||
luxe-core = { path = "../luxe-core", version = "0.1.3" }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
# HTTP and WebSocket only: no TLS, no HTTP/2, no form or query parsing until something needs it.
|
||||
axum = { version = "0.8", default-features = false, features = ["http1", "ws", "json", "tokio"] }
|
||||
# Pairing: invitations and device credentials are random, and stored only as digests. The same
|
||||
# versions core's OAuth loopback uses, so nothing new is linked.
|
||||
getrandom = "0.4"
|
||||
sha2 = "0.11"
|
||||
base64 = { workspace = true }
|
||||
base16ct = { version = "1", features = ["alloc"] }
|
||||
# Web Push: the P-256, HKDF and AES-GCM it needs, from the copy rustls already links
|
||||
ring = "0.17"
|
||||
# Web Push's one outbound call, to the push service a device subscribed through
|
||||
reqwest = { workspace = true }
|
||||
# The phone app, `app/`, in the binary. A debug build reads the folder from disk instead, so
|
||||
# editing the app takes a reload, not a rebuild.
|
||||
rust-embed = { version = "8.13", default-features = false }
|
||||
|
||||
# Windows always embeds the app. A debug build's disk lookup compares against the folder's path as
|
||||
# canonicalized at build time, so a binary built on Linux and run under wine finds no file.
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
rust-embed = { version = "8.13", default-features = false, features = ["debug-embed"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
# A paused clock, for the waits notifications are held for
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
# The version axum's `ws` already links, so the tests add no second copy
|
||||
tokio-tungstenite = "0.29"
|
||||
futures = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
113
crates/luxe-remote/app-tests/commands.test.mjs
Normal file
113
crates/luxe-remote/app-tests/commands.test.mjs
Normal file
@@ -0,0 +1,113 @@
|
||||
// The slash commands the phone carries out, and the frames they send.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { commandAction, matchCommands, runCommand } from "../app/commands.js";
|
||||
|
||||
const names = (commands) => commands.map((command) => command.name);
|
||||
|
||||
// The break this catches: the picker missing at the bare slash, which is where you'd browse
|
||||
test("a bare slash offers every command", () => {
|
||||
assert.deepEqual(names(matchCommands("/")), ["compact", "cost", "dock", "mode", "model", "thinking"]);
|
||||
});
|
||||
|
||||
// The break this catches: names matched anywhere but their start, or with case counted
|
||||
test("what's typed narrows by the start of the name", () => {
|
||||
assert.deepEqual(names(matchCommands("/mo")), ["mode", "model"]);
|
||||
assert.deepEqual(names(matchCommands("/MOD")), ["mode", "model"]);
|
||||
assert.deepEqual(names(matchCommands("/st")), []);
|
||||
});
|
||||
|
||||
// The break this catches: the picker staying up over the words a command takes, or over a
|
||||
// message that happens to hold a slash
|
||||
test("nothing is offered once there's a space, or no slash first", () => {
|
||||
assert.deepEqual(matchCommands("/compact the API"), []);
|
||||
assert.deepEqual(matchCommands("see a/b"), []);
|
||||
});
|
||||
|
||||
// The break this catches: the focus dropped, so the summary keeps what it likes
|
||||
test("compact sends its focus", () => {
|
||||
assert.deepEqual(commandAction("/compact the API decisions", "build"), {
|
||||
frame: { kind: "compact_now", content: { focus: "the API decisions" } },
|
||||
});
|
||||
});
|
||||
|
||||
// The break this catches: an empty focus sent, which the summary would be told to keep
|
||||
test("compact alone sends no focus", () => {
|
||||
assert.deepEqual(commandAction("/compact", "build"), { frame: { kind: "compact_now" } });
|
||||
});
|
||||
|
||||
// The break this catches: a bare `/mode` sent as a mode named nothing, rather than the next one
|
||||
test("mode alone moves to the next mode", () => {
|
||||
assert.deepEqual(commandAction("/mode", "build"), { frame: { kind: "set_mode", content: "plan" } });
|
||||
});
|
||||
|
||||
// The break this catches: a named mode ignored for the next one, or any word sent as a mode
|
||||
test("mode takes plan or build, and anything else goes to the agent", () => {
|
||||
assert.deepEqual(commandAction("/mode build", "build"), { frame: { kind: "set_mode", content: "build" } });
|
||||
assert.equal(commandAction("/mode fast", "build"), null);
|
||||
});
|
||||
|
||||
// The break this catches: the pickers' commands sent to the agent as a message
|
||||
test("model, thinking and cost open the details", () => {
|
||||
for (const name of ["model", "thinking", "cost"]) assert.deepEqual(commandAction(`/${name}`, "build"), { details: true });
|
||||
});
|
||||
|
||||
// The break this catches: a bare `/dock` doing nothing, where the TUI's toggles
|
||||
test("dock alone toggles", () => {
|
||||
assert.deepEqual(commandAction("/dock", "build"), { dock: "toggle" });
|
||||
});
|
||||
|
||||
// The break this catches: one of the TUI's `/dock` verbs dropped, or any word taken for one
|
||||
test("dock takes the TUI's verbs, and anything else goes to the agent", () => {
|
||||
for (const verb of ["show", "hide", "auto", "left", "right"]) assert.deepEqual(commandAction(`/dock ${verb}`, "build"), { dock: verb });
|
||||
assert.deepEqual(commandAction("/dock Left", "build"), { dock: "left" });
|
||||
assert.equal(commandAction("/dock is in the way", "build"), null);
|
||||
});
|
||||
|
||||
/** Hooks that record what a command did. */
|
||||
function recorded() {
|
||||
/** @type {unknown[]} */
|
||||
const did = [];
|
||||
const hooks = {
|
||||
send: (/** @type {unknown} */ frame) => (did.push(frame), true),
|
||||
details: () => void did.push("details"),
|
||||
dock: (/** @type {string} */ verb) => void did.push(`dock ${verb}`),
|
||||
};
|
||||
return { did, hooks };
|
||||
}
|
||||
|
||||
// The break this catches: a command routed to the wrong place, the sheet's commands sent to the
|
||||
// session or the dock's left undone, or a message run as a command
|
||||
test("each command goes where it's carried out", () => {
|
||||
const { did, hooks } = recorded();
|
||||
assert.equal(runCommand({ details: true }, hooks), true);
|
||||
assert.equal(runCommand({ dock: "left" }, hooks), true);
|
||||
assert.equal(runCommand({ frame: { kind: "compact_now" } }, hooks), true);
|
||||
assert.equal(runCommand(null, hooks), null);
|
||||
assert.deepEqual(did, ["details", "dock left", { kind: "compact_now" }]);
|
||||
});
|
||||
|
||||
// The break this catches: a frame that couldn't go out reported as sent, so the box clears and
|
||||
// the command is lost
|
||||
test("a command frame that couldn't be sent says so", () => {
|
||||
const hooks = { ...recorded().hooks, send: () => false };
|
||||
assert.equal(runCommand({ frame: { kind: "compact_now" } }, hooks), false);
|
||||
});
|
||||
|
||||
// The break this catches: a command the keyboard capitalized sent to the agent as a message
|
||||
test("a command counts whatever its case", () => {
|
||||
assert.deepEqual(commandAction("/Model", "build"), { details: true });
|
||||
});
|
||||
|
||||
// The break this catches: a known command given words it doesn't take swallowed, so the message
|
||||
// never reaches the agent
|
||||
test("a command given words it doesn't take is a message", () => {
|
||||
assert.equal(commandAction("/model is slow today", "build"), null);
|
||||
});
|
||||
|
||||
// The break this catches: a slash that isn't one of the phone's commands kept from the agent
|
||||
test("anything else that starts with a slash is a message", () => {
|
||||
assert.equal(commandAction("/review the diff", "build"), null);
|
||||
assert.equal(commandAction("not /compact", "build"), null);
|
||||
});
|
||||
161
crates/luxe-remote/app-tests/comments.test.mjs
Normal file
161
crates/luxe-remote/app-tests/comments.test.mjs
Normal file
@@ -0,0 +1,161 @@
|
||||
// @ts-check
|
||||
// Comments from the phone: where one goes, the edits the buttons send, and the session they answer.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { actEdit, anchorFor, anchorWords, commentEdit, labelOf, unsent } from "../app/comments.js";
|
||||
import { composedEdit, tapCard } from "../app/comments-view.js";
|
||||
import { applyReview, chapterPiece, createReview } from "../app/review.js";
|
||||
|
||||
const line = (/** @type {number | null} */ n) => ({ new_line: n });
|
||||
/** `src/a.rs` with two hunks (lines 1–3, then 10–11), and a chapter naming both. */
|
||||
const REVIEW = {
|
||||
id: "review:1",
|
||||
chapters: [{ id: "chapter:1", items: [{ kind: "hunk", id: "hunk:1" }, { kind: "hunk", id: "hunk:2" }] }],
|
||||
files: [{ id: "file:a", new_path: "src/a.rs", hunks: [
|
||||
{ id: "hunk:1", lines: [line(1), line(2), line(null), line(3)] },
|
||||
{ id: "hunk:2", lines: [line(10), line(11)] },
|
||||
] }],
|
||||
};
|
||||
const pick = (/** @type {number} */ first, last = first, path = "src/a.rs") => ({ path, first, last });
|
||||
|
||||
// The break this catches: a one-line pick anchored anywhere but its line (the comment lands on the
|
||||
// wrong code), or on the old side, which a pick can't name
|
||||
test("one picked line is a line comment on the new side", () => {
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(2)), { kind: "line", file_id: "file:a", hunk_id: "hunk:1", side: "new", line: 2 });
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(11)).hunk_id, "hunk:2");
|
||||
});
|
||||
|
||||
// The break this catches: a run inside one hunk anchored to its first line only, or a run across
|
||||
// hunks pinned to one of them
|
||||
test("a run is its hunk's comment, and a wider one the chapter's", () => {
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(1, 3)), { kind: "hunk", file_id: "file:a", hunk_id: "hunk:1" });
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(2, 10)), { kind: "chapter", chapter_id: "chapter:1" });
|
||||
});
|
||||
|
||||
// The break this catches: a comment with no pick, or on a line the review doesn't hold, sent with
|
||||
// an anchor the desk refuses
|
||||
test("no pick, or a line the review doesn't hold, comments on the chapter", () => {
|
||||
const chapter = { kind: "chapter", chapter_id: "chapter:1" };
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", null), chapter);
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(2, 2, "src/b.rs")), chapter);
|
||||
assert.deepEqual(anchorFor(REVIEW, "chapter:1", pick(7)), chapter);
|
||||
});
|
||||
|
||||
// The break this catches: the composer saying "line 12" over a comment going on the chapter
|
||||
test("the composer says where the comment goes", () => {
|
||||
assert.equal(anchorWords({ kind: "line", line: 12 }, pick(12)), "Comment on line 12");
|
||||
assert.equal(anchorWords({ kind: "hunk" }, pick(1, 3)), "Comment on lines 1–3");
|
||||
assert.equal(anchorWords({ kind: "chapter" }, null), "Comment on this chapter");
|
||||
});
|
||||
|
||||
// The break this catches: a question sent as an issue (the agent fixes instead of answering), or
|
||||
// Save sending what was meant to wait
|
||||
test("a comment carries its kind and whether it goes now", () => {
|
||||
const anchor = { kind: "chapter", chapter_id: "chapter:1" };
|
||||
assert.deepEqual(commentEdit(anchor, "Why?", true, false), { edit: "comment", anchor, body: "Why?", severity: "question", send: false });
|
||||
assert.equal(commentEdit(anchor, "Fix it", false, true).severity, "issue");
|
||||
assert.equal(commentEdit(anchor, "Fix it", false, true).send, true);
|
||||
});
|
||||
|
||||
// The break this catches: a card's button sending another edit than it says, or a reply left
|
||||
// unsent (the TUI's go at once)
|
||||
test("each card button sends its own edit", () => {
|
||||
assert.deepEqual(actEdit("send", "f:1"), { edit: "send", finding_ids: ["f:1"] });
|
||||
assert.deepEqual(actEdit("delete", "f:1"), { edit: "delete_comment", finding_id: "f:1" });
|
||||
assert.deepEqual(actEdit("resolve", "f:1"), { edit: "resolve", finding_id: "f:1" });
|
||||
assert.deepEqual(actEdit("reopen", "f:1"), { edit: "reopen", finding_id: "f:1" });
|
||||
assert.deepEqual(actEdit("reply", "f:1", "Thanks"), { edit: "reply", finding_id: "f:1", body: "Thanks", send: true });
|
||||
assert.equal(actEdit("explode", "f:1"), null);
|
||||
});
|
||||
|
||||
// The break this catches: Send all re-sending sent comments, or posting one already on GitHub
|
||||
test("only drafts not on GitHub are unsent", () => {
|
||||
const session = { findings: [
|
||||
{ id: "f:1", state: "draft", label: "R1" }, { id: "f:2", state: "open", label: "R2" },
|
||||
{ id: "f:3", state: "draft", posted: { url: "x" }, label: "R3" },
|
||||
] };
|
||||
assert.deepEqual(unsent(session), ["f:1"]);
|
||||
assert.deepEqual(unsent(null), []);
|
||||
assert.equal(labelOf(session, "f:2"), "R2");
|
||||
});
|
||||
|
||||
/** A tap on a card's `act` button, and what it did. */
|
||||
function tapAct(/** @type {string | null} */ act) {
|
||||
const edits = /** @type {any[]} */ ([]);
|
||||
const composed = /** @type {any[]} */ ([]);
|
||||
const card = { getAttribute: () => "f:1" };
|
||||
const button = act && { getAttribute: () => act, closest: () => card };
|
||||
const event = /** @type {any} */ ({ target: { closest: () => button } });
|
||||
const review = { shown: { value: { session: { findings: [{ id: "f:1", label: "R1" }] } } }, edit: (/** @type {any} */ _send, /** @type {any} */ edit) => edits.push(edit) };
|
||||
tapCard(event, /** @type {any} */ ({ review, send: () => true }), (composing) => composed.push(composing));
|
||||
return { edits, composed };
|
||||
}
|
||||
|
||||
// The break this catches: Reply sending an empty reply instead of opening the composer, or a tap
|
||||
// between buttons sending something
|
||||
test("Reply opens the composer and other buttons send", () => {
|
||||
assert.deepEqual(tapAct("reply"), { edits: [], composed: [{ heading: "Reply to R1", reply: "f:1" }] });
|
||||
assert.deepEqual(tapAct("resolve").edits, [{ edit: "resolve", finding_id: "f:1" }]);
|
||||
assert.deepEqual(tapAct(null), { edits: [], composed: [] });
|
||||
});
|
||||
|
||||
// The break this catches: the composer's words sent as a new comment when they reply to one
|
||||
test("the composer replies or comments as it was opened", () => {
|
||||
assert.equal(composedEdit({ heading: "", reply: "f:1" }, "Yes", false, false).edit, "reply");
|
||||
assert.equal(composedEdit({ heading: "", anchor: { kind: "review" } }, "No", true, true).severity, "question");
|
||||
});
|
||||
|
||||
/** A review tab showing REVIEW, and everything it sent. */
|
||||
function shownTab() {
|
||||
const sent = /** @type {any[]} */ ([]);
|
||||
const state = createReview();
|
||||
const send = (/** @type {any} */ frame) => sent.push(frame) > 0;
|
||||
state.ask(send);
|
||||
state.apply({ kind: "open_review_shown", content: { request_id: sent[0].content.request_id, review: REVIEW, session: { id: "review:1", findings: [] } } });
|
||||
return { state, sent, send };
|
||||
}
|
||||
|
||||
// The break this catches: comments made in the TUI, or the desk's answer to the phone's own edit,
|
||||
// not reaching the phone, or another review's session taken for this one
|
||||
test("a saved session for the open review is the one shown", () => {
|
||||
const { state } = shownTab();
|
||||
const session = { id: "review:1", findings: [{ id: "f:1" }], progress: { walked_chapter_ids: ["chapter:1"] } };
|
||||
state.apply({ kind: "review_session_saved", content: { request_id: "elsewhere", session } });
|
||||
assert.deepEqual([state.shown.value.session, state.shown.value.walked], [session, ["chapter:1"]]);
|
||||
state.apply({ kind: "review_session_saved", content: { request_id: "x", session: { id: "review:9", findings: [] } } });
|
||||
assert.equal(state.shown.value.session, session);
|
||||
});
|
||||
|
||||
// The break this catches: an edit sent without the open review's id, a refusal of it unsaid, or
|
||||
// another client's refusal shown as this one's
|
||||
test("an edit names the open review and its refusal is said", () => {
|
||||
const { state, sent, send } = shownTab();
|
||||
state.edit(send, { edit: "resolve", finding_id: "f:1" });
|
||||
const edit = sent[sent.length - 1];
|
||||
assert.deepEqual([edit.kind, edit.content.review_id, edit.content.edit], ["edit_review", "review:1", "resolve"]);
|
||||
state.apply({ kind: "review_session_save_failed", content: { request_id: "elsewhere", message: "no" } });
|
||||
assert.equal(state.shown.value.problem, undefined);
|
||||
state.apply({ kind: "review_session_save_failed", content: { request_id: edit.content.request_id, message: "That comment was sent already." } });
|
||||
assert.equal(state.shown.value.problem, "That comment was sent already.");
|
||||
});
|
||||
|
||||
// The break this catches: an edit that couldn't be sent read as sent, or an edit with no review
|
||||
// open sent anyway
|
||||
test("an edit that can't go says so, and none goes without a review", () => {
|
||||
const { state } = shownTab();
|
||||
state.edit(() => false, { edit: "resolve", finding_id: "f:1" });
|
||||
assert.match(state.shown.value.problem ?? "", /Connection lost/);
|
||||
const none = createReview();
|
||||
const sent = /** @type {any[]} */ ([]);
|
||||
none.edit((frame) => sent.push(frame) > 0, { edit: "resolve", finding_id: "f:1" });
|
||||
assert.equal(sent.length, 0);
|
||||
});
|
||||
|
||||
// The break this catches: a chapter drawn without the session's comments, so none ever show
|
||||
test("a chapter's piece carries the session's comments", () => {
|
||||
const findings = [{ id: "f:1" }];
|
||||
const piece = chapterPiece(/** @type {any} */ ({ review: REVIEW, reading: [], walked: [], session: { findings } }), "chapter:1");
|
||||
assert.equal(piece.findings, findings);
|
||||
assert.deepEqual(chapterPiece(/** @type {any} */ ({ review: REVIEW, reading: [], walked: [] }), "chapter:1").findings, []);
|
||||
assert.deepEqual(applyReview(/** @type {any} */ ({ review: null }), { kind: "review_session_saved", content: { session: { id: "review:1" } } }, { id: "", load: "" }).next, { review: null });
|
||||
});
|
||||
34
crates/luxe-remote/app-tests/composer.test.mjs
Normal file
34
crates/luxe-remote/app-tests/composer.test.mjs
Normal file
@@ -0,0 +1,34 @@
|
||||
// What the composer says while a turn runs, since its buttons are icons.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { sendLabel, steeringLine } from "../app/composer.js";
|
||||
|
||||
// The break this catches: a line shown between turns, which says sending steers when it starts one
|
||||
test("idle, with nothing waiting, there's no line", () => {
|
||||
assert.equal(steeringLine(false, 0, false), "");
|
||||
});
|
||||
|
||||
// The break this catches: the running turn left unsaid, so the icon gives no hint a message steers
|
||||
test("while a turn runs, the line says sending steers it", () => {
|
||||
assert.equal(steeringLine(true, 0, false), "Send steers the turn");
|
||||
});
|
||||
|
||||
// The break this catches: a message with a photo promised to steer, when it waits for the turn
|
||||
test("with a photo attached, the line says it waits for the turn", () => {
|
||||
assert.equal(steeringLine(true, 0, true), "Photos wait for the turn");
|
||||
});
|
||||
|
||||
// The break this catches: waiting steering hidden behind the running-turn hint, or once the turn
|
||||
// ends, though the engine holds it for the next one and it can still be withdrawn
|
||||
test("steering that waits is counted, running or not", () => {
|
||||
assert.equal(steeringLine(true, 1, false), "1 message waiting to steer");
|
||||
assert.equal(steeringLine(false, 3, false), "3 messages waiting to steer");
|
||||
});
|
||||
|
||||
// The break this catches: the send icon's spoken name left at Send while it steers or queues
|
||||
test("the send button's name follows what it does", () => {
|
||||
assert.equal(sendLabel(false, true), "Send");
|
||||
assert.equal(sendLabel(true, false), "Steer");
|
||||
assert.equal(sendLabel(true, true), "Queue");
|
||||
});
|
||||
59
crates/luxe-remote/app-tests/connection.test.mjs
Normal file
59
crates/luxe-remote/app-tests/connection.test.mjs
Normal file
@@ -0,0 +1,59 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
/** A WebSocket that only records: the test plays the browser's part. */
|
||||
class FakeSocket {
|
||||
static OPEN = 1;
|
||||
static made = [];
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.closedWith = null;
|
||||
FakeSocket.made.push(this);
|
||||
}
|
||||
close(code) {
|
||||
this.closedWith = code;
|
||||
}
|
||||
}
|
||||
|
||||
const page = /** @type {EventTarget & { visibilityState: string }} */ (Object.assign(new EventTarget(), { visibilityState: "visible" }));
|
||||
Object.assign(globalThis, { document: page, WebSocket: FakeSocket, location: { protocol: "http:", host: "bridge" } });
|
||||
const { connect } = await import("../app/connection.js");
|
||||
|
||||
function show(state) {
|
||||
page.visibilityState = state;
|
||||
page.dispatchEvent(new Event("visibilitychange"));
|
||||
}
|
||||
|
||||
function joined() {
|
||||
FakeSocket.made = [];
|
||||
const statuses = [];
|
||||
const link = connect("s-1", { onFrame: () => {}, onStatus: (status) => statuses.push(status) });
|
||||
return { link, statuses };
|
||||
}
|
||||
|
||||
// The break this catches: a socket held open while the app is hidden, so the bridge thinks you're
|
||||
// looking and never notifies you, or a hidden app's close taken for the session ending.
|
||||
test("the socket closes while the app is hidden and opens again on return", () => {
|
||||
const { link, statuses } = joined();
|
||||
const first = FakeSocket.made[0];
|
||||
first.onopen();
|
||||
show("hidden");
|
||||
assert.equal(first.closedWith, 1000);
|
||||
first.onclose?.({ code: 1000 });
|
||||
assert.ok(!statuses.includes("ended"), `${statuses}`);
|
||||
show("visible");
|
||||
assert.equal(FakeSocket.made.length, 2, "a new socket on return");
|
||||
assert.deepEqual(statuses, ["connecting", "live", "connecting"]);
|
||||
link.close();
|
||||
});
|
||||
|
||||
// The break this catches: a session opened while the app is out of sight (a retry coming due, or
|
||||
// a load in the background), holding a socket open with nobody looking.
|
||||
test("nothing opens while the app is hidden", () => {
|
||||
show("hidden");
|
||||
const { link } = joined();
|
||||
assert.equal(FakeSocket.made.length, 0);
|
||||
show("visible");
|
||||
assert.equal(FakeSocket.made.length, 1);
|
||||
link.close();
|
||||
});
|
||||
29
crates/luxe-remote/app-tests/details.test.mjs
Normal file
29
crates/luxe-remote/app-tests/details.test.mjs
Normal file
@@ -0,0 +1,29 @@
|
||||
// The details sheet's readings, from the markup the bridge renders for the status line.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { hasReadings } from "../app/details.js";
|
||||
|
||||
const MODEL = '<span class="seg seg-model">Scripted</span>';
|
||||
const THINKING = '<span class="seg seg-thinking"><span class="seg-glyph" aria-hidden="true">x</span> off</span>';
|
||||
|
||||
// The break this catches: a SESSION heading over nothing, when the line holds only the model and
|
||||
// thinking the sheet already has pickers for
|
||||
test("a line with only the model and thinking has no readings", () => {
|
||||
assert.equal(hasReadings(THINKING + MODEL), false);
|
||||
});
|
||||
|
||||
// The break this catches: the context reading missed, so a filling window goes unshown
|
||||
test("the context is a reading", () => {
|
||||
assert.equal(hasReadings(`<span class="seg seg-context tone-error">95%/200k</span>${MODEL}`), true);
|
||||
});
|
||||
|
||||
// The break this catches: the cost missed, which the phone's line leaves to the sheet alone
|
||||
test("the cost is a reading", () => {
|
||||
assert.equal(hasReadings(`<span class="seg seg-cost">$1.20</span>${MODEL}`), true);
|
||||
});
|
||||
|
||||
// The break this catches: nothing rendered yet read as something, or a crash before the first render
|
||||
test("nothing rendered has no readings", () => {
|
||||
assert.equal(hasReadings(null), false);
|
||||
});
|
||||
267
crates/luxe-remote/app-tests/e2e/flow.mjs
Normal file
267
crates/luxe-remote/app-tests/e2e/flow.mjs
Normal file
@@ -0,0 +1,267 @@
|
||||
// The app end to end in WebKit, Safari's engine: pair by pasting the invitation link, open the
|
||||
// session from the list, send a message, grant the write it asks for, and watch the mock model's
|
||||
// turn arrive as the TUI would show it: the rendered answer, the changed file in the dock, and its
|
||||
// diff.
|
||||
//
|
||||
// Needs a built `luxe` (`LUXE_BIN`, or target/debug/luxe) and Playwright's WebKit
|
||||
// (`npx playwright install webkit`). Run: npm run e2e
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { createRequire } from "node:module";
|
||||
import { basename } from "node:path";
|
||||
import { after, before, test } from "node:test";
|
||||
import { LOGIN, startHost } from "./host.mjs";
|
||||
import { WRITTEN, startMockProvider } from "./mock-provider.mjs";
|
||||
|
||||
const playwright = createRequire(import.meta.url)("playwright");
|
||||
|
||||
let model, host, browser, page;
|
||||
const troubles = [];
|
||||
|
||||
before(async () => {
|
||||
model = await startMockProvider();
|
||||
host = await startHost(model.port);
|
||||
browser = await playwright.webkit.launch();
|
||||
const context = await browser.newContext({
|
||||
...playwright.devices["iPad Pro 11 landscape"],
|
||||
extraHTTPHeaders: { "Tailscale-User-Login": LOGIN },
|
||||
});
|
||||
page = await context.newPage();
|
||||
page.on("pageerror", (error) => troubles.push(`page error: ${error.message}`));
|
||||
page.on("console", (message) => message.type() === "error" && troubles.push(`console: ${message.text()}`));
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await browser?.close();
|
||||
await host?.stop();
|
||||
await model?.close();
|
||||
});
|
||||
|
||||
// The break this catches: any link in the chain from invitation to diff (the unpaired app's
|
||||
// pairing field, pairing, the session list, the socket, the composer, the permission card,
|
||||
// rendering, the dock, the diff request) broken in Safari's engine
|
||||
test("a paired iPad drives a turn and reads its diff", async () => {
|
||||
await pair();
|
||||
await page.locator("a.session").click();
|
||||
await page.locator(".composer textarea").fill("Write the file, please.");
|
||||
await page.locator(".send").click();
|
||||
await page.locator(".prompt .choice.once").click();
|
||||
await page.locator(".item.reply strong", { hasText: WRITTEN.path }).waitFor();
|
||||
await page.locator(`button.change[data-path="${WRITTEN.path}"]`).click();
|
||||
const added = page.locator(".sheet .dl-addition code");
|
||||
assert.equal((await added.textContent())?.trim(), WRITTEN.content.trim());
|
||||
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
|
||||
});
|
||||
|
||||
// Pairs as an app on the home screen would: the unpaired app takes the pasted link to the
|
||||
// invitation page. Serve puts HTTPS in front of the bridge, so the credential is a Secure cookie,
|
||||
// and WebKit drops one that arrives over this test's plain HTTP; the test carries it over itself,
|
||||
// then opens the app as the page's redirect would.
|
||||
async function pair() {
|
||||
await page.goto(host.url);
|
||||
await page.locator(".pair-link input").fill(`https://desk.example.ts.net/pair#${host.invitation}`);
|
||||
await page.locator(".pair-link button").click();
|
||||
const answered = page.waitForResponse("**/api/pair");
|
||||
await page.locator("#pair button").click();
|
||||
const cookie = (await (await answered).headerValue("set-cookie"))?.split(";")[0] ?? "";
|
||||
// let the page's own redirect land and finish asking, or the visit below races it
|
||||
await page.waitForURL((url) => url.pathname === "/", { waitUntil: "networkidle" });
|
||||
const at = cookie.indexOf("=");
|
||||
await page.context().addCookies([{ name: cookie.slice(0, at), value: cookie.slice(at + 1), url: host.url }]);
|
||||
// the page's own redirect may have asked for the list before the cookie was carried over
|
||||
troubles.length = 0;
|
||||
await page.goto(host.url);
|
||||
}
|
||||
|
||||
// The break this catches: the turn reaching the model without the tool's result, so the answer
|
||||
// on screen came from somewhere other than the loop the app drove
|
||||
test("the model saw the message and the tool's result", () => {
|
||||
const turns = model.requests.filter((request) => request.tools?.length);
|
||||
assert.equal(turns.length, 2, "one request to act, one with the result");
|
||||
const sent = JSON.stringify(turns[0].messages);
|
||||
assert.ok(sent.includes("Write the file, please."), sent);
|
||||
assert.equal(turns[1].messages.at(-1).role, "tool");
|
||||
});
|
||||
|
||||
// The break this catches: the Files tab's chain (the header's button, `list_directory` and
|
||||
// `read_project_file` through the bridge, the file piece's rendering, Mention into the composer)
|
||||
// broken in Safari's engine
|
||||
test("the project panel lists the project, shows a file and mentions it", async () => {
|
||||
await page.keyboard.press("Escape");
|
||||
// The break this catches: the session's header naming its folder bare, without the branch it's on
|
||||
const header = page.locator("header.bar:has(.back) .title .project-name");
|
||||
await header.locator(".project-branch").waitFor();
|
||||
assert.match((await header.textContent()) ?? "", new RegExp(`${basename(host.project)}.*\\S+ \\*$`));
|
||||
await page.locator(".panel-button").click();
|
||||
const named = page.locator(".panel .bar .project-name");
|
||||
await named.waitFor();
|
||||
assert.ok((await named.textContent())?.includes(basename(host.project)), "the bar names the project");
|
||||
assert.ok(await named.locator(".project-mark").first().textContent(), "behind the tree's folder mark");
|
||||
// the project is a git repository the turn just wrote into, so its branch shows, starred
|
||||
assert.match((await named.locator(".project-branch").textContent()) ?? "", /\S+ \*$/);
|
||||
// the file the turn wrote wears its change, as it does in the TUI's tree
|
||||
await page.locator(`button.tree-row[data-file="${WRITTEN.path}"] .tree-name[class*="change-"]`).waitFor();
|
||||
await page.locator("button.tree-row", { hasText: "README.md" }).click();
|
||||
assert.equal((await page.locator(".peek .file .fl code").first().textContent())?.trim(), "# e2e");
|
||||
// Escape closes the file and leaves the tree, as the TUI's Escape leaves a peek
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".peek").waitFor({ state: "detached" });
|
||||
await page.locator("button.tree-row", { hasText: "README.md" }).click();
|
||||
await page.locator(".peek .mention").click();
|
||||
await page.waitForFunction(() => document.querySelector("textarea")?.value === "`README.md` ");
|
||||
assert.equal(await page.locator(".panel, .peek").count(), 0, "Mention leaves the composer in view");
|
||||
await page.locator(".panel-button").click();
|
||||
await page.locator("button.tree-row").first().waitFor();
|
||||
assert.equal(await page.locator(".peek").count(), 0, "the mentioned file isn't waiting in the panel");
|
||||
// straight away: Escape is armed as soon as the panel is on screen, not a frame later
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".panel").waitFor({ state: "detached", timeout: 2000 });
|
||||
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
|
||||
});
|
||||
|
||||
// The break this catches: the Review tab's chain (`show_open_review` through the engine to the
|
||||
// review desk, `load_guided_review` of the working changes, the guide and chapter pieces, and
|
||||
// `record_review_progress` kept in the session the next ask reads) broken in Safari's engine
|
||||
test("the review tab reviews the changes and keeps a chapter marked", async () => {
|
||||
await page.locator(".panel-button").click();
|
||||
await page.locator('button.tab:has-text("Review")').click();
|
||||
await page.locator('.panel button.retry:has-text("Review changes")').click();
|
||||
await page.locator(".rv-target", { hasText: "Working changes" }).waitFor();
|
||||
await page.locator(".rv-chapter .rv-title").first().click();
|
||||
await page.locator(".peek .rv-chapter-view .rv-file", { hasText: WRITTEN.path }).waitFor();
|
||||
await page.locator('.peek button.mention:has-text("Reviewed")').click();
|
||||
await page.locator('.peek button.mention[aria-pressed="true"]').waitFor();
|
||||
// Escape closes the chapter, then the panel, as it closes a file and then the panel
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".peek").waitFor({ state: "detached" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".panel").waitFor({ state: "detached", timeout: 2000 });
|
||||
await page.locator(".panel-button").click();
|
||||
await page.locator('button.tab:has-text("Review")').click();
|
||||
// asked afresh, the host's session says which chapter was walked
|
||||
await page.locator(".rv-chapter .rv-walked").first().waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
|
||||
});
|
||||
|
||||
/** Opens README.md from the Files tab, its lines drawn. */
|
||||
async function openReadme() {
|
||||
await page.locator(".panel").waitFor({ state: "detached" });
|
||||
await page.locator(".panel-button").click();
|
||||
await page.locator('button.tab:has-text("Files")').click();
|
||||
await page.locator("button.tree-row", { hasText: "README.md" }).click();
|
||||
await page.locator('.peek .fl[data-line="4"]').waitFor();
|
||||
}
|
||||
|
||||
/** Selects `words` inside line `line` of the open file, as a long press and drag would. */
|
||||
async function selectWithin(/** @type {number} */ line, /** @type {string} */ words) {
|
||||
await page.evaluate(([line, words]) => {
|
||||
const code = document.querySelector(`.peek .fl[data-line="${line}"] code`);
|
||||
const walker = document.createTreeWalker(/** @type {Node} */ (code), NodeFilter.SHOW_TEXT);
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
const at = node.textContent?.indexOf(String(words)) ?? -1;
|
||||
if (at < 0) continue;
|
||||
const range = document.createRange();
|
||||
range.setStart(node, at);
|
||||
range.setEnd(node, at + String(words).length);
|
||||
document.getSelection()?.removeAllRanges();
|
||||
document.getSelection()?.addRange(range);
|
||||
return;
|
||||
}
|
||||
}, [line, words]);
|
||||
}
|
||||
|
||||
// The break this catches: line picks lost between the host's markup and the composer (rows not
|
||||
// naming their lines, a tap on a number not picking, a second tap not stretching, picked rows not
|
||||
// marked), or a selection inside a line, the phone's own way, not offering Ask for that line, or
|
||||
// Ask writing other words than the TUI sends for the same lines
|
||||
test("lines picked by number, or selected in part, are asked about in the TUI's words", async () => {
|
||||
await openReadme();
|
||||
const number = (/** @type {number} */ line) => page.locator(`.peek .fl[data-line="${line}"] .ln`);
|
||||
await number(3).click();
|
||||
await page.locator(".line-ask button", { hasText: "Ask about line 3" }).waitFor();
|
||||
await number(4).click();
|
||||
await page.locator(".line-ask button", { hasText: "Ask about lines 3–4" }).waitFor();
|
||||
assert.equal(await page.locator(".peek .fl.picked").count(), 2, "the picked rows are marked");
|
||||
await page.locator(".line-ask button").click();
|
||||
await page.waitForFunction(() => document.querySelector("textarea")?.value.includes("`README.md` lines 3–4"));
|
||||
assert.equal(await page.locator(".panel, .peek").count(), 0, "Ask leaves the composer in view");
|
||||
await openReadme();
|
||||
await selectWithin(3, "4519");
|
||||
await page.locator(".line-ask button", { hasText: "Ask about line 3" }).click();
|
||||
await page.waitForFunction(() => document.querySelector("textarea")?.value.includes("`README.md` line 3"));
|
||||
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
|
||||
});
|
||||
|
||||
/** Writes a comment in the open composer, as a question or not, and saves it unsent. */
|
||||
async function saveComment(/** @type {string} */ words, question = false) {
|
||||
if (question) await page.locator(".rv-kinds button", { hasText: "Question" }).click();
|
||||
await page.locator(".rv-compose textarea").fill(words);
|
||||
await page.locator(".rv-compose button", { hasText: "Save" }).click();
|
||||
}
|
||||
|
||||
// The break this catches: comments lost between the phone and the review desk (a line pick not
|
||||
// anchoring to its line, the chapter comment not offered with nothing picked, the desk's saved
|
||||
// session not redrawn as cards, a card's Delete not reaching the desk, or the guide not counting
|
||||
// what's unsent)
|
||||
test("a review chapter takes comments on its lines and on itself, kept by the host", async () => {
|
||||
await page.locator(".panel").waitFor({ state: "detached" });
|
||||
await page.locator(".panel-button").click();
|
||||
await page.locator('button.tab:has-text("Review")').click();
|
||||
await page.locator(".rv-chapter .rv-title").first().click();
|
||||
await page.locator('.peek .dl[data-line="1"] .ln').first().click();
|
||||
await page.locator(".line-ask button", { hasText: /^Comment$/ }).click();
|
||||
await page.locator(".rv-compose", { hasText: "Comment on line 1" }).waitFor();
|
||||
await saveComment("Why this file?", true);
|
||||
const asked = page.locator(".peek .rv-finding", { hasText: "Why this file?" });
|
||||
await asked.locator(".rv-state", { hasText: "unsent" }).waitFor();
|
||||
assert.match((await asked.locator(".rv-finding-head").textContent()) ?? "", /question.*line 1/);
|
||||
await page.locator(".line-ask button", { hasText: "Comment on the chapter" }).click();
|
||||
await saveComment("Split this up.");
|
||||
await page.locator(".peek .rv-finding", { hasText: "Split this up." }).waitFor();
|
||||
await asked.locator('button[data-act="delete"]').click();
|
||||
await asked.waitFor({ state: "detached" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".peek").waitFor({ state: "detached" });
|
||||
await page.locator(".rv-unsent", { hasText: "1 unsent comment" }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
|
||||
});
|
||||
|
||||
/** Sends `command` from the composer, as typed. */
|
||||
async function runCommand(/** @type {string} */ command) {
|
||||
await page.locator(".composer textarea").fill(command);
|
||||
await page.locator(".send").click();
|
||||
}
|
||||
|
||||
/** The label of the panel tab showing. */
|
||||
const shownTab = () => page.locator('.panel button.tab[aria-selected="true"]').textContent();
|
||||
|
||||
// The break this catches: a phone keeping two header buttons, the panel's button not reaching the
|
||||
// dock, its tabs wrapping to a second row on the narrowest iPhone, a diff opened from the dock
|
||||
// drawn under the panel, Escape closing the panel with the diff, or `/dock` on a phone doing
|
||||
// nothing now the dock lives in the panel
|
||||
test("on a phone one header button opens the dock and the project", async () => {
|
||||
await page.locator(".panel").waitFor({ state: "detached" });
|
||||
await page.setViewportSize({ width: 375, height: 812 });
|
||||
// no dock button beside the panel's, once the app sees the narrow screen
|
||||
await page.locator(".dock-toggle").waitFor({ state: "detached", timeout: 2000 });
|
||||
await page.locator(".panel-button").click();
|
||||
assert.equal(await shownTab(), "Dock");
|
||||
const rows = await page.$$eval(".panel button.tab", (tabs) => new Set(tabs.map((tab) => tab.getBoundingClientRect().top)).size);
|
||||
assert.equal(rows, 1, "the tabs fit one row");
|
||||
await page.locator(`.panel button.change[data-path="${WRITTEN.path}"]`).click();
|
||||
await page.locator(".peek .dl-addition").waitFor();
|
||||
const onTop = await page.evaluate(() => document.elementFromPoint(innerWidth / 2, innerHeight / 2)?.closest(".peek") !== null);
|
||||
assert.ok(onTop, "the diff covers the panel");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".peek").waitFor({ state: "detached" });
|
||||
assert.equal(await page.locator(".panel").count(), 1, "the diff took the Escape, not the panel");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".panel").waitFor({ state: "detached", timeout: 2000 });
|
||||
await runCommand("/dock");
|
||||
assert.equal(await shownTab(), "Dock");
|
||||
await page.locator(".panel .close").click();
|
||||
await page.setViewportSize(playwright.devices["iPad Pro 11 landscape"].viewport);
|
||||
assert.deepEqual(troubles, [], "the page ran without errors or refusals");
|
||||
});
|
||||
117
crates/luxe-remote/app-tests/e2e/host.mjs
Normal file
117
crates/luxe-remote/app-tests/e2e/host.mjs
Normal file
@@ -0,0 +1,117 @@
|
||||
// A Luxe of the test's own: a session in a fresh git project, driven by the mock model, and a
|
||||
// bridge serving it, all under one temporary directory, so nothing touches the real config.
|
||||
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..");
|
||||
|
||||
/** The tailnet login the bridge lets in, sent as Tailscale Serve would send it. */
|
||||
export const LOGIN = "e2e@luxe.test";
|
||||
|
||||
/** The `luxe` to test: `LUXE_BIN`, or the debug build. */
|
||||
const LUXE = process.env.LUXE_BIN ?? join(REPO, "target/debug/luxe");
|
||||
|
||||
/** Starts a session and a bridge for the mock model on `modelPort`. */
|
||||
export async function startHost(modelPort) {
|
||||
const root = mkdtempSync(join(tmpdir(), "luxe-e2e-"));
|
||||
const env = isolatedEnv(root);
|
||||
const project = gitProject(root);
|
||||
writeConfig(env.LUXE_CONFIG_DIR, modelPort);
|
||||
const children = [];
|
||||
const host = { root, project, children, stop: () => stop(host) };
|
||||
host.sessionId = await startSession(env, project, children);
|
||||
host.invitation = invite(env);
|
||||
host.url = await startBridge(env, children);
|
||||
return host;
|
||||
}
|
||||
|
||||
function isolatedEnv(root) {
|
||||
const dirs = { LUXE_CONFIG_DIR: "config", LUXE_STATE_DIR: "state", LUXE_RUNTIME_DIR: "run", XDG_CACHE_HOME: "cache" };
|
||||
/** @type {NodeJS.ProcessEnv} */
|
||||
const env = { ...process.env, LUXE_MODELS_DEV_REFRESH: "0", HOME: join(root, "home") };
|
||||
for (const [name, dir] of Object.entries(dirs)) mkdirSync((env[name] = join(root, dir)), { recursive: true });
|
||||
return env;
|
||||
}
|
||||
|
||||
function gitProject(root) {
|
||||
const project = join(root, "project");
|
||||
mkdirSync(project);
|
||||
const git = (...args) => execFileSync("git", ["-c", "user.name=e2e", "-c", "user.email=e2e@luxe.test", ...args], { cwd: project });
|
||||
git("init", "-q");
|
||||
// a few lines, so a phone can pick a range of them and select part of one
|
||||
writeFileSync(join(project, "README.md"), "# e2e\n\nThe port is 4519.\nThe host is luxe.local.\n");
|
||||
git("add", ".");
|
||||
git("commit", "-qm", "start");
|
||||
return project;
|
||||
}
|
||||
|
||||
// The mock model, and a rule that stops its write for a permission the phone has to grant
|
||||
function writeConfig(configDir, port) {
|
||||
const models = {
|
||||
providers: { mock: { base_url: `http://127.0.0.1:${port}/v1`, api_key: "unused", api: "openai-completions" } },
|
||||
models: { "mock/scripted": { name: "Scripted", context_window: 32000, max_tokens: 4000 } },
|
||||
};
|
||||
writeFileSync(join(configDir, "models.json"), JSON.stringify(models));
|
||||
writeFileSync(join(configDir, "permissions.json"), JSON.stringify({ permission: { edit: "ask" } }));
|
||||
}
|
||||
|
||||
// `--rpc` keeps the session while its stdin is open, and its `ready` event names it. Its events
|
||||
// keep being read after that, so a full pipe never stalls it.
|
||||
function startSession(env, project, children) {
|
||||
const luxe = spawn(LUXE, ["--rpc", "--model", "mock/scripted"], { cwd: project, env, stdio: ["pipe", "pipe", "inherit"] });
|
||||
children.push(luxe);
|
||||
return new Promise((ready, failed) => {
|
||||
createInterface({ input: luxe.stdout }).on("line", (line) => {
|
||||
const event = JSON.parse(line);
|
||||
if (event.kind === "ready") ready(event.content.session_id);
|
||||
});
|
||||
luxe.once("exit", (code) => failed(new Error(`luxe --rpc exited (${code}) before it was ready`)));
|
||||
});
|
||||
}
|
||||
|
||||
// The token is the link's fragment, or printed on its own where Tailscale can't name the machine
|
||||
function invite(env) {
|
||||
const out = execFileSync(LUXE, ["remote", "pair"], { env, encoding: "utf8" });
|
||||
const token = /#([\w-]+)/.exec(out)?.[1];
|
||||
if (!token) throw new Error(`no invitation in: ${out}`);
|
||||
return token;
|
||||
}
|
||||
|
||||
async function startBridge(env, children) {
|
||||
const port = await freePort();
|
||||
const bridge = spawn(LUXE, ["remote", "--port", String(port), "--allow", LOGIN], { env, stdio: "inherit" });
|
||||
children.push(bridge);
|
||||
const url = `http://127.0.0.1:${port}`;
|
||||
await until(() => fetch(url).then(() => true, () => false), "the bridge to listen");
|
||||
return url;
|
||||
}
|
||||
|
||||
function freePort() {
|
||||
return new Promise((done) => {
|
||||
const probe = createServer().listen(0, "127.0.0.1", () => {
|
||||
const { port } = /** @type {import("node:net").AddressInfo} */ (probe.address());
|
||||
probe.close(() => done(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Polls `check` until it's true, for at most ten seconds. */
|
||||
export async function until(check, what) {
|
||||
for (let tries = 0; tries < 100; tries += 1) {
|
||||
if (await check()) return;
|
||||
await new Promise((done) => setTimeout(done, 100));
|
||||
}
|
||||
throw new Error(`timed out waiting for ${what}`);
|
||||
}
|
||||
|
||||
async function stop(host) {
|
||||
for (const child of host.children) child.kill();
|
||||
await Promise.all(host.children.map((child) => child.exitCode ?? new Promise((done) => child.once("exit", done))));
|
||||
rmSync(host.root, { recursive: true, force: true });
|
||||
}
|
||||
62
crates/luxe-remote/app-tests/e2e/mock-provider.mjs
Normal file
62
crates/luxe-remote/app-tests/e2e/mock-provider.mjs
Normal file
@@ -0,0 +1,62 @@
|
||||
// A model that follows a script, served the way an OpenAI-compatible endpoint streams: asked to
|
||||
// act, it calls `write`; given the tool's result, it says what it did. A request with no tools
|
||||
// (a session title, say) gets a word back. Every request is kept for the test to look at.
|
||||
|
||||
import { createServer } from "node:http";
|
||||
|
||||
/** The file the scripted model writes, and what it writes in it. */
|
||||
export const WRITTEN = { path: "hello.txt", content: "hello from the mock\n" };
|
||||
|
||||
/** Starts the server on a free port. */
|
||||
export async function startMockProvider() {
|
||||
const requests = [];
|
||||
const server = createServer((request, response) => answer(request, response, requests));
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(undefined)));
|
||||
const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
|
||||
return { port, requests, close: () => new Promise((resolve) => server.close(resolve)) };
|
||||
}
|
||||
|
||||
async function answer(request, response, requests) {
|
||||
if (request.method !== "POST" || !request.url?.endsWith("/chat/completions")) {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
const body = JSON.parse(await readBody(request));
|
||||
requests.push(body);
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
for (const chunk of reply(body)) response.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||
response.end("data: [DONE]\n\n");
|
||||
}
|
||||
|
||||
async function readBody(request) {
|
||||
let text = "";
|
||||
for await (const part of request) text += part;
|
||||
return text;
|
||||
}
|
||||
|
||||
function reply(body) {
|
||||
if (!body.tools?.length) return words("Mock");
|
||||
if (body.messages.at(-1)?.role === "tool") return words(`Wrote **${WRITTEN.path}**.`);
|
||||
return writeCall();
|
||||
}
|
||||
|
||||
const chunk = (delta, finish = null) => ({
|
||||
id: "mock", object: "chat.completion.chunk", created: 0, model: "scripted",
|
||||
choices: [{ index: 0, delta, finish_reason: finish }],
|
||||
});
|
||||
|
||||
const usage = { id: "mock", object: "chat.completion.chunk", created: 0, model: "scripted", choices: [],
|
||||
usage: { prompt_tokens: 1200, completion_tokens: 20, total_tokens: 1220 } };
|
||||
|
||||
function words(text) {
|
||||
const half = Math.ceil(text.length / 2);
|
||||
return [chunk({ role: "assistant", content: text.slice(0, half) }), chunk({ content: text.slice(half) }),
|
||||
chunk({}, "stop"), usage];
|
||||
}
|
||||
|
||||
function writeCall() {
|
||||
const call = { index: 0, id: "call_write", type: "function", function: { name: "write", arguments: "" } };
|
||||
const args = { index: 0, function: { arguments: JSON.stringify(WRITTEN) } };
|
||||
return [chunk({ role: "assistant", content: null, tool_calls: [call] }), chunk({ tool_calls: [args] }),
|
||||
chunk({}, "tool_calls"), usage];
|
||||
}
|
||||
181
crates/luxe-remote/app-tests/files.test.mjs
Normal file
181
crates/luxe-remote/app-tests/files.test.mjs
Normal file
@@ -0,0 +1,181 @@
|
||||
// The Files tab: the tree's rows and taps, reading a file, its answer, and mentioning it.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { applyRead, childPath, createFiles, entriesNote, fileMention, toggled, treeRows, withMention } from "../app/files.js";
|
||||
import { createGithub } from "../app/github.js";
|
||||
import { createReview } from "../app/review.js";
|
||||
import { tapRow } from "../app/files-view.js";
|
||||
|
||||
/** @import { OpenFile } from "../app/files.js" */
|
||||
|
||||
/** @type {OpenFile} */
|
||||
const ASKING = { path: "src/a.rs", requestId: "file:1", state: "asking" };
|
||||
/** A `project_file_read` frame's file, copied from `luxe --rpc`. */
|
||||
const FILE = { path: "a.rs", text: "fn main() {}\n", bytes: 13, truncated: false, binary: false };
|
||||
|
||||
// The break this catches: the question in a shape `read_project_file` doesn't take, or its id
|
||||
// counted rather than random, so two phones in one session open each other's files
|
||||
test("reading a file asks read_project_file with an id of its own", () => {
|
||||
/** @type {any[]} */
|
||||
const frames = [];
|
||||
const files = createFiles();
|
||||
files.read("src/a.rs", (frame) => (frames.push(frame), true));
|
||||
files.read("src/a.rs", (frame) => (frames.push(frame), true));
|
||||
assert.deepEqual(frames[0], { kind: "read_project_file", content: { request_id: frames[0].content.request_id, path: "src/a.rs" } });
|
||||
assert.match(frames[0].content.request_id, /^file:/);
|
||||
assert.notEqual(frames[0].content.request_id, frames[1].content.request_id);
|
||||
assert.equal(files.open.value?.state, "asking");
|
||||
});
|
||||
|
||||
// The break this catches: a read that never left shown as loading forever
|
||||
test("a read that couldn't be sent shows as lost", () => {
|
||||
const files = createFiles();
|
||||
files.read("a.rs", () => false);
|
||||
assert.equal(files.open.value?.state, "lost");
|
||||
});
|
||||
|
||||
// The break this catches: the answer's file read from the wrong field
|
||||
test("the answer to the open file shows it", () => {
|
||||
const read = applyRead(ASKING, { kind: "project_file_read", content: { request_id: "file:1", file: FILE } });
|
||||
assert.deepEqual(read, { ...ASKING, state: "read", file: FILE });
|
||||
});
|
||||
|
||||
// The break this catches: a failure left loading, or its reason dropped
|
||||
test("a failed read says why", () => {
|
||||
const failed = applyRead(ASKING, { kind: "project_file_read_failed", content: { request_id: "file:1", path: "src/a.rs", error: "not_found" } });
|
||||
assert.deepEqual(failed, { ...ASKING, state: "failed", error: "not_found" });
|
||||
});
|
||||
|
||||
// The break this catches: another phone's answer, or one for a file since closed, shown here
|
||||
test("an answer to another question changes nothing", () => {
|
||||
const frame = { kind: "project_file_read", content: { request_id: "file:2", file: FILE } };
|
||||
assert.equal(applyRead(ASKING, frame), ASKING);
|
||||
assert.equal(applyRead(null, frame), null);
|
||||
});
|
||||
|
||||
// The break this catches: a read asked for before the connection dropped left loading forever
|
||||
test("a new connection marks a read still on its way as lost", () => {
|
||||
assert.equal(applyRead(ASKING, { kind: "ready", content: {} })?.state, "lost");
|
||||
});
|
||||
|
||||
// The break this catches: a file already shown thrown back to lost by a reconnect
|
||||
test("a new connection leaves a file already read alone", () => {
|
||||
/** @type {OpenFile} */
|
||||
const read = { ...ASKING, state: "read", file: FILE };
|
||||
assert.equal(applyRead(read, { kind: "ready", content: {} }), read);
|
||||
});
|
||||
|
||||
// The break this catches: a root entry asked for as `/name`, which isn't a project path
|
||||
test("a path inside the root has no leading slash", () => {
|
||||
assert.equal(childPath("", "src"), "src");
|
||||
assert.equal(childPath("src/app", "a.rs"), "src/app/a.rs");
|
||||
});
|
||||
|
||||
/** Listings as `directory_listed` leaves them: the root, `src` and `src/app`. */
|
||||
const FOLDERS = /** @type {Record<string, import("../app/mentions.js").Listing>} */ ({
|
||||
"": { state: "listed", entries: [{ name: "src", kind: "directory" }, { name: "README.md", kind: "file" }] },
|
||||
src: { state: "listed", entries: [{ name: "app", kind: "directory" }, { name: "lib.rs", kind: "file" }] },
|
||||
"src/app": { state: "listed", entries: [{ name: "a.rs", kind: "file" }] },
|
||||
});
|
||||
|
||||
// The break this catches: an open folder's entries left out, placed after its siblings rather than
|
||||
// under it, at the wrong depth, or by name alone rather than their whole path
|
||||
test("an open folder's entries sit under it, a level in", () => {
|
||||
assert.deepEqual(treeRows(FOLDERS, new Set(["src"])), [
|
||||
{ kind: "folder", path: "src", name: "src", depth: 0, open: true },
|
||||
{ kind: "folder", path: "src/app", name: "app", depth: 1, open: false },
|
||||
{ kind: "file", path: "src/lib.rs", name: "lib.rs", depth: 1 },
|
||||
{ kind: "file", path: "README.md", name: "README.md", depth: 0 },
|
||||
]);
|
||||
});
|
||||
|
||||
// The break this catches: a folder open inside a closed one shown anyway, which the TUI hides until
|
||||
// the closed one opens again
|
||||
test("a closed folder hides what's open inside it", () => {
|
||||
const rows = treeRows(FOLDERS, new Set(["src/app"]));
|
||||
assert.deepEqual(rows.map((row) => row.kind === "note" ? row.text : row.path), ["src", "README.md"]);
|
||||
});
|
||||
|
||||
// The break this catches: an open folder not listed yet shown as empty, or its note at the
|
||||
// folder's own depth rather than where its entries will be
|
||||
test("an open folder still being listed says so where its entries will be", () => {
|
||||
const rows = treeRows({ "": FOLDERS[""] }, new Set(["src"]));
|
||||
assert.deepEqual(rows[1], { kind: "note", depth: 1, text: "Loading…" });
|
||||
assert.deepEqual(treeRows({}, new Set()), [{ kind: "note", depth: 0, text: "Loading…" }]);
|
||||
});
|
||||
|
||||
// The break this catches: a tap that only ever opens, so a folder can't be closed again, or one
|
||||
// that closes every other folder too
|
||||
test("toggling opens a closed folder and closes an open one", () => {
|
||||
const opened = toggled(new Set(["docs"]), "src");
|
||||
assert.deepEqual([...opened], ["docs", "src"]);
|
||||
assert.deepEqual([...toggled(opened, "src")], ["docs"]);
|
||||
});
|
||||
|
||||
/**
|
||||
* A tap on a tree row with `dataset`, and what it asked for.
|
||||
* @param {Record<string, string>} dataset @param {Iterable<string>} [unfolded]
|
||||
*/
|
||||
function tap(dataset, unfolded = []) {
|
||||
/** @type {any[]} */
|
||||
const asked = [];
|
||||
const files = createFiles();
|
||||
files.unfolded.value = new Set(unfolded);
|
||||
const listings = /** @type {any} */ ({ ask: (/** @type {any[]} */ ...args) => asked.push(args) });
|
||||
const event = /** @type {any} */ ({ target: { closest: () => ({ dataset }) } });
|
||||
const send = () => true;
|
||||
const github = createGithub();
|
||||
github.open.value = /** @type {any} */ ({ subject: { number: 1 } });
|
||||
const review = createReview();
|
||||
review.open.value = "chapter:1";
|
||||
tapRow(event, /** @type {any} */ ({ files, github, review, listings, send }));
|
||||
return { files, github, review, asked, send };
|
||||
}
|
||||
|
||||
// The break this catches: a folder opened without being listed afresh, so it shows what was there
|
||||
// before the agent changed it, or listed again on closing, which asks for nothing anyone sees
|
||||
test("opening a folder lists it afresh and closing it doesn't", () => {
|
||||
const opened = tap({ folder: "src" });
|
||||
assert.deepEqual([...opened.files.unfolded.value], ["src"]);
|
||||
assert.deepEqual(opened.asked, [["src", opened.send, { fresh: true }]]);
|
||||
const closed = tap({ folder: "src" }, ["src"]);
|
||||
assert.deepEqual([...closed.files.unfolded.value], []);
|
||||
assert.deepEqual(closed.asked, []);
|
||||
});
|
||||
|
||||
// The break this catches: a file tap that unfolds nothing but doesn't open the file either, opens
|
||||
// the wrong path, or leaves an open pull request in the pane over it
|
||||
test("tapping a file opens it", () => {
|
||||
const { files, github, review } = tap({ file: "src/lib.rs" });
|
||||
assert.equal(files.open.value?.path, "src/lib.rs");
|
||||
assert.deepEqual([...files.unfolded.value], []);
|
||||
assert.equal(github.open.value, null);
|
||||
assert.equal(review.open.value, null, "one pane at a time");
|
||||
});
|
||||
|
||||
// The break this catches: a folder tap that closes the open pull request, which only a file
|
||||
// taking the pane should
|
||||
test("tapping a folder leaves the pane alone", () => {
|
||||
const { github, review } = tap({ folder: "src" });
|
||||
assert.notEqual(github.open.value, null);
|
||||
assert.equal(review.open.value, "chapter:1");
|
||||
});
|
||||
|
||||
// The break this catches: a mention run into the word before it, or a file not in the backticks
|
||||
// the `@` picker writes, which is what the TUI sends the model for a file
|
||||
test("a mention goes at the end of the draft, spaced from what's there", () => {
|
||||
assert.deepEqual(withMention("look at", fileMention("a.rs")), { text: "look at `a.rs` ", caret: 15, placed: true });
|
||||
assert.deepEqual(withMention("look at ", "#7").text, "look at #7 ");
|
||||
assert.deepEqual(withMention("", "#7").text, "#7 ");
|
||||
});
|
||||
|
||||
// The break this catches: an empty folder shown as loading, a failure as empty, or a folder being
|
||||
// listed again hidden behind "Loading…" when its last entries are there to show
|
||||
test("a folder with nothing to list says why", () => {
|
||||
assert.equal(entriesNote(undefined), "Loading…");
|
||||
assert.equal(entriesNote({ state: "asking", entries: [] }), "Loading…");
|
||||
assert.equal(entriesNote({ state: "listed", entries: [] }), "Empty folder");
|
||||
assert.equal(entriesNote({ state: "failed", entries: [] }), "Couldn't list this folder");
|
||||
assert.equal(entriesNote({ state: "asking", entries: [{ name: "a", kind: "file" }] }), "");
|
||||
});
|
||||
52
crates/luxe-remote/app-tests/fixtures/turn.jsonl
Normal file
52
crates/luxe-remote/app-tests/fixtures/turn.jsonl
Normal file
File diff suppressed because one or more lines are too long
77
crates/luxe-remote/app-tests/folders.test.mjs
Normal file
77
crates/luxe-remote/app-tests/folders.test.mjs
Normal file
@@ -0,0 +1,77 @@
|
||||
// Starting a session from the phone.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { matchFolders, startIn } from "../app/folders.js";
|
||||
|
||||
const folder = (path) => ({ path, name: path.split("/").pop(), sessions: 0 });
|
||||
const WORKED_IN = [
|
||||
folder("/home/me/code/notes-app"),
|
||||
folder("/home/me/code/app"),
|
||||
folder("/home/me/apparel/site"),
|
||||
folder("/home/me/docs"),
|
||||
];
|
||||
const names = (matched) => matched.map((entry) => entry.name);
|
||||
|
||||
/** A fetch that records what it was asked and answers `status` with `body`. */
|
||||
function answering(status, body) {
|
||||
const asked = [];
|
||||
const post = async (url, init) => {
|
||||
asked.push({ url, init });
|
||||
const text = typeof body === "string" ? body : JSON.stringify(body);
|
||||
return new Response(status === 204 ? null : text, { status });
|
||||
};
|
||||
return { asked, post };
|
||||
}
|
||||
|
||||
// The break this catches: the request the bridge's start route doesn't take (another path, a GET,
|
||||
// or the folder under another name), so every tap on a folder is refused
|
||||
test("a start posts the folder and opens the session the bridge started", async () => {
|
||||
const started = { session: { session_id: "abc-123", cwd: "/home/me/app" }, place: "herdr" };
|
||||
const { asked, post } = answering(201, started);
|
||||
assert.equal(await startIn("~/app", post), "abc-123");
|
||||
assert.equal(asked[0].url, "/api/sessions");
|
||||
assert.equal(asked[0].init.method, "POST");
|
||||
assert.deepEqual(JSON.parse(asked[0].init.body), { folder: "~/app" });
|
||||
});
|
||||
|
||||
// The break this catches: a refused start taken for a session, or shown without the bridge's
|
||||
// reason, so "isn't a folder on this machine" never reaches the reader
|
||||
test("a refused start says why, in the bridge's words", async () => {
|
||||
const { post } = answering(400, "/nope isn't a folder on this machine");
|
||||
await assert.rejects(startIn("/nope", post), { message: "/nope isn't a folder on this machine" });
|
||||
});
|
||||
|
||||
// The break this catches: an empty field showing nothing, so the folders you've worked in only
|
||||
// appear once you start typing
|
||||
test("an empty field offers every folder, in the bridge's order", () => {
|
||||
assert.deepEqual(matchFolders(WORKED_IN, " "), WORKED_IN);
|
||||
});
|
||||
|
||||
// The break this catches: the ranks collapsed or reordered, so the folder named for what you typed
|
||||
// sits under ones that only hold it somewhere
|
||||
test("a name starting with what's typed leads, then a name holding it, then a path", () => {
|
||||
assert.deepEqual(names(matchFolders(WORKED_IN, "app")), ["app", "notes-app", "site"]);
|
||||
});
|
||||
|
||||
// The break this catches: a folder that holds the text nowhere offered anyway
|
||||
test("a folder that doesn't hold what's typed is left out", () => {
|
||||
assert.deepEqual(names(matchFolders(WORKED_IN, "docs")), ["docs"]);
|
||||
});
|
||||
|
||||
// The break this catches: case counted, so "App" finds nothing on a phone that capitalizes
|
||||
test("case doesn't matter", () => {
|
||||
assert.deepEqual(names(matchFolders(WORKED_IN, "DOCS")), ["docs"]);
|
||||
});
|
||||
|
||||
// The break this catches: the `~/` kept, which no absolute path holds, so typing a path the way
|
||||
// you'd type it in a terminal finds nothing
|
||||
test("a path typed from home still finds the folder under it", () => {
|
||||
assert.deepEqual(names(matchFolders(WORKED_IN, "~/code/app")), ["app"]);
|
||||
});
|
||||
|
||||
// The break this catches: a refusal with no words read as an empty message, which shows nothing
|
||||
test("a refusal with no reason still says the start failed", async () => {
|
||||
const { post } = answering(504, "");
|
||||
await assert.rejects(startIn("/slow", post), { message: "starting failed: 504" });
|
||||
});
|
||||
195
crates/luxe-remote/app-tests/github.test.mjs
Normal file
195
crates/luxe-remote/app-tests/github.test.mjs
Normal file
@@ -0,0 +1,195 @@
|
||||
// @ts-check
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { applyItem, applyListed, createGithub, githubMention, rowSubject, shownSection } from "../app/github.js";
|
||||
import { linkedSubject, tapDetail, tapGithubRow } from "../app/github-view.js";
|
||||
|
||||
/** @import { OpenItem, GithubListing } from "../app/github.js" */
|
||||
|
||||
/** A `github_listed` frame's content, cut from a live session to one section and one row. */
|
||||
const LISTED = {
|
||||
repository: "nora-quinn/luxe-dev",
|
||||
sections: [
|
||||
{ name: "Review requested", items: [], error: null, total: 0 },
|
||||
{ name: "Pull requests", items: [{ number: 211, title: "chore: refresh the embedded models.dev snapshot" }], error: null, total: 5 },
|
||||
],
|
||||
};
|
||||
|
||||
/** @type {GithubListing} */
|
||||
const ASKING = { state: "asking", repository: null, sections: [], at: 0 };
|
||||
|
||||
/** @param {Partial<OpenItem>} [fields] @returns {OpenItem} */
|
||||
function asking(fields = {}) {
|
||||
const subject = { number: 235, pull_request: true, repository: null, url: "https://github.com/nora-quinn/luxe-dev/pull/235" };
|
||||
return { subject, tab: "overview", overview: { state: "asking" }, conversation: { state: "asking" }, ...fields };
|
||||
}
|
||||
|
||||
// The break this catches: the answer not kept, or kept while nothing was asked, or a reconnect
|
||||
// that leaves the tab saying it's loading for good
|
||||
test("the listing takes the answer to what it asked", () => {
|
||||
const listed = applyListed(ASKING, { kind: "github_listed", content: LISTED });
|
||||
assert.equal(listed.state, "listed");
|
||||
assert.equal(listed.repository, "nora-quinn/luxe-dev");
|
||||
assert.equal(listed.sections.length, 2);
|
||||
assert.ok(listed.at > 1_700_000_000, "stamped with the clock its ages are drawn from");
|
||||
const idle = { ...ASKING, state: /** @type {const} */ ("idle") };
|
||||
assert.equal(applyListed(idle, { kind: "github_listed", content: LISTED }), idle);
|
||||
assert.equal(applyListed(ASKING, { kind: "ready", content: {} }).state, "lost");
|
||||
assert.equal(applyListed(ASKING, { kind: "workspace_updated", content: {} }), ASKING);
|
||||
});
|
||||
|
||||
// The break this catches: an answer for another item, or the same number in another repository,
|
||||
// taken as this one's
|
||||
test("an item takes only its own answers", () => {
|
||||
const item = asking();
|
||||
const overview = { kind: "pull_request", overview: { number: 235 } };
|
||||
assert.equal(applyItem(item, { kind: "github_overview_read", content: { number: 211, repository: null, overview } }), item);
|
||||
assert.equal(applyItem(item, { kind: "github_overview_read", content: { number: 235, repository: "a/b", overview } }), item);
|
||||
const read = applyItem(item, { kind: "github_overview_read", content: { number: 235, repository: null, overview, error: null } });
|
||||
assert.equal(read?.overview.state, "read");
|
||||
assert.deepEqual(read?.overview.value, overview);
|
||||
assert.equal(read?.conversation.state, "asking", "the overview's answer isn't the conversation's");
|
||||
});
|
||||
|
||||
// The break this catches: a failure shown as an empty read, the conversation's answer dropped,
|
||||
// or a later answer overwriting the first
|
||||
test("each half is read or failed on its own", () => {
|
||||
const entries = [{ kind: "opening" }];
|
||||
const content = { number: 235, repository: null, entries, error: null };
|
||||
const read = applyItem(asking(), { kind: "github_conversation_read", content });
|
||||
assert.deepEqual(read?.conversation.value, entries);
|
||||
const failed = applyItem(asking(), { kind: "github_overview_read", content: { number: 235, repository: null, overview: null, error: "gh failed" } });
|
||||
assert.deepEqual([failed?.overview.state, failed?.overview.error], ["failed", "gh failed"]);
|
||||
const again = applyItem(read, { kind: "github_conversation_read", content: { ...content, entries: [] } });
|
||||
assert.deepEqual(again?.conversation.value, entries);
|
||||
const silent = applyItem(asking(), { kind: "github_conversation_read", content: { ...content, entries: null, error: "gone" } });
|
||||
assert.deepEqual([silent?.conversation.state, silent?.conversation.error], ["failed", "gone"]);
|
||||
const overviewRead = applyItem(asking(), { kind: "github_overview_read", content: { number: 235, repository: null, overview: 1 } });
|
||||
const overviewAgain = applyItem(overviewRead, { kind: "github_overview_read", content: { number: 235, repository: null, overview: 2 } });
|
||||
assert.equal(overviewAgain?.overview.value, 1);
|
||||
});
|
||||
|
||||
// The break this catches: a reconnect that strands a half still asking, or throws away one
|
||||
// already read
|
||||
test("a reconnect loses only what was still being asked", () => {
|
||||
const item = asking({ overview: { state: "read", value: {}, at: 1 } });
|
||||
const after = applyItem(item, { kind: "ready", content: {} });
|
||||
assert.equal(after?.overview.state, "read");
|
||||
assert.equal(after?.conversation.state, "lost");
|
||||
assert.equal(applyItem(null, { kind: "ready", content: {} }), null);
|
||||
});
|
||||
|
||||
// The break this catches: opening an item that asks for only one half, asks without saying which,
|
||||
// or claims to be loading when nothing went out
|
||||
test("opening an item asks for both halves", () => {
|
||||
const github = createGithub();
|
||||
/** @type {any[]} */
|
||||
const sent = [];
|
||||
github.read(asking().subject, (frame) => sent.push(frame) > 0);
|
||||
const content = { number: 235, pull_request: true, repository: null };
|
||||
assert.deepEqual(sent, [{ kind: "read_github_overview", content }, { kind: "read_github_conversation", content }]);
|
||||
assert.equal(github.open.value?.overview.state, "asking");
|
||||
github.read(asking().subject, () => false);
|
||||
assert.equal(github.open.value?.conversation.state, "lost");
|
||||
});
|
||||
|
||||
// The break this catches: the tab never asking for its sections, or saying it's loading when
|
||||
// nothing went out
|
||||
test("listing asks for every section", () => {
|
||||
const github = createGithub();
|
||||
/** @type {any[]} */
|
||||
const sent = [];
|
||||
github.list((frame) => sent.push(frame) > 0);
|
||||
assert.deepEqual(sent, [{ kind: "list_github", content: {} }]);
|
||||
assert.equal(github.listing.value.state, "asking");
|
||||
github.list(() => false);
|
||||
assert.equal(github.listing.value.state, "lost");
|
||||
});
|
||||
|
||||
// The break this catches: the tab opening on an empty section when another has rows, or losing
|
||||
// the reader's pick on a refresh
|
||||
test("the tab shows the pick, else the first section with rows", () => {
|
||||
assert.equal(shownSection(LISTED.sections, "Review requested").name, "Review requested");
|
||||
assert.equal(shownSection(LISTED.sections, null).name, "Pull requests");
|
||||
assert.equal(shownSection(LISTED.sections, "Gone").name, "Pull requests");
|
||||
assert.equal(shownSection([LISTED.sections[0]], null).name, "Review requested");
|
||||
});
|
||||
|
||||
/** A row as the host draws it. @param {string} repository */
|
||||
const row = (repository) => /** @type {any} */ ({ dataset: { number: "211", pull: "true", repository, url: "https://github.com/x/pull/211" } });
|
||||
|
||||
// The break this catches: the number read as text, the kind inverted, or the checkout's own
|
||||
// repository named in the ask, which the host reads as somewhere else
|
||||
test("a row says which item to open", () => {
|
||||
const here = "nora-quinn/luxe-dev";
|
||||
assert.deepEqual(rowSubject(row(here), here), { number: 211, pull_request: true, repository: null, url: "https://github.com/x/pull/211" });
|
||||
assert.equal(rowSubject(row("someone/else"), here).repository, "someone/else");
|
||||
const issue = row(here);
|
||||
issue.dataset.pull = "false";
|
||||
assert.equal(rowSubject(issue, here).pull_request, false);
|
||||
});
|
||||
|
||||
// The break this catches: a mention that names the wrong kind, leaves out the repository the
|
||||
// agent needs to read it, or drops the link
|
||||
test("a mention says what it is and where", () => {
|
||||
const subject = { number: 7, pull_request: true, repository: null, url: "https://github.com/o/r/pull/7" };
|
||||
assert.equal(githubMention(subject, "o/r"), "pull request o/r#7 (https://github.com/o/r/pull/7)");
|
||||
const issue = { number: 8, pull_request: false, repository: "x/y", url: "https://github.com/x/y/issues/8" };
|
||||
assert.equal(githubMention(issue, "o/r"), "issue x/y#8 (https://github.com/x/y/issues/8)");
|
||||
});
|
||||
|
||||
/** An event that landed in `element` when asked for `selector`. @param {string} selector @param {any} element */
|
||||
const landing = (selector, element) => /** @type {any} */ ({ target: { closest: (/** @type {string} */ asked) => (asked === selector ? element : null) } });
|
||||
|
||||
/** Hooks with a GitHub state, a file open, and what was sent. */
|
||||
function hooks() {
|
||||
const github = createGithub();
|
||||
github.listing.value = { state: "listed", repository: "o/r", sections: [], at: 1 };
|
||||
let fileOpen = true;
|
||||
/** @type {any[]} */
|
||||
const sent = [];
|
||||
const files = { close: () => (fileOpen = false) };
|
||||
let chapterOpen = true;
|
||||
const review = { close: () => (chapterOpen = false) };
|
||||
const send = (/** @type {any} */ frame) => sent.push(frame) > 0;
|
||||
return { github, files, review, send, sent, fileOpen: () => fileOpen, chapterOpen: () => chapterOpen };
|
||||
}
|
||||
|
||||
// The break this catches: a row tap that leaves the open file in the pane, opens nothing, or
|
||||
// reacts to a tap between rows
|
||||
test("tapping a row opens it in place of the file", () => {
|
||||
const at = hooks();
|
||||
tapGithubRow(landing("button.gh-row", row("o/r")), /** @type {any} */ (at));
|
||||
assert.equal(at.fileOpen(), false);
|
||||
assert.equal(at.chapterOpen(), false, "one pane at a time");
|
||||
assert.equal(at.github.open.value?.subject.number, 211);
|
||||
const missed = hooks();
|
||||
tapGithubRow(landing("nothing", null), /** @type {any} */ (missed));
|
||||
assert.equal(missed.fileOpen(), true);
|
||||
assert.equal(missed.chapterOpen(), true);
|
||||
assert.equal(missed.sent.length, 0);
|
||||
});
|
||||
|
||||
// The break this catches: "open #N" opening an issue or another repository's number, "more lines"
|
||||
// not switching to Conversation, or "Show all" not unfolding its own card
|
||||
test("taps inside the detail open, switch and unfold", () => {
|
||||
const at = hooks();
|
||||
at.github.read({ number: 235, pull_request: true, repository: "x/y", url: "" }, at.send);
|
||||
tapDetail(landing("button.gh-open", { dataset: { number: "230" } }), /** @type {any} */ (at));
|
||||
assert.deepEqual(at.github.open.value?.subject, { number: 230, pull_request: true, repository: "x/y", url: "https://github.com/x/y/pull/230" });
|
||||
tapDetail(landing("button.gh-more", {}), /** @type {any} */ (at));
|
||||
assert.equal(at.github.open.value?.tab, "conversation");
|
||||
const removed = /** @type {string[]} */ ([]);
|
||||
const card = { classList: { remove: (/** @type {string} */ name) => removed.push(name) } };
|
||||
tapDetail(landing("button.gh-unfold", { closest: () => card }), /** @type {any} */ (at));
|
||||
assert.deepEqual(removed, ["folded"]);
|
||||
});
|
||||
|
||||
// The break this catches: a linked pull request's link pointing at nowhere when it's in the
|
||||
// checkout's own repository
|
||||
test("a linked pull request's link names the checkout when it's there", () => {
|
||||
const subject = { number: 1, pull_request: false, repository: null, url: "" };
|
||||
assert.equal(linkedSubject(subject, 5, "o/r").url, "https://github.com/o/r/pull/5");
|
||||
assert.equal(linkedSubject(subject, 5, "o/r").repository, null);
|
||||
});
|
||||
105
crates/luxe-remote/app-tests/layout.test.mjs
Normal file
105
crates/luxe-remote/app-tests/layout.test.mjs
Normal file
@@ -0,0 +1,105 @@
|
||||
// Whether the dock shows and on which side: started from the page, changed by `/dock` and the
|
||||
// header's button.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
import { WIDE, createDock, dockAfter, dockVisible, panelTabs, phoneDock, shownTab, startingMode } from "../app/layout.js";
|
||||
|
||||
const ids = (/** @type {boolean} */ wide) => panelTabs(wide).map(({ id }) => id);
|
||||
|
||||
// The break this catches: a phone left with no way to the plan and changes once its dock button is
|
||||
// gone, or a wide screen showing them twice, in the rail and the panel
|
||||
test("a phone's panel holds the dock first; a wide screen's leaves it to the rail", () => {
|
||||
assert.deepEqual(ids(false), ["dock", "files", "github", "review"]);
|
||||
assert.deepEqual(ids(true), ["files", "github", "review"]);
|
||||
});
|
||||
|
||||
// The break this catches: a panel open on the dock going blank when an iPad turns wide, or a tab
|
||||
// the screen has swapped for its first
|
||||
test("the panel shows its tab where the screen has it, and the screen's first where it doesn't", () => {
|
||||
assert.equal(shownTab("dock", true), "files");
|
||||
assert.equal(shownTab("github", true), "github");
|
||||
assert.equal(shownTab("review", false), "review");
|
||||
assert.equal(shownTab(null, false), "dock");
|
||||
});
|
||||
|
||||
// The break this catches: `/dock` on a phone doing nothing now the dock lives in the panel, a bare
|
||||
// one that can't close what it opened, or one closing Files as though it were the dock
|
||||
test("on a phone, /dock opens the panel on the dock and a bare one closes it from there", () => {
|
||||
assert.equal(phoneDock("toggle", null), "open");
|
||||
assert.equal(phoneDock("toggle", "files"), "open");
|
||||
assert.equal(phoneDock("toggle", "dock"), "close");
|
||||
assert.equal(phoneDock("show", "dock"), "open");
|
||||
assert.equal(phoneDock("hide", "files"), "close");
|
||||
assert.equal(phoneDock("left", null), null);
|
||||
assert.equal(phoneDock("auto", "dock"), null);
|
||||
});
|
||||
|
||||
// The break this catches: a stylesheet's breakpoint moved without the script's, so on a screen
|
||||
// between the two the button says the dock is hidden while the rail shows, or a peek that's only a
|
||||
// pane beside the rail is announced as covering the page
|
||||
test("the script's wide screen is the stylesheets'", () => {
|
||||
for (const sheet of ["dock.css", "peek.css"]) {
|
||||
const css = readFileSync(new URL(`../app/${sheet}`, import.meta.url), "utf8");
|
||||
assert.ok(css.includes(`@media ${WIDE} {`), `${sheet} has no @media ${WIDE}`);
|
||||
}
|
||||
});
|
||||
|
||||
// The break this catches: the config's mode ignored, or a value the app doesn't know taken as is,
|
||||
// where the TUI falls back to auto
|
||||
test("the mode starts from the page, and auto when it says nothing known", () => {
|
||||
assert.equal(startingMode({ dockMode: "shown" }), "shown");
|
||||
assert.equal(startingMode({ dockMode: "hidden" }), "hidden");
|
||||
assert.equal(startingMode({ dockMode: "sideways" }), "auto");
|
||||
assert.equal(startingMode({}), "auto");
|
||||
});
|
||||
|
||||
// The break this catches: auto showing the dock over a phone's conversation, or hiding the rail
|
||||
// on an iPad
|
||||
test("auto shows the dock on a wide screen only", () => {
|
||||
assert.equal(dockVisible("auto", true), true);
|
||||
assert.equal(dockVisible("auto", false), false);
|
||||
});
|
||||
|
||||
// The break this catches: shown or hidden bent by the screen's width, which only auto follows
|
||||
test("shown and hidden hold at any width", () => {
|
||||
assert.equal(dockVisible("shown", false), true);
|
||||
assert.equal(dockVisible("hidden", true), false);
|
||||
});
|
||||
|
||||
// The break this catches: the toggle flipping the mode rather than what's on screen, so the first
|
||||
// tap on an iPad in auto shows a dock already showing
|
||||
test("the toggle flips what's on screen", () => {
|
||||
assert.equal(dockAfter("auto", "toggle", true), "hidden");
|
||||
assert.equal(dockAfter("auto", "toggle", false), "shown");
|
||||
assert.equal(dockAfter("hidden", "toggle", true), "shown");
|
||||
});
|
||||
|
||||
// The break this catches: a `/dock` verb setting the wrong mode, or a side verb changing it
|
||||
test("show, hide and auto set the mode, and the sides leave it", () => {
|
||||
assert.equal(dockAfter("hidden", "show", false), "shown");
|
||||
assert.equal(dockAfter("shown", "hide", false), "hidden");
|
||||
assert.equal(dockAfter("shown", "auto", false), "auto");
|
||||
assert.equal(dockAfter("shown", "left", false), null);
|
||||
});
|
||||
|
||||
// The break this catches: the side kept anywhere the stylesheet doesn't read, or a side verb
|
||||
// taken for a mode
|
||||
test("a side moves the page's dock side and leaves the mode", () => {
|
||||
const page = { dataset: { dockMode: "shown", dockSide: "left" } };
|
||||
const dock = createDock(/** @type {any} */ (page), () => true);
|
||||
dock.apply("right");
|
||||
assert.equal(page.dataset.dockSide, "right");
|
||||
assert.equal(dock.mode.value, "shown");
|
||||
});
|
||||
|
||||
// The break this catches: the screen's width read once at start, so a rotated iPad's toggle
|
||||
// flips the wrong way
|
||||
test("the toggle reads the width when it's tapped", () => {
|
||||
let wide = true;
|
||||
const dock = createDock(/** @type {any} */ ({ dataset: {} }), () => wide);
|
||||
wide = false;
|
||||
dock.apply("toggle");
|
||||
assert.equal(dock.mode.value, "shown");
|
||||
});
|
||||
95
crates/luxe-remote/app-tests/lines.test.mjs
Normal file
95
crates/luxe-remote/app-tests/lines.test.mjs
Normal file
@@ -0,0 +1,95 @@
|
||||
// @ts-check
|
||||
// Line picks: what a tap on a line's number picks, what a selection covers, and what Ask writes.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { askLabel, lineWords, markPicked, selectedLines, tapLine, tapped } from "../app/lines.js";
|
||||
|
||||
const at = (/** @type {number} */ first, last = first, path = "src/a.rs") => ({ path, first, last });
|
||||
|
||||
// The break this catches: a second tap starting over instead of stretching, a stretch that runs
|
||||
// backwards when the second line is above the first, or a lone pick that can't be let go
|
||||
test("a tap picks, a second stretches, and the same line lets go", () => {
|
||||
assert.deepEqual(tapLine(null, "src/a.rs", 12), at(12));
|
||||
assert.deepEqual(tapLine(at(12), "src/a.rs", 18), at(12, 18));
|
||||
assert.deepEqual(tapLine(at(12), "src/a.rs", 4), at(4, 12));
|
||||
assert.equal(tapLine(at(12), "src/a.rs", 12), null);
|
||||
});
|
||||
|
||||
// The break this catches: a third tap stretching a stretch, or a tap in another file stretching
|
||||
// across files
|
||||
test("after a stretch, or in another file, a tap starts over", () => {
|
||||
assert.deepEqual(tapLine(at(12, 18), "src/a.rs", 30), at(30));
|
||||
assert.deepEqual(tapLine(at(12), "src/b.rs", 18), at(18, 18, "src/b.rs"));
|
||||
});
|
||||
|
||||
// The break this catches: Ask writing something other than what the TUI sends for the same lines
|
||||
// (its mention expands to the path in backticks, then `line 12` or `lines 12–18` with an en dash)
|
||||
test("ask writes the path and lines as the TUI does", () => {
|
||||
assert.equal(lineWords(at(12)), "`src/a.rs` line 12");
|
||||
assert.equal(lineWords(at(12, 18)), "`src/a.rs` lines 12–18");
|
||||
assert.equal(askLabel(at(12)), "Ask about line 12");
|
||||
assert.equal(askLabel(at(12, 18)), "Ask about lines 12–18");
|
||||
});
|
||||
|
||||
/** A row of the host's HTML: line `line` in the block for `path`. */
|
||||
function row(/** @type {number | null} */ line, path = "src/a.rs") {
|
||||
const block = { getAttribute: () => path };
|
||||
const classes = new Set();
|
||||
const element = {
|
||||
getAttribute: (/** @type {string} */ name) => (name === "data-line" ? String(line) : null),
|
||||
closest: (/** @type {string} */ selector) => (selector === "[data-path]" ? block : line === null ? null : element),
|
||||
classList: { toggle: (/** @type {string} */ name, /** @type {boolean} */ on) => (on ? classes.add(name) : classes.delete(name)), has: (/** @type {string} */ name) => classes.has(name) },
|
||||
};
|
||||
return element;
|
||||
}
|
||||
|
||||
/** A tap that landed on `row`'s number, or on its code. */
|
||||
const landing = (/** @type {any} */ target, onNumber = true) => ({ closest: (/** @type {string} */ selector) => (selector === ".ln" && onNumber ? target : null) });
|
||||
|
||||
// The break this catches: a tap on the code (where a selection starts) picking the line, or a tap
|
||||
// on a number not reading its line and file from the host's HTML
|
||||
test("only a tap on a line's number picks it", () => {
|
||||
assert.deepEqual(tapped(null, /** @type {any} */ (landing(row(7)))), at(7));
|
||||
assert.equal(tapped(at(7), /** @type {any} */ (landing(row(9), false))), null, "a tap elsewhere lets go");
|
||||
assert.equal(tapped(at(7), null), null);
|
||||
});
|
||||
|
||||
/** A selection whose range touches `touched` rows of a block holding `rows`. */
|
||||
function selecting(/** @type {any[]} */ rows, /** @type {any[]} */ touched, inside = true, path = "src/a.rs") {
|
||||
const block = { nodeType: 1, getAttribute: () => path, closest: () => block, querySelectorAll: () => rows };
|
||||
const range = { commonAncestorContainer: block, intersectsNode: (/** @type {any} */ node) => touched.includes(node) };
|
||||
const selection = { isCollapsed: false, rangeCount: 1, getRangeAt: () => range };
|
||||
const root = { contains: () => inside };
|
||||
return { selection: /** @type {any} */ (selection), root: /** @type {any} */ (root) };
|
||||
}
|
||||
|
||||
// The break this catches: a selection that starts partway through a line not counting it, or the
|
||||
// lines read from the first and last rows rather than every row touched
|
||||
test("a selection offers every line it touches", () => {
|
||||
const rows = [row(3), row(4), row(5), row(6)];
|
||||
const { selection, root } = selecting(rows, [rows[1], rows[2]]);
|
||||
assert.deepEqual(selectedLines(selection, root), at(4, 5));
|
||||
});
|
||||
|
||||
// The break this catches: Ask offered for nothing (a collapsed caret, a selection in another pane,
|
||||
// or one across deleted lines alone, which no line in the file stands for)
|
||||
test("a selection offers nothing when it covers no line of this pane", () => {
|
||||
const rows = [row(3), row(4)];
|
||||
assert.equal(selectedLines({ ...selecting(rows, rows).selection, isCollapsed: true }, selecting(rows, rows).root), null);
|
||||
const outside = selecting(rows, rows, false);
|
||||
assert.equal(selectedLines(outside.selection, outside.root), null);
|
||||
const none = selecting(rows, []);
|
||||
assert.equal(selectedLines(none.selection, none.root), null);
|
||||
assert.equal(selectedLines(null, none.root), null);
|
||||
});
|
||||
|
||||
// The break this catches: rows outside the pick, or in another file with the same line numbers,
|
||||
// marked as picked, or a let-go pick leaving its marks behind
|
||||
test("only the picked rows of the picked file are marked", () => {
|
||||
const rows = [row(3), row(4), row(5), row(6), row(4, "src/b.rs")];
|
||||
const root = /** @type {any} */ ({ querySelectorAll: () => rows });
|
||||
markPicked(root, at(4, 5));
|
||||
assert.deepEqual(rows.map((it) => it.classList.has("picked")), [false, true, true, false, false]);
|
||||
markPicked(root, null);
|
||||
assert.deepEqual(rows.map((it) => it.classList.has("picked")), [false, false, false, false, false]);
|
||||
});
|
||||
18
crates/luxe-remote/app-tests/machine.test.mjs
Normal file
18
crates/luxe-remote/app-tests/machine.test.mjs
Normal file
@@ -0,0 +1,18 @@
|
||||
// @ts-check
|
||||
// Which computer the app reaches, as the bridge names the page for it.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { machineName } from "../app/sessions.js";
|
||||
|
||||
/** A page whose `luxe-machine` meta says `name`, or that has none. */
|
||||
const page = (/** @type {string | null} */ name) => ({
|
||||
querySelector: (/** @type {string} */ selector) =>
|
||||
selector === 'meta[name="luxe-machine"]' && name !== null ? { getAttribute: () => name } : null,
|
||||
});
|
||||
|
||||
// The break this catches: the session list of two computers' apps looking the same because the
|
||||
// meta goes unread, or a page without one (Tailscale couldn't say) showing a stray label
|
||||
test("the app names the computer its page is named for, and nothing without a name", () => {
|
||||
assert.equal(machineName(/** @type {any} */ (page("desk"))), "desk");
|
||||
assert.equal(machineName(/** @type {any} */ (page(null))), "");
|
||||
});
|
||||
157
crates/luxe-remote/app-tests/mentions.test.mjs
Normal file
157
crates/luxe-remote/app-tests/mentions.test.mjs
Normal file
@@ -0,0 +1,157 @@
|
||||
// `@` mentions of project files: reading one back from the box, and the folders listed for it.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createListings, matchEntries, mentionAt, pickEntry } from "../app/mentions.js";
|
||||
|
||||
/** @import { Entry } from "../app/mentions.js" */
|
||||
|
||||
/** @param {string} name @returns {Entry} */
|
||||
const dir = (name) => ({ name, kind: "directory" });
|
||||
/** @param {string} name @returns {Entry} */
|
||||
const file = (name) => ({ name, kind: "file" });
|
||||
|
||||
// The break this catches: the mention missed at the start of the box, where most begin
|
||||
test("an @ at the start is a mention", () => {
|
||||
assert.deepEqual(mentionAt("@ma", 3), { start: 0, folder: "", name: "ma" });
|
||||
});
|
||||
|
||||
// The break this catches: the folder and name split anywhere but the last slash
|
||||
test("what's typed splits into a folder and a name at the last slash", () => {
|
||||
const text = "look at @src/cli/ma";
|
||||
assert.deepEqual(mentionAt(text, text.length), { start: 8, folder: "src/cli", name: "ma" });
|
||||
});
|
||||
|
||||
// The break this catches: an address read as a mention, which pops the picker mid-email
|
||||
test("an @ inside a word isn't a mention", () => {
|
||||
assert.equal(mentionAt("me@example.com", 14), null);
|
||||
});
|
||||
|
||||
// The break this catches: the picker kept up after the mention's done and a space typed
|
||||
test("a space ends the mention", () => {
|
||||
assert.equal(mentionAt("@src ", 5), null);
|
||||
});
|
||||
|
||||
// The break this catches: the caret ignored, so a mention typed mid-message reads the end instead
|
||||
test("the mention is the one just before the caret", () => {
|
||||
assert.deepEqual(mentionAt("@do and more", 3), { start: 0, folder: "", name: "do" });
|
||||
});
|
||||
|
||||
// The break this catches: the ranks lost, so a name holding the text comes before one starting
|
||||
// with it, or one holding it nowhere stays in
|
||||
test("names starting with what's typed lead, then names holding it", () => {
|
||||
const entries = [file("domain.rs"), file("main.rs"), file("Makefile"), file("lib.rs")];
|
||||
assert.deepEqual(matchEntries(entries, "ma").map((entry) => entry.name), ["main.rs", "Makefile", "domain.rs"]);
|
||||
});
|
||||
|
||||
// The break this catches: case counted, so a capital the keyboard put in hides every file
|
||||
test("names match whatever the case typed", () => {
|
||||
assert.deepEqual(matchEntries([file("main.rs")], "MA").map((entry) => entry.name), ["main.rs"]);
|
||||
});
|
||||
|
||||
// The break this catches: a file put in bare or without the folder it's in, which isn't what the
|
||||
// TUI sends the model, or the caret left before it
|
||||
test("a picked file goes in as its path in backticks", () => {
|
||||
const text = "fix @src/ma please";
|
||||
const query = /** @type {any} */ (mentionAt(text, 11));
|
||||
assert.deepEqual(pickEntry(text, 11, query, file("main.rs")), { text: "fix `src/main.rs` please", caret: 18 });
|
||||
});
|
||||
|
||||
// The break this catches: a picked folder closing the mention, so its files can't be reached
|
||||
test("a picked folder opens it for the next level", () => {
|
||||
const query = /** @type {any} */ (mentionAt("@sr", 3));
|
||||
assert.deepEqual(pickEntry("@sr", 3, query, dir("src")), { text: "@src/", caret: 5 });
|
||||
});
|
||||
|
||||
/**
|
||||
* Listings that have asked for `folders`, the frames they sent, and the id of the nth question.
|
||||
* @param {string[]} folders
|
||||
*/
|
||||
function listingsAsked(...folders) {
|
||||
const listings = createListings();
|
||||
/** @type {import("../app/connection.js").Frame[]} */
|
||||
const frames = [];
|
||||
for (const folder of folders) listings.ask(folder, (frame) => (frames.push(frame), true));
|
||||
return { listings, frames, idOf: (/** @type {number} */ nth) => frames[nth].content.request_id };
|
||||
}
|
||||
|
||||
// The break this catches: the question in a shape `list_directory` doesn't take, or asked twice
|
||||
test("a folder is asked for once, as list_directory", () => {
|
||||
const { listings, frames, idOf } = listingsAsked("src", "src");
|
||||
assert.deepEqual(frames, [{ kind: "list_directory", content: { request_id: idOf(0), path: "src" } }]);
|
||||
assert.equal(listings.folders.value.src.state, "asking");
|
||||
});
|
||||
|
||||
// The break this catches: ids counted from one on every phone, so two phones in one session file
|
||||
// each other's answers, since every client hears every answer
|
||||
test("no two phones ask with the same id", () => {
|
||||
const first = listingsAsked("src");
|
||||
const second = listingsAsked("src");
|
||||
assert.notEqual(first.idOf(0), second.idOf(0));
|
||||
});
|
||||
|
||||
// The break this catches: the answer filed under the wrong folder, or its entries read from the
|
||||
// wrong field
|
||||
test("the answer is filed under the folder that was asked for", () => {
|
||||
const { listings, idOf } = listingsAsked("", "src");
|
||||
const listing = { path: "src", entries: [file("main.rs")], omitted: 0 };
|
||||
listings.apply({ kind: "directory_listed", content: { request_id: idOf(1), listing } });
|
||||
assert.deepEqual(listings.folders.value.src, { state: "listed", entries: [file("main.rs")] });
|
||||
assert.equal(listings.folders.value[""].state, "asking");
|
||||
});
|
||||
|
||||
// The break this catches: a folder that can't be listed left asking forever
|
||||
test("a folder that can't be listed says so", () => {
|
||||
const { listings, idOf } = listingsAsked("gone");
|
||||
listings.apply({ kind: "directory_list_failed", content: { request_id: idOf(0), path: "gone", error: "no such folder" } });
|
||||
assert.equal(listings.folders.value.gone.state, "failed");
|
||||
});
|
||||
|
||||
// The break this catches: another client's answer, or a stale one, filed as if it were ours
|
||||
test("an answer to a question not asked here changes nothing", () => {
|
||||
const { listings } = listingsAsked("src");
|
||||
const listing = { path: "lib", entries: [], omitted: 0 };
|
||||
listings.apply({ kind: "directory_listed", content: { request_id: "listing:elsewhere", listing } });
|
||||
assert.deepEqual(Object.keys(listings.folders.value), ["src"]);
|
||||
});
|
||||
|
||||
// The break this catches: a question that never left counted as asked, so it's never asked again
|
||||
test("a question that couldn't be sent is asked again next time", () => {
|
||||
const listings = createListings();
|
||||
listings.ask("src", () => false);
|
||||
assert.equal(listings.folders.value.src, undefined);
|
||||
});
|
||||
|
||||
/** Listings with `src` listed as holding `main.rs`, and the frames sent so far. */
|
||||
function srcListed() {
|
||||
const asked = listingsAsked("src");
|
||||
const listing = { path: "src", entries: [file("main.rs")], omitted: 0 };
|
||||
asked.listings.apply({ kind: "directory_listed", content: { request_id: asked.idOf(0), listing } });
|
||||
return asked;
|
||||
}
|
||||
|
||||
// The break this catches: the Files tab shown a folder as it was when the picker first listed it,
|
||||
// missing what the agent has written since
|
||||
test("a fresh ask lists a known folder again, keeping its entries up meanwhile", () => {
|
||||
const { listings, frames } = srcListed();
|
||||
listings.ask("src", (frame) => (frames.push(frame), true), { fresh: true });
|
||||
assert.equal(frames.length, 2);
|
||||
assert.deepEqual(listings.folders.value.src, { state: "asking", entries: [file("main.rs")] });
|
||||
});
|
||||
|
||||
// The break this catches: a fresh ask sent again while one is on its way, doubling every request
|
||||
// each time the view draws
|
||||
test("a fresh ask waits for the one on its way", () => {
|
||||
const { listings, frames } = listingsAsked("src");
|
||||
listings.ask("src", (frame) => (frames.push(frame), true), { fresh: true });
|
||||
assert.equal(frames.length, 1);
|
||||
});
|
||||
|
||||
// The break this catches: a folder asked for just before the connection dropped left loading
|
||||
// forever, since the new connection never answers the old question
|
||||
test("a new connection forgets the folders still on their way, and only those", () => {
|
||||
const { listings, frames } = srcListed();
|
||||
listings.ask("lib", (frame) => (frames.push(frame), true));
|
||||
listings.apply({ kind: "ready", content: {} });
|
||||
assert.deepEqual(Object.keys(listings.folders.value), ["src"]);
|
||||
});
|
||||
88
crates/luxe-remote/app-tests/models.test.mjs
Normal file
88
crates/luxe-remote/app-tests/models.test.mjs
Normal file
@@ -0,0 +1,88 @@
|
||||
// The model and thinking pickers: asking the session for its models, and the frames a pick sends.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createModels, isCurrent, selectModelFrame, thinkingFrame, thinkingLevels } from "../app/models.js";
|
||||
|
||||
const SONNET = { provider: "anthropic", model: "claude-sonnet-5", name: "Claude Sonnet 5", thinking_levels: ["off", "low", "high"] };
|
||||
const MINI = { provider: "openai", model: "gpt-mini", name: "GPT Mini", thinking_levels: ["off"] };
|
||||
|
||||
/** A models state that has asked once, and the frames it sent. */
|
||||
function asked(sent = true) {
|
||||
const models = createModels();
|
||||
const frames = [];
|
||||
models.ask((frame) => (frames.push(frame), sent));
|
||||
return { models, frames };
|
||||
}
|
||||
|
||||
// The break this catches: the question sent in a shape `list_models` doesn't take, or the sheet
|
||||
// not showing that it's waiting
|
||||
test("asking sends list_models with an id, and waits", () => {
|
||||
const { models, frames } = asked();
|
||||
assert.deepEqual(frames, [{ kind: "list_models", content: { request_id: "models-1" } }]);
|
||||
assert.equal(models.listing.value.state, "asking");
|
||||
});
|
||||
|
||||
// The break this catches: a question that never left counted as asked, so the sheet waits forever
|
||||
test("a question that couldn't be sent says so", () => {
|
||||
assert.equal(asked(false).models.listing.value.state, "lost");
|
||||
});
|
||||
|
||||
// The break this catches: the answer not taken, or taken from the wrong field
|
||||
test("the answer to the question is listed", () => {
|
||||
const { models } = asked();
|
||||
models.apply({ kind: "models_listed", content: { request_id: "models-1", models: [SONNET, MINI] } });
|
||||
assert.deepEqual(models.listing.value, { state: "listed", models: [SONNET, MINI] });
|
||||
});
|
||||
|
||||
// The break this catches: an answer to an earlier question, arriving late, replacing the latest
|
||||
test("an answer to an earlier question is ignored", () => {
|
||||
const { models } = asked();
|
||||
models.ask(() => true);
|
||||
models.apply({ kind: "models_listed", content: { request_id: "models-1", models: [MINI] } });
|
||||
assert.equal(models.listing.value.state, "asking");
|
||||
});
|
||||
|
||||
// The break this catches: an older Luxe's refusal ignored, so the sheet says it's listing forever
|
||||
test("a Luxe that doesn't know the question is told apart", () => {
|
||||
const { models } = asked();
|
||||
models.apply({ kind: "action_rejected", content: { kind: "list_models", reason: "unknown kind" } });
|
||||
assert.equal(models.listing.value.state, "unsupported");
|
||||
});
|
||||
|
||||
// The break this catches: any refusal, of something else entirely, taken for the question's
|
||||
test("a refusal of something else leaves the question waiting", () => {
|
||||
const { models } = asked();
|
||||
models.apply({ kind: "action_rejected", content: { kind: "steer_turn", reason: "missing text" } });
|
||||
assert.equal(models.listing.value.state, "asking");
|
||||
});
|
||||
|
||||
// The break this catches: the running model matched by provider or by id alone, which marks a
|
||||
// second provider's model of the same name as running
|
||||
test("the running model is matched by provider and id together", () => {
|
||||
assert.equal(isCurrent(SONNET, { provider: "anthropic", model: "claude-sonnet-5" }), true);
|
||||
assert.equal(isCurrent(SONNET, { provider: "bedrock", model: "claude-sonnet-5" }), false);
|
||||
assert.equal(isCurrent(SONNET, { provider: "anthropic", model: "claude-opus-5" }), false);
|
||||
});
|
||||
|
||||
// The break this catches: the levels offered from another model's list, or every level offered
|
||||
// before the running model's are known, which the session would clamp without a word
|
||||
test("thinking offers the running model's levels, and none before it's listed", () => {
|
||||
const current = { provider: "openai", model: "gpt-mini" };
|
||||
assert.deepEqual(thinkingLevels([SONNET, MINI], current), ["off"]);
|
||||
assert.deepEqual(thinkingLevels([], current), []);
|
||||
});
|
||||
|
||||
// The break this catches: a pick sent with the display name or levels, which `select_model`
|
||||
// doesn't take, or under another key
|
||||
test("a picked model is sent as provider and id", () => {
|
||||
assert.deepEqual(selectModelFrame(SONNET), {
|
||||
kind: "select_model",
|
||||
content: { provider: "anthropic", model: "claude-sonnet-5" },
|
||||
});
|
||||
});
|
||||
|
||||
// The break this catches: the level wrapped in an object, when `set_thinking_level` takes a string
|
||||
test("a picked level is sent bare", () => {
|
||||
assert.deepEqual(thinkingFrame("high"), { kind: "set_thinking_level", content: "high" });
|
||||
});
|
||||
23
crates/luxe-remote/app-tests/notifications.test.mjs
Normal file
23
crates/luxe-remote/app-tests/notifications.test.mjs
Normal file
@@ -0,0 +1,23 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { keyBytes, support } from "../app/notifications.js";
|
||||
|
||||
// The break this catches: the switch offered where subscribing can only fail, or a Safari tab on
|
||||
// iOS told notifications are impossible when the Home Screen is the way to them.
|
||||
test("what the switch offers follows what the browser can do", () => {
|
||||
assert.equal(support({ worker: true, push: true, standalone: false }), "ready");
|
||||
assert.equal(support({ worker: true, push: true, standalone: true }), "ready");
|
||||
assert.equal(support({ worker: true, push: false, standalone: false }), "home-screen");
|
||||
assert.equal(support({ worker: false, push: true, standalone: false }), "home-screen");
|
||||
assert.equal(support({ worker: true, push: false, standalone: true }), "unsupported");
|
||||
});
|
||||
|
||||
// The break this catches: the key passed as base64url text or decoded as plain base64, which
|
||||
// PushManager refuses, so turning notifications on fails on every device.
|
||||
test("the bridge's key reaches the browser as bytes", () => {
|
||||
assert.deepEqual([...keyBytes("AQID_-8")], [1, 2, 3, 255, 239]);
|
||||
const key = "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
|
||||
const bytes = keyBytes(key);
|
||||
assert.equal(bytes.length, 65);
|
||||
assert.equal(bytes[0], 4, "an uncompressed point");
|
||||
});
|
||||
133
crates/luxe-remote/app-tests/package-lock.json
generated
Normal file
133
crates/luxe-remote/app-tests/package-lock.json
generated
Normal file
@@ -0,0 +1,133 @@
|
||||
{
|
||||
"name": "luxe-remote-app-tests",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "luxe-remote-app-tests",
|
||||
"devDependencies": {
|
||||
"@preact/signals": "2.11.3",
|
||||
"@preact/signals-core": "1.14.4",
|
||||
"@types/node": "^24.0.0",
|
||||
"htm": "3.1.1",
|
||||
"playwright": "1.63.0",
|
||||
"preact": "11.0.1",
|
||||
"typescript": "5.9.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@preact/signals": {
|
||||
"version": "2.11.3",
|
||||
"resolved": "https://registry.npmjs.org/@preact/signals/-/signals-2.11.3.tgz",
|
||||
"integrity": "sha512-mttwFM98G/JiriTgMwU+UWygL6sfVmYEiNcPSKkUnv4PxPpZhmP2ugGC4qi360+ZIHyQ8NY05bfJT3b4RUIGlw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@preact/signals-core": "^1.14.4"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/preact"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"preact": ">= 10.25.0 || >=11.0.0-0"
|
||||
}
|
||||
},
|
||||
"node_modules/@preact/signals-core": {
|
||||
"version": "1.14.4",
|
||||
"resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.4.tgz",
|
||||
"integrity": "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/preact"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.19.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
|
||||
"integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/htm": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/htm/-/htm-3.1.1.tgz",
|
||||
"integrity": "sha512-983Vyg8NwUE7JkZ6NmOqpCZ+sh1bKv2iYTlUkzlWmA5JD2acKoxd4KVxbMmxX/85mtfdnDmTFoNKcg5DGAvxNQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
|
||||
"integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.63.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.63.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
|
||||
"integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/preact": {
|
||||
"version": "11.0.1",
|
||||
"resolved": "https://registry.npmjs.org/preact/-/preact-11.0.1.tgz",
|
||||
"integrity": "sha512-TNNwEq++jYNHy747LziCjPRVgEwnLSOIOAw/oYcjI3Tdnubx2EXtt76I0an8PATvUWtx/DX1kFIg1eFN+O/fkw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/preact"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"preact-render-to-string": ">=6.7.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"preact-render-to-string": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
20
crates/luxe-remote/app-tests/package.json
Normal file
20
crates/luxe-remote/app-tests/package.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "luxe-remote-app-tests",
|
||||
"private": true,
|
||||
"description": "Type checks, unit tests and the WebKit end-to-end test for the luxe remote phone app",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"check": "tsc -p . && tsc -p tsconfig.worker.json && tsc -p tsconfig.tests.json",
|
||||
"test": "node --import ./register.mjs --test",
|
||||
"e2e": "node --test --test-timeout=60000 e2e/flow.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@preact/signals": "2.11.3",
|
||||
"@preact/signals-core": "1.14.4",
|
||||
"htm": "3.1.1",
|
||||
"playwright": "1.63.0",
|
||||
"preact": "11.0.1",
|
||||
"typescript": "5.9.3",
|
||||
"@types/node": "^24.0.0"
|
||||
}
|
||||
}
|
||||
28
crates/luxe-remote/app-tests/pairing.test.mjs
Normal file
28
crates/luxe-remote/app-tests/pairing.test.mjs
Normal file
@@ -0,0 +1,28 @@
|
||||
// Reading an invitation out of what someone pasted.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { invitationFrom } from "../app/pairing.js";
|
||||
|
||||
/** A token as `luxe remote pair` makes one: 32 random bytes, URL-safe base64 without padding. */
|
||||
const TOKEN = "q3J0-Zx_8fLmN2pQrStUvWxYz0123456789AbCdEfGh";
|
||||
|
||||
// The break this catches: the whole link sent as the invitation, which the bridge can't match
|
||||
test("the token is read out of the printed link", () => {
|
||||
assert.equal(invitationFrom(`https://desk.tail1234.ts.net/pair#${TOKEN}`), TOKEN);
|
||||
});
|
||||
|
||||
// The break this catches: insisting on a whole link, when a notes app or a message may carry only
|
||||
// the part after the #, or a copy picks up the line's spaces
|
||||
test("the token alone is taken, spaces and all", () => {
|
||||
assert.equal(invitationFrom(TOKEN), TOKEN);
|
||||
assert.equal(invitationFrom(` ${TOKEN}\n`), TOKEN);
|
||||
});
|
||||
|
||||
// The break this catches: a link without its invitation, or text that isn't one, enabling Pair
|
||||
// for a request that can only fail
|
||||
test("nothing that can't be an invitation is taken for one", () => {
|
||||
for (const text of ["", "https://desk.tail1234.ts.net/pair", "https://desk.tail1234.ts.net/pair#", "two words"]) {
|
||||
assert.equal(invitationFrom(text), null, JSON.stringify(text));
|
||||
}
|
||||
});
|
||||
105
crates/luxe-remote/app-tests/pending.test.mjs
Normal file
105
crates/luxe-remote/app-tests/pending.test.mjs
Normal file
@@ -0,0 +1,105 @@
|
||||
// Prompts and steering, folded from frames, and the frames the phone sends back.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createPending, messageFrame, permissionReply, questionReply } from "../app/pending.js";
|
||||
import { permissionChoices, toggled } from "../app/prompt.js";
|
||||
|
||||
const frame = (kind, content) => ({ kind, content });
|
||||
const asked = (id) => frame("permission_requested", {
|
||||
id, session_id: "s", tool: "bash", permission: "bash", summary: "Run: rm -rf build", always_patterns: ["rm *"],
|
||||
});
|
||||
const ids = (pending) => pending.prompts.value.map((prompt) => prompt.id);
|
||||
|
||||
function fold(frames) {
|
||||
const pending = createPending();
|
||||
frames.forEach(pending.apply);
|
||||
return pending;
|
||||
}
|
||||
|
||||
// The break this catches: `prompt_closed` taking down every prompt, or the wrong one, so a
|
||||
// question answered at the desk clears the approval still waiting on the phone
|
||||
test("a prompt closes by its own id, whoever answered it", () => {
|
||||
const pending = fold([asked("perm:1"), asked("perm:2"), asked("perm:3"), frame("prompt_closed", { id: "perm:2" })]);
|
||||
assert.deepEqual(ids(pending), ["perm:1", "perm:3"]);
|
||||
});
|
||||
|
||||
// The break this catches: a question shown as a permission card, or its options lost
|
||||
test("a question opens as a question, with its options", () => {
|
||||
const options = [{ label: "postgres", description: "Relational", recommended: true }];
|
||||
const pending = fold([frame("question_asked", { id: "ask:1", session_id: "s", prompt: "Which?", options, multi: false })]);
|
||||
const [prompt] = pending.prompts.value;
|
||||
assert.equal(prompt.kind, "question");
|
||||
assert.deepEqual(prompt.options, options);
|
||||
});
|
||||
|
||||
// The break this catches: the same prompt sent twice (a snapshot racing the live event) drawn as
|
||||
// two, so answering one leaves a card behind that can't be answered
|
||||
test("a prompt already open isn't opened twice", () => {
|
||||
assert.deepEqual(ids(fold([asked("perm:1"), asked("perm:1")])), ["perm:1"]);
|
||||
});
|
||||
|
||||
// The break this catches: a reconnect keeping the last connection's prompts, which the snapshot
|
||||
// sends again if they're still open, so one answered meanwhile lingers on the phone
|
||||
test("a new connection starts with nothing waiting", () => {
|
||||
const pending = fold([asked("perm:1"), frame("ready", {})]);
|
||||
pending.steered();
|
||||
pending.apply(frame("ready", {}));
|
||||
assert.deepEqual(ids(pending), []);
|
||||
assert.equal(pending.steering.value, 0);
|
||||
});
|
||||
|
||||
// The break this catches: a delivery clearing only some of the tray, or a turn ending clearing
|
||||
// steering the engine holds for the next turn, as the TUI's tray keeps it
|
||||
test("steering waits through a turn's end, and a checkpoint delivers all of it", () => {
|
||||
const pending = createPending();
|
||||
pending.steered();
|
||||
pending.steered();
|
||||
pending.apply(frame("turn_ended", { reason: "end_turn" }));
|
||||
assert.equal(pending.steering.value, 2);
|
||||
pending.apply(frame("steering_delivered", { count: 1 }));
|
||||
assert.equal(pending.steering.value, 0);
|
||||
});
|
||||
|
||||
// The break this catches: Stop or withdraw leaving the tray saying messages wait that the engine
|
||||
// has thrown away
|
||||
test("dropping steering empties the tray", () => {
|
||||
const pending = createPending();
|
||||
pending.steered();
|
||||
pending.dropSteering();
|
||||
assert.equal(pending.steering.value, 0);
|
||||
});
|
||||
|
||||
// The break this catches: a reply frame the host's decoder doesn't know, which it rejects, so a
|
||||
// tap on the phone answers nothing; shapes as `rpc.md` documents them
|
||||
test("replies are the protocol's frames", () => {
|
||||
assert.deepEqual(permissionReply("perm:1", "always"), { kind: "respond_permission", content: { id: "perm:1", reply: "always" } });
|
||||
assert.deepEqual(questionReply("ask:1", ["postgres", "my own"]), {
|
||||
kind: "answer_question", content: { id: "ask:1", reply: { answered: ["postgres", "my own"] } },
|
||||
});
|
||||
assert.deepEqual(questionReply("ask:1", null), { kind: "answer_question", content: { id: "ask:1", reply: "cancelled" } });
|
||||
});
|
||||
|
||||
// The break this catches: writing while a turn runs sent as a new message, which waits for the
|
||||
// turn to end, instead of steering the one running
|
||||
test("a message steers while a turn runs, and starts one otherwise", () => {
|
||||
assert.deepEqual(messageFrame("hi", false), { kind: "submit_user_message", content: { text: "hi" } });
|
||||
assert.deepEqual(messageFrame("hi", true), { kind: "steer_turn", content: { text: "hi" } });
|
||||
});
|
||||
|
||||
// The break this catches: "remember" offered for a call with no pattern to remember, which the
|
||||
// engine can only treat as once; or the options out of the TUI's order
|
||||
test("the remembering answers appear only when the call has a pattern", () => {
|
||||
/** @param {string[]} always_patterns */
|
||||
const asking = (always_patterns) => permissionChoices({ kind: "permission", id: "p", tool: "bash", summary: "", always_patterns });
|
||||
const replies = (patterns) => asking(patterns).map((choice) => choice.reply);
|
||||
assert.deepEqual(replies([]), ["once", "reject"]);
|
||||
assert.deepEqual(replies(["rm *"]), ["once", "always", "always_persist", "reject"]);
|
||||
assert.match(asking(["rm *"])[1].hint, /rm \*/);
|
||||
});
|
||||
|
||||
// The break this catches: ticking an option twice leaving it ticked, so it can't be taken back
|
||||
test("ticking an option again unticks it", () => {
|
||||
assert.deepEqual(toggled(["a"], "b"), ["a", "b"]);
|
||||
assert.deepEqual(toggled(["a", "b"], "a"), ["b"]);
|
||||
});
|
||||
40
crates/luxe-remote/app-tests/photos.test.mjs
Normal file
40
crates/luxe-remote/app-tests/photos.test.mjs
Normal file
@@ -0,0 +1,40 @@
|
||||
// Photos in the composer: their size, the frame that carries them, and the button's word.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { sendLabel } from "../app/composer.js";
|
||||
import { messageFrame } from "../app/pending.js";
|
||||
import { LONGEST_EDGE, dataOf, fitWithin, forTheWire } from "../app/photos.js";
|
||||
|
||||
// The break this catches: a photo sent at full size (12 megapixels, megabytes over the phone's
|
||||
// network), squashed out of shape, or a small screenshot blown up past its own pixels
|
||||
test("a photo fits the longest edge, keeps its shape, and is never enlarged", () => {
|
||||
assert.deepEqual(fitWithin(4032, 3024), { width: LONGEST_EDGE, height: 1176 });
|
||||
assert.deepEqual(fitWithin(3024, 4032), { width: 1176, height: LONGEST_EDGE });
|
||||
assert.deepEqual(fitWithin(800, 600), { width: 800, height: 600 });
|
||||
});
|
||||
|
||||
// The break this catches: the preview sent along, doubling every photo's size, or the data URL's
|
||||
// header sent as part of the base64, which no provider can decode
|
||||
test("on the wire a photo is its base64, its type and its name", () => {
|
||||
const preview = "data:image/jpeg;base64,QUJD";
|
||||
assert.equal(dataOf(preview), "QUJD");
|
||||
const photo = { data: "QUJD", mime: "image/jpeg", name: "IMG_1.HEIC", preview };
|
||||
assert.deepEqual(forTheWire([photo]), [{ data: "QUJD", mime: "image/jpeg", name: "IMG_1.HEIC" }]);
|
||||
});
|
||||
|
||||
// The break this catches: photos sent as steering, which carries only words, so they're dropped;
|
||||
// a message with photos starts a turn, waiting for a running one to end
|
||||
test("a message with photos is always a new turn", () => {
|
||||
const images = [{ data: "QUJD", mime: "image/jpeg", name: null }];
|
||||
const frame = { kind: "submit_user_message", content: { text: "what's this?", images } };
|
||||
assert.deepEqual(messageFrame("what's this?", true, images), frame);
|
||||
assert.deepEqual(messageFrame("what's this?", false, images), frame);
|
||||
});
|
||||
|
||||
// The break this catches: the button saying Steer for a message that will wait for the next turn
|
||||
test("the send button says what will happen", () => {
|
||||
assert.equal(sendLabel(false, true), "Send");
|
||||
assert.equal(sendLabel(true, false), "Steer");
|
||||
assert.equal(sendLabel(true, true), "Queue");
|
||||
});
|
||||
87
crates/luxe-remote/app-tests/picker.test.mjs
Normal file
87
crates/luxe-remote/app-tests/picker.test.mjs
Normal file
@@ -0,0 +1,87 @@
|
||||
// What the box offers as you type, and what a pick does to the draft.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { COMMANDS } from "../app/commands.js";
|
||||
import { afterPick, pickerNote, suggestions } from "../app/picker.js";
|
||||
|
||||
/** @import { Entry, Listing } from "../app/mentions.js" */
|
||||
|
||||
/** @param {string} text */
|
||||
const at = (text) => ({ text, caret: text.length });
|
||||
/** @type {Entry} */
|
||||
const MAIN = { name: "main.rs", kind: "file" };
|
||||
/** @type {Listing} */
|
||||
const SRC = { state: "listed", entries: [{ name: "cli", kind: "directory" }, MAIN] };
|
||||
/** @type {Listing} */
|
||||
const ASKING = { state: "asking", entries: [] };
|
||||
/** @type {Listing} */
|
||||
const FAILED = { state: "failed", entries: [] };
|
||||
/** @param {string} name */
|
||||
const command = (name) => COMMANDS.find((entry) => entry.name === name);
|
||||
|
||||
// The break this catches: commands labeled without their slash, or without the TUI's title
|
||||
test("a slash offers commands, labeled as the TUI's", () => {
|
||||
const offered = suggestions(at("/co"), {});
|
||||
assert.deepEqual(offered.map((item) => [item.label, item.hint]), [["/compact", "Compact the conversation"], ["/cost", "Session cost"]]);
|
||||
});
|
||||
|
||||
// The break this catches: a folder shown like a file, so it's not clear a tap opens it
|
||||
test("a mention offers the folder's entries, folders marked with a slash", () => {
|
||||
const offered = suggestions(at("@src/"), { src: SRC });
|
||||
assert.deepEqual(offered.map((item) => item.label), ["cli/", "main.rs"]);
|
||||
});
|
||||
|
||||
// The break this catches: suggestions for a folder that hasn't been listed taken from another
|
||||
test("nothing is offered from a folder not listed yet", () => {
|
||||
assert.deepEqual(suggestions(at("@lib/"), { src: SRC }), []);
|
||||
});
|
||||
|
||||
// The break this catches: a plain message offering anything
|
||||
test("a plain message offers nothing", () => {
|
||||
assert.deepEqual(suggestions(at("hello"), { src: SRC }), []);
|
||||
});
|
||||
|
||||
// The break this catches: a command that takes words run before they're written
|
||||
test("a command that takes words goes into the box to finish", () => {
|
||||
assert.deepEqual(afterPick(at("/co"), { key: "compact", label: "", hint: "", command: command("compact") }), {
|
||||
text: "/compact ",
|
||||
caret: 9,
|
||||
placed: true,
|
||||
});
|
||||
});
|
||||
|
||||
// The break this catches: a command that takes nothing put in the box, a second tap to run it
|
||||
test("a command that takes nothing runs", () => {
|
||||
assert.equal(afterPick(at("/mo"), { key: "model", label: "", hint: "", command: command("model") }), null);
|
||||
});
|
||||
|
||||
// The break this catches: the caret not placed after the pick, so typing goes in before it
|
||||
test("a picked file replaces the mention and places the caret after it", () => {
|
||||
assert.deepEqual(afterPick(at("@src/ma"), { key: "main.rs", label: "", hint: "", entry: MAIN }), {
|
||||
text: "`src/main.rs` ",
|
||||
caret: 14,
|
||||
placed: true,
|
||||
});
|
||||
});
|
||||
|
||||
// The break this catches: a folder on its way shown as empty, which reads as no files
|
||||
test("a folder being listed says so", () => {
|
||||
assert.equal(pickerNote(at("@src/"), { src: ASKING }), "Listing files…");
|
||||
});
|
||||
|
||||
// The break this catches: an empty folder showing no picker at all, which reads as broken, or a
|
||||
// folder with files said to be empty
|
||||
test("an empty folder says so", () => {
|
||||
/** @type {Listing} */
|
||||
const empty = { state: "listed", entries: [] };
|
||||
assert.equal(pickerNote(at("@.luxe/"), { ".luxe": empty }), "No files in .luxe");
|
||||
assert.equal(pickerNote(at("@src/zz"), { src: SRC }), "");
|
||||
});
|
||||
|
||||
// The break this catches: a folder that can't be listed shown as empty, or the project root named
|
||||
// as nothing
|
||||
test("a folder that can't be listed is named", () => {
|
||||
assert.equal(pickerNote(at("@gone/"), { gone: FAILED }), "Couldn't list gone");
|
||||
assert.equal(pickerNote(at("@"), { "": FAILED }), "Couldn't list the project");
|
||||
});
|
||||
20
crates/luxe-remote/app-tests/register.mjs
Normal file
20
crates/luxe-remote/app-tests/register.mjs
Normal file
@@ -0,0 +1,20 @@
|
||||
// `node --import ./register.mjs --test`: resolves the app's bare imports through index.html's
|
||||
// import map, as the browser does, so the tests run the vendored files the phone runs rather than
|
||||
// whatever npm would find.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { registerHooks } from "node:module";
|
||||
|
||||
const app = new URL("../app/", import.meta.url);
|
||||
const page = readFileSync(new URL("index.html", app), "utf8");
|
||||
const block = /<script type="importmap">([\s\S]*?)<\/script>/.exec(page);
|
||||
if (!block) throw new Error("index.html has no import map");
|
||||
const imports = JSON.parse(block[1]).imports;
|
||||
|
||||
registerHooks({
|
||||
resolve(specifier, context, next) {
|
||||
const mapped = imports[specifier];
|
||||
if (!mapped) return next(specifier, context);
|
||||
return next(new URL(mapped.replace(/^\/app\//, ""), app).href, context);
|
||||
},
|
||||
});
|
||||
64
crates/luxe-remote/app-tests/render.test.mjs
Normal file
64
crates/luxe-remote/app-tests/render.test.mjs
Normal file
@@ -0,0 +1,64 @@
|
||||
// Asking the host for rendered text: batching, keeping, and failing.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createRenderer } from "../app/render.js";
|
||||
|
||||
/** A host that answers each piece with its own JSON, and remembers every batch it was sent. */
|
||||
function fakeHost() {
|
||||
const batches = [];
|
||||
const post = async (pieces) => {
|
||||
batches.push(pieces);
|
||||
return pieces.map((piece) => `<p>${JSON.stringify(piece)}</p>`);
|
||||
};
|
||||
return { batches, post };
|
||||
}
|
||||
|
||||
/** @param {string} text @returns {import("../app/render.js").Piece} */
|
||||
const answer = (text) => ({ kind: "answer", text });
|
||||
|
||||
// The break this catches: a request per piece, so a transcript of a hundred messages costs a
|
||||
// hundred round trips; or answers handed back by position wrongly, so one message shows another's
|
||||
test("pieces asked for together go in one request and come back to their askers", async () => {
|
||||
const host = fakeHost();
|
||||
const renderer = createRenderer(host.post);
|
||||
const [first, second] = await Promise.all([
|
||||
renderer.render(answer("one"), { keep: false }),
|
||||
renderer.render(answer("two"), { keep: false }),
|
||||
]);
|
||||
assert.equal(host.batches.length, 1);
|
||||
assert.equal(first, '<p>{"kind":"answer","text":"one"}</p>');
|
||||
assert.equal(second, '<p>{"kind":"answer","text":"two"}</p>');
|
||||
});
|
||||
|
||||
// The break this catches: finished messages asked for again on every redraw and reconnect
|
||||
test("a finished piece is kept and not asked for again", async () => {
|
||||
const host = fakeHost();
|
||||
const renderer = createRenderer(host.post);
|
||||
await renderer.render(answer("done"), { keep: true });
|
||||
const again = await renderer.render(answer("done"), { keep: true });
|
||||
assert.equal(host.batches.length, 1);
|
||||
assert.equal(again, renderer.peek(answer("done")));
|
||||
});
|
||||
|
||||
// The break this catches: every version of a streaming reply kept, which fills the cache with
|
||||
// prefixes nobody will see again
|
||||
test("a growing piece isn't kept", async () => {
|
||||
const host = fakeHost();
|
||||
const renderer = createRenderer(host.post);
|
||||
await renderer.render(answer("grow"), { keep: false });
|
||||
assert.equal(renderer.peek(answer("grow")), undefined);
|
||||
await renderer.render(answer("grow"), { keep: false });
|
||||
assert.equal(host.batches.length, 2);
|
||||
});
|
||||
|
||||
// The break this catches: a failed request leaving its askers waiting forever, so those messages
|
||||
// never fall back from plain text and never ask again
|
||||
test("a failed request fails every piece in it", async () => {
|
||||
const renderer = createRenderer(async () => {
|
||||
throw new Error("rendering failed: 502");
|
||||
});
|
||||
const asked = [renderer.render(answer("a"), { keep: true }), renderer.render(answer("b"), { keep: true })];
|
||||
for (const one of asked) await assert.rejects(one, /502/);
|
||||
assert.equal(renderer.peek(answer("a")), undefined);
|
||||
});
|
||||
211
crates/luxe-remote/app-tests/review.test.mjs
Normal file
211
crates/luxe-remote/app-tests/review.test.mjs
Normal file
@@ -0,0 +1,211 @@
|
||||
// @ts-check
|
||||
// The Review tab's state: joining the open review, loading one when none is, keeping up when any
|
||||
// client changes it, and the pieces it asks the host to draw.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { applyReview, chapterPiece, createReview, guidePiece, nextChapter, targetName, withoutLines } from "../app/review.js";
|
||||
import { tapChapter } from "../app/review-view.js";
|
||||
|
||||
/** @param {string} id @param {string} text */
|
||||
const hunk = (id, text) => ({ id, lines: [{ kind: "addition", text }] });
|
||||
|
||||
/** Two chapters: the first names one hunk of `a.rs` and all of `b.png`; the second `c.rs`'s hunk. */
|
||||
function review() {
|
||||
return {
|
||||
id: "review:1",
|
||||
target: { kind: "working_tree" },
|
||||
chapters: [
|
||||
{ id: "chapter:1", items: [{ kind: "hunk", id: "hunk:a1" }, { kind: "file", id: "file:b" }] },
|
||||
{ id: "chapter:2", items: [{ kind: "hunk", id: "hunk:c1" }] },
|
||||
],
|
||||
files: [
|
||||
{ id: "file:a", hunks: [hunk("hunk:a1", "one"), hunk("hunk:a2", "two")] },
|
||||
{ id: "file:b", hunks: [] },
|
||||
{ id: "file:c", hunks: [hunk("hunk:c1", "three")] },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** A review tab and everything it sent. */
|
||||
function tab() {
|
||||
/** @type {any[]} */
|
||||
const sent = [];
|
||||
const state = createReview();
|
||||
const send = (/** @type {any} */ frame) => sent.push(frame) > 0;
|
||||
return { state, sent, send, last: () => sent[sent.length - 1] };
|
||||
}
|
||||
|
||||
/** The answer to the last `show_open_review` sent. @param {any[]} sent @param {any} content */
|
||||
function answer(sent, content) {
|
||||
const asked = [...sent].reverse().find((frame) => frame.kind === "show_open_review");
|
||||
return { kind: "open_review_shown", content: { request_id: asked.content.request_id, ...content } };
|
||||
}
|
||||
|
||||
// The break this catches: taking another phone's answer for this one's, or ignoring this one's
|
||||
test("an answer shows only for the request that asked", () => {
|
||||
const { state, sent, send } = tab();
|
||||
state.ask(send);
|
||||
assert.equal(state.shown.value.state, "asking");
|
||||
state.apply({ kind: "open_review_shown", content: { request_id: "phone-review:show:other", review: review() } });
|
||||
assert.equal(state.shown.value.review, null);
|
||||
state.apply(answer(sent, { review: review(), reading: [{ chapter_id: "chapter:1", needs_review: 1 }] }));
|
||||
assert.equal(state.shown.value.state, "shown");
|
||||
assert.equal(state.shown.value.review?.id, "review:1");
|
||||
assert.equal(state.shown.value.reading.length, 1);
|
||||
});
|
||||
|
||||
// The break this catches: two phones asking with the same id, each taking the other's answer
|
||||
test("each ask carries an id of its own", () => {
|
||||
const { state, sent, send } = tab();
|
||||
state.ask(send);
|
||||
state.ask(send);
|
||||
assert.notEqual(sent[0].content.request_id, sent[1].content.request_id);
|
||||
});
|
||||
|
||||
// The break this catches: a review with nothing open read as still loading, so the button to
|
||||
// review the changes never shows
|
||||
test("nothing open is shown as nothing open", () => {
|
||||
const { state, sent, send } = tab();
|
||||
state.ask(send);
|
||||
state.apply(answer(sent, { review: null, session: null, reading: [] }));
|
||||
assert.deepEqual([state.shown.value.state, state.shown.value.review], ["shown", null]);
|
||||
});
|
||||
|
||||
// The break this catches: the guide's piece sent with every line of the review, or the lines
|
||||
// stripped from the review itself, leaving a chapter nothing to show
|
||||
test("the guide goes without lines and the review keeps them", () => {
|
||||
const full = review();
|
||||
const guide = withoutLines(full);
|
||||
assert.deepEqual(guide.files[0].hunks.map((/** @type {any} */ it) => [it.id, it.lines]), [["hunk:a1", []], ["hunk:a2", []]]);
|
||||
assert.equal(full.files[0].hunks[0].lines.length, 1);
|
||||
});
|
||||
|
||||
// The break this catches: progress walked on the terminal not showing here, or the guide piece
|
||||
// leaving out what it marks
|
||||
test("walked chapters come from the session and reach the guide", () => {
|
||||
const { state, sent, send } = tab();
|
||||
state.ask(send);
|
||||
state.apply(answer(sent, { review: review(), session: { progress: { walked_chapter_ids: ["chapter:2"] } } }));
|
||||
const piece = guidePiece(state.shown.value);
|
||||
assert.deepEqual([piece.kind, piece.walked, piece.review.files[2].hunks[0].lines], ["review_guide", ["chapter:2"], []]);
|
||||
});
|
||||
|
||||
// The break this catches: a review another client loaded or re-guided left stale here, or the
|
||||
// tab asking before anyone opened it
|
||||
test("a review loaded or re-guided anywhere is asked for again", () => {
|
||||
const { state, sent, send } = tab();
|
||||
state.apply({ kind: "guided_review_loaded", content: { request_id: "elsewhere" } });
|
||||
assert.equal(sent.length, 0, "not before the tab has asked");
|
||||
state.ask(send);
|
||||
state.apply(answer(sent, { review: review() }));
|
||||
state.apply({ kind: "guided_review_loaded", content: { request_id: "elsewhere" } });
|
||||
assert.equal(sent.length, 2);
|
||||
state.apply({ kind: "guided_review_guide_updated", content: {} });
|
||||
assert.equal(sent.length, 3);
|
||||
assert.equal(sent[2].kind, "show_open_review");
|
||||
});
|
||||
|
||||
// The break this catches: loading something other than the working changes, or a failure of
|
||||
// another client's load shown as this one's
|
||||
test("loading reviews the working changes and says when it fails", () => {
|
||||
const { state, sent, send, last } = tab();
|
||||
state.load(send);
|
||||
assert.deepEqual([last().kind, last().content.target], ["load_guided_review", { kind: "working_tree" }]);
|
||||
assert.equal(state.shown.value.state, "loading");
|
||||
state.apply({ kind: "guided_review_failed", content: { request_id: "elsewhere", error: { message: "no" } } });
|
||||
assert.equal(state.shown.value.state, "loading");
|
||||
state.apply({ kind: "guided_review_failed", content: { request_id: sent[0].content.request_id, error: { message: "Not a repository" } } });
|
||||
assert.deepEqual([state.shown.value.state, state.shown.value.error], ["failed", "Not a repository"]);
|
||||
});
|
||||
|
||||
// The break this catches: a lost connection leaving "Loading…" up forever, or a shown review
|
||||
// thrown away when the connection comes back
|
||||
test("a new connection loses only what was waiting", () => {
|
||||
const asking = tab();
|
||||
asking.state.ask(asking.send);
|
||||
asking.state.apply({ kind: "ready", content: {} });
|
||||
assert.equal(asking.state.shown.value.state, "lost");
|
||||
const shown = tab();
|
||||
shown.state.ask(shown.send);
|
||||
shown.state.apply(answer(shown.sent, { review: review() }));
|
||||
shown.state.apply({ kind: "ready", content: {} });
|
||||
assert.equal(shown.state.shown.value.state, "shown");
|
||||
});
|
||||
|
||||
// The break this catches: a send that didn't go read as asking, so the tab waits on nothing
|
||||
test("an ask that couldn't be sent is lost", () => {
|
||||
const state = createReview();
|
||||
state.ask(() => false);
|
||||
assert.equal(state.shown.value.state, "lost");
|
||||
});
|
||||
|
||||
// The break this catches: a chapter from a replaced review left open, or the open one closed by a
|
||||
// fresh answer for the same review
|
||||
test("a chapter stays open only while the review has it", () => {
|
||||
const { state, sent, send } = tab();
|
||||
state.ask(send);
|
||||
state.apply(answer(sent, { review: review() }));
|
||||
state.pick("chapter:2");
|
||||
state.apply(answer(sent, { review: review() }));
|
||||
assert.equal(state.open.value, "chapter:2");
|
||||
const other = { ...review(), chapters: [{ id: "chapter:9", items: [] }] };
|
||||
state.apply(answer(sent, { review: other }));
|
||||
assert.equal(state.open.value, null);
|
||||
});
|
||||
|
||||
// The break this catches: marking a chapter sending only that one (the session keeps the list it's
|
||||
// sent, so the others would be unwalked), or unmarking doing nothing
|
||||
test("marking a chapter reviewed sends every chapter walked, and unmarks", () => {
|
||||
const { state, sent, send, last } = tab();
|
||||
state.ask(send);
|
||||
state.apply(answer(sent, { review: review(), session: { progress: { walked_chapter_ids: ["chapter:2"] } } }));
|
||||
state.walk("chapter:1", send);
|
||||
assert.deepEqual(last(), { kind: "record_review_progress", content: { review_id: "review:1", walked_chapter_ids: ["chapter:2", "chapter:1"] } });
|
||||
state.walk("chapter:2", send);
|
||||
assert.deepEqual(last().content.walked_chapter_ids, ["chapter:1"]);
|
||||
assert.deepEqual(state.shown.value.walked, ["chapter:1"]);
|
||||
});
|
||||
|
||||
// The break this catches: a chapter's piece carrying the whole review, a hunk from another
|
||||
// chapter, or the wrong place in the list
|
||||
test("a chapter's piece holds only its files and hunks", () => {
|
||||
const shown = /** @type {any} */ ({ review: review(), reading: [{ chapter_id: "chapter:1", needs_review: 2 }], walked: ["chapter:1"] });
|
||||
const piece = chapterPiece(shown, "chapter:1");
|
||||
assert.deepEqual(piece.files.map((/** @type {any} */ file) => [file.id, file.hunks.map((/** @type {any} */ it) => it.id)]), [["file:a", ["hunk:a1"]], ["file:b", []]]);
|
||||
assert.deepEqual(piece.place, { number: 1, total: 2, walked: true });
|
||||
assert.equal(piece.reading?.needs_review, 2);
|
||||
assert.equal(chapterPiece(shown, "chapter:2").reading, null);
|
||||
});
|
||||
|
||||
// The break this catches: Next skipping a chapter, or offered past the last one
|
||||
test("next is the chapter after, and nothing after the last", () => {
|
||||
assert.equal(nextChapter(review(), "chapter:1"), "chapter:2");
|
||||
assert.equal(nextChapter(review(), "chapter:2"), null);
|
||||
});
|
||||
|
||||
// The break this catches: every review called the same thing, so the tab can't say what it's of
|
||||
test("a review says what it's of", () => {
|
||||
assert.equal(targetName({ kind: "working_tree" }), "Working changes");
|
||||
assert.equal(targetName({ kind: "pull_request", number: 230 }), "Pull request #230");
|
||||
assert.equal(targetName({ kind: "commit", oid: "842ffb60c0ffee" }), "Commit 842ffb60");
|
||||
assert.equal(targetName({ kind: "base", reference: "main" }), "Changes since main");
|
||||
});
|
||||
|
||||
// The break this catches: a chapter tap leaving a file or pull request in the pane, or a tap
|
||||
// between chapters opening something
|
||||
test("tapping a chapter opens it in place of the other panes", () => {
|
||||
const closed = /** @type {string[]} */ ([]);
|
||||
const state = createReview();
|
||||
const hooks = /** @type {any} */ ({ review: state, files: { close: () => closed.push("file") }, github: { close: () => closed.push("item") } });
|
||||
const event = (/** @type {any} */ found) => /** @type {any} */ ({ target: { closest: () => found } });
|
||||
tapChapter(event(null), hooks);
|
||||
assert.deepEqual([state.open.value, closed], [null, []]);
|
||||
tapChapter(event({ dataset: { chapter: "chapter:2" } }), hooks);
|
||||
assert.deepEqual([state.open.value, closed], ["chapter:2", ["file", "item"]]);
|
||||
});
|
||||
|
||||
// The break this catches: a frame for nothing this tab asked changing it
|
||||
test("other frames leave the tab alone", () => {
|
||||
const shown = /** @type {any} */ ({ state: "shown", review: null, guide: null, reading: [], walked: [] });
|
||||
assert.deepEqual(applyReview(shown, { kind: "turn_started", content: {} }, { id: "a", load: "b" }), { next: shown, again: false });
|
||||
});
|
||||
73
crates/luxe-remote/app-tests/service-worker.test.mjs
Normal file
73
crates/luxe-remote/app-tests/service-worker.test.mjs
Normal file
@@ -0,0 +1,73 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import vm from "node:vm";
|
||||
|
||||
const source = readFileSync(new URL("../app/worker/service-worker.js", import.meta.url), "utf8");
|
||||
|
||||
/** Runs the worker against a stand-in for the browser, with `windows` open. */
|
||||
function worker(windows = []) {
|
||||
const listeners = {};
|
||||
const shown = [];
|
||||
const opened = [];
|
||||
const self = {
|
||||
addEventListener: (type, listener) => (listeners[type] = listener),
|
||||
registration: { showNotification: async (title, options) => shown.push({ title, options }) },
|
||||
clients: { matchAll: async () => windows, openWindow: async (url) => opened.push(url) },
|
||||
};
|
||||
vm.runInNewContext(source, { self });
|
||||
const fire = async (type, event) => {
|
||||
let pending;
|
||||
listeners[type]({ ...event, waitUntil: (promise) => (pending = promise) });
|
||||
await pending;
|
||||
};
|
||||
return { fire, shown, opened };
|
||||
}
|
||||
|
||||
// objects made in the worker's context have its own Object, which strict equality tells apart
|
||||
const plain = (value) => JSON.parse(JSON.stringify(value));
|
||||
|
||||
const push = (payload) => ({ data: { json: () => (typeof payload === "string" ? JSON.parse(payload) : payload) } });
|
||||
|
||||
// The break this catches: a notice shown without its folder or what's waiting, or with the
|
||||
// session it should open lost.
|
||||
test("a push shows what the bridge sent", async () => {
|
||||
const { fire, shown } = worker();
|
||||
await fire("push", push({ title: "luxe-dev", body: "Approve bash", session: "s-1" }));
|
||||
const options = { body: "Approve bash", icon: "/icons/192.png", data: { session: "s-1" } };
|
||||
assert.deepEqual(plain(shown), [{ title: "luxe-dev", options }]);
|
||||
});
|
||||
|
||||
// The break this catches: a push that shows nothing, which iOS answers by ending the subscription.
|
||||
test("a push it can't read still shows a notification", async () => {
|
||||
const { fire, shown } = worker();
|
||||
await fire("push", push("not json"));
|
||||
await fire("push", { data: null });
|
||||
assert.deepEqual(shown.map((notice) => notice.title), ["Luxe", "Luxe"]);
|
||||
});
|
||||
|
||||
const click = (session) => {
|
||||
const closed = [];
|
||||
return { closed, event: { notification: { data: { session }, close: () => closed.push(true) } } };
|
||||
};
|
||||
|
||||
// The break this catches: a tap that opens the app's list instead of the session, or opens nothing
|
||||
// when the app isn't running.
|
||||
test("a tap with the app closed opens it on the session", async () => {
|
||||
const { fire, opened } = worker();
|
||||
const { closed, event } = click("s 1");
|
||||
await fire("notificationclick", event);
|
||||
assert.deepEqual(opened, ["/#/session/s%201"]);
|
||||
assert.deepEqual(closed, [true]);
|
||||
});
|
||||
|
||||
// The break this catches: a second copy of the app opened beside the first, or the open one
|
||||
// brought forward without being told which session to show.
|
||||
test("a tap with the app open brings it forward on the session", async () => {
|
||||
const told = [];
|
||||
const open = { focus: async () => told.push("focus"), postMessage: (message) => told.push(message) };
|
||||
const { fire, opened } = worker([open]);
|
||||
await fire("notificationclick", click("s-1").event);
|
||||
assert.deepEqual(plain(told), ["focus", { kind: "open_session", session: "s-1" }]);
|
||||
assert.deepEqual(opened, []);
|
||||
});
|
||||
39
crates/luxe-remote/app-tests/status.test.mjs
Normal file
39
crates/luxe-remote/app-tests/status.test.mjs
Normal file
@@ -0,0 +1,39 @@
|
||||
// The status line's facts, folded from frames, and the mode switch.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createStatus, nextModeFrame } from "../app/status.js";
|
||||
|
||||
const frame = (kind, content) => ({ kind, content });
|
||||
const model = { provider: "github-copilot", model: "claude-haiku-4.5", display_name: "Claude Haiku 4.5 (latest)" };
|
||||
|
||||
// The break this catches: each frame replacing the facts rather than adding to them, so a
|
||||
// thinking change wipes the context reading until the next call reports it again
|
||||
test("each frame updates its own facts and keeps the rest", () => {
|
||||
const status = createStatus();
|
||||
status.apply(frame("context_usage", { used_tokens: 9613, context_window: 200000 }));
|
||||
status.apply(frame("state_changed", { model, streaming: false, mode: "plan", thinking: "high" }));
|
||||
assert.deepEqual(status.facts.value, {
|
||||
context: { used_tokens: 9613, context_window: 200000 },
|
||||
model,
|
||||
thinking: "high",
|
||||
});
|
||||
assert.equal(status.mode.value, "plan");
|
||||
});
|
||||
|
||||
// The break this catches: the plan's allowance or the session's spend never reaching the host,
|
||||
// so the cost slot stays empty; the spend goes as its total, which is all the line shows
|
||||
test("the plan and the spend are kept for the cost slot", () => {
|
||||
const status = createStatus();
|
||||
const plan = { plan: "individual", primary: { used_percent: 22.3, window_minutes: 43200 } };
|
||||
const total = { calls: 14, cost_usd: 0, unpriced_calls: 0, plan_usd: 0.045, plan_calls: 14 };
|
||||
status.apply(frame("plan_usage", plan));
|
||||
status.apply(frame("session_usage", { total, by_source: [{ source: "agent", totals: total }] }));
|
||||
assert.deepEqual(status.facts.value, { plan, session: { total } });
|
||||
});
|
||||
|
||||
// The break this catches: the mode switch sending the mode already on, so a tap does nothing
|
||||
test("a tap on the mode switches to the other one", () => {
|
||||
assert.deepEqual(nextModeFrame("build"), { kind: "set_mode", content: "plan" });
|
||||
assert.deepEqual(nextModeFrame("plan"), { kind: "set_mode", content: "build" });
|
||||
});
|
||||
220
crates/luxe-remote/app-tests/transcript.test.mjs
Normal file
220
crates/luxe-remote/app-tests/transcript.test.mjs
Normal file
@@ -0,0 +1,220 @@
|
||||
// The transcript fold, against a real recorded session and against one frame at a time.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
import { WINDOW, elapsed, windowOf } from "../app/items.js";
|
||||
import { createTranscript, formatTokens } from "../app/transcript.js";
|
||||
|
||||
/** A session joined through the bridge: the snapshot, then a live turn with two tool calls. */
|
||||
const recorded = readFileSync(new URL("fixtures/turn.jsonl", import.meta.url), "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
|
||||
function fold(frames) {
|
||||
const transcript = createTranscript();
|
||||
frames.forEach(transcript.apply);
|
||||
return transcript;
|
||||
}
|
||||
|
||||
function shape(transcript) {
|
||||
return transcript.items.value.map((item) => {
|
||||
if (item.card) return `tool ${item.card.value.name} ${item.card.value.state}`;
|
||||
return `${item.kind}${item.provisional ? " (streaming)" : ""}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** @import { Item, TextItem, ToolItem } from "../app/transcript.js" */
|
||||
|
||||
/** `item`, which the test expects to be text. @param {Item} item @returns {TextItem} */
|
||||
function asText(item) {
|
||||
assert.ok(item.kind !== "tool", `${item.key} is a tool card`);
|
||||
return item;
|
||||
}
|
||||
|
||||
/** `item`, which the test expects to be a tool card. @param {Item} item @returns {ToolItem} */
|
||||
function asTool(item) {
|
||||
assert.ok(item.kind === "tool", `${item.key} isn't a tool card`);
|
||||
return item;
|
||||
}
|
||||
|
||||
const frame = (kind, content) => ({ kind, content });
|
||||
const reply = (...content) => frame("message_committed", { message: { role: "assistant", content } });
|
||||
const card = (revision, state) =>
|
||||
frame("tool_activity_updated", { call_id: "c1", name: "bash", label: "ls", state, revision });
|
||||
|
||||
// The break this catches: a photo's bytes kept for the render request, sent back to the host on
|
||||
// every redraw; or the blocks that aren't text dropped, which moves hook context to block 0, where
|
||||
// the host reads it as the reader's own words
|
||||
test("a user message keeps its blocks for rendering, an image as just its type", () => {
|
||||
const image = { type: "image", content: { media_type: "image/png", data: "iVBORw0KGgo=" } };
|
||||
const words = { type: "text", content: "what's this?" };
|
||||
const message = { role: "user", content: [image, words] };
|
||||
const transcript = fold([frame("message_committed", { message })]);
|
||||
const item = asText(transcript.items.value[0]);
|
||||
assert.equal(item.text.value, "what's this?");
|
||||
assert.deepEqual(item.content, [{ type: "image" }, words]);
|
||||
});
|
||||
|
||||
// The break this catches: a commit that adds the saved reply beside the streamed one, so every
|
||||
// answer shows twice; or a turn whose question never arrives, so the phone shows answers alone.
|
||||
test("a recorded turn folds into what the TUI shows", () => {
|
||||
const items = shape(fold(recorded));
|
||||
const lastTurn = items.slice(items.lastIndexOf("user"));
|
||||
assert.deepEqual(lastTurn, ["user", "thinking", "tool bash succeeded", "tool read succeeded", "assistant"]);
|
||||
assert.equal(items.filter((item) => item === "user").length, 4);
|
||||
});
|
||||
|
||||
// The break this catches: lining blocks up by position whatever their kind, so the saved
|
||||
// reasoning lands in the reply's place and the reply goes missing.
|
||||
test("streamed blocks that don't match the saved ones are replaced by them", () => {
|
||||
const transcript = fold([
|
||||
frame("token_delta", { block: 0, delta: "Hel" }),
|
||||
reply({ type: "thinking", content: { text: "why", signature: "" } }, { type: "text", content: "Hello" }),
|
||||
]);
|
||||
assert.deepEqual(shape(transcript), ["thinking", "assistant"]);
|
||||
assert.deepEqual(transcript.items.value.map((item) => asText(item).text.value), ["why", "Hello"]);
|
||||
});
|
||||
|
||||
// The break this catches: swapping a streamed reply for a new item on commit, which redraws it,
|
||||
// so a long answer flickers and the page jumps as it finishes.
|
||||
test("streamed blocks that match keep their place and take the saved text", () => {
|
||||
const transcript = fold([
|
||||
frame("token_delta", { block: 0, delta: "Hello wor" }),
|
||||
]);
|
||||
const streamed = asText(transcript.items.value[0]);
|
||||
transcript.apply(reply({ type: "text", content: "Hello world\n\n" }));
|
||||
assert.equal(transcript.items.value[0], streamed);
|
||||
assert.equal(streamed.text.value, "Hello world");
|
||||
assert.deepEqual(shape(transcript), ["assistant"]);
|
||||
});
|
||||
|
||||
// The break this catches: a rejoin, which replays the snapshot, adding the whole history again
|
||||
// under what is already there.
|
||||
test("joining again starts the transcript over", () => {
|
||||
const once = shape(fold(recorded)).length;
|
||||
assert.equal(shape(fold([...recorded, ...recorded])).length, once);
|
||||
});
|
||||
|
||||
// The break this catches: taking whatever card update arrives last, so a late, older update puts a
|
||||
// finished call back to running.
|
||||
test("an older card update doesn't undo a newer one", () => {
|
||||
assert.deepEqual(shape(fold([card(3, "succeeded"), card(2, "running")])), ["tool bash succeeded"]);
|
||||
});
|
||||
|
||||
// The break this catches: a call the session never finished showing as running forever.
|
||||
test("a call without a result when the session loads shows as interrupted", () => {
|
||||
const call = { type: "tool_call", content: { id: "c1", name: "bash", arguments: { command: "make" } } };
|
||||
const loaded = frame("session_loaded", { messages: [{ message: { role: "assistant", content: [call] } }] });
|
||||
assert.deepEqual(shape(fold([loaded])), ["tool bash interrupted"]);
|
||||
});
|
||||
|
||||
// The break this catches: reading every saved result as a success, so a failed call looks fine.
|
||||
test("a saved result settles its card, failures as failures", () => {
|
||||
const call = { type: "tool_call", content: { id: "c1", name: "bash", arguments: { command: "make" } } };
|
||||
const result = {
|
||||
type: "tool_result",
|
||||
content: { call_id: "c1", content: [{ type: "text", content: "no rule" }], is_error: true },
|
||||
};
|
||||
const loaded = frame("session_loaded", {
|
||||
messages: [{ message: { role: "assistant", content: [call] } }, { message: { role: "tool", content: [result] } }],
|
||||
});
|
||||
const transcript = fold([loaded]);
|
||||
assert.deepEqual(shape(transcript), ["tool bash failed"]);
|
||||
assert.equal(asTool(transcript.items.value[0]).card.value.output_preview, "no rule");
|
||||
});
|
||||
|
||||
// The break this catches: a frame the host refused vanishing, so a reply or a message sent from
|
||||
// the phone seems to go nowhere
|
||||
test("a refused action shows as an error, with the host's reason", () => {
|
||||
const transcript = fold([frame("action_rejected", { kind: "respond_permission", reason: "no such prompt" })]);
|
||||
assert.deepEqual(shape(transcript), ["error"]);
|
||||
assert.match(asText(transcript.items.value[0]).text.value, /no such prompt/);
|
||||
});
|
||||
|
||||
// The break this catches: the composer never offering to steer, since the engine announces no
|
||||
// turn's start; or a turn kept running after it ended, so a new message is sent as steering
|
||||
test("a turn runs from its first sign until it ends", () => {
|
||||
const transcript = createTranscript();
|
||||
const user = frame("message_committed", { message: { role: "user", content: [{ type: "text", content: "hi" }] } });
|
||||
/** @type {[import("../app/connection.js").Frame, boolean][]} */
|
||||
const steps = [
|
||||
[user, true],
|
||||
[frame("turn_ended", { reason: "end_turn" }), false],
|
||||
[frame("thinking_delta", { block: 0, delta: "hm" }), true],
|
||||
[frame("error", "provider down"), false],
|
||||
[frame("tool_call_composing", { call_id: "c", name: "bash" }), true],
|
||||
[frame("state_changed", { streaming: false }), false],
|
||||
[frame("token_delta", { block: 0, delta: "a" }), true],
|
||||
[frame("turn_ended", { reason: "end_turn" }), false],
|
||||
[frame("turn_started"), true],
|
||||
];
|
||||
for (const [step, busy] of steps) {
|
||||
transcript.apply(step);
|
||||
assert.equal(transcript.busy.value, busy, step.kind);
|
||||
}
|
||||
});
|
||||
|
||||
// The break this catches: a photo sent with no words dropped from the conversation, or its bytes
|
||||
// kept in what's sent to the host to render
|
||||
test("a photo sent on its own is still a message", () => {
|
||||
const photo = { role: "user", content: [{ type: "image", content: { data: "QUJD", mime: "image/jpeg" } }] };
|
||||
const transcript = fold([frame("message_committed", { message: photo })]);
|
||||
assert.deepEqual(shape(transcript), ["user"]);
|
||||
assert.deepEqual(asText(transcript.items.value[0]).content, [{ type: "image" }]);
|
||||
});
|
||||
|
||||
// The break this catches: a hook's note, committed between turns, taken for a turn starting
|
||||
test("a system message doesn't start a turn", () => {
|
||||
const note = { role: "system", content: [{ type: "text", content: "hook says hi" }] };
|
||||
assert.equal(fold([frame("message_committed", { message: note })]).busy.value, false);
|
||||
});
|
||||
|
||||
/** The text of each of `transcript`'s lines. */
|
||||
const texts = (transcript) => transcript.items.value.map((item) => asText(item).text.value);
|
||||
|
||||
// The break this catches: a minute of summary with nothing on the phone to say so, or a second
|
||||
// line added beside the first when it's done
|
||||
test("a compaction shows as it starts, and its line becomes the result", () => {
|
||||
const transcript = fold([frame("compaction_started", { tokens_before: 579_400 })]);
|
||||
assert.deepEqual(texts(transcript), ["Compacting the conversation — 579.4k of context…"]);
|
||||
transcript.apply(frame("compaction_done", { tokens_before: 579_400, tokens_after: 28_700 }));
|
||||
assert.deepEqual(texts(transcript), ["Compacted the conversation — 579.4k → 28.7k of context."]);
|
||||
});
|
||||
|
||||
// The break this catches: "Compacting…" left standing after a cancel or failure, or the end
|
||||
// written onto whatever line came last rather than the one that announced it
|
||||
test("a stopped compaction settles the line that announced it", () => {
|
||||
const started = frame("compaction_started", { tokens_before: 1000 });
|
||||
const transcript = fold([started, frame("notice", "between"), frame("compaction_stopped")]);
|
||||
assert.deepEqual(texts(transcript), ["Compaction stopped.", "between"]);
|
||||
});
|
||||
|
||||
// The break this catches: the phone writing a count differently from the TUI beside it.
|
||||
test("token counts read as the TUI writes them", () => {
|
||||
assert.deepEqual([812, 1000, 579_400, 1_240_000].map(formatTokens), ["812", "1.0k", "579.4k", "1.2M"]);
|
||||
});
|
||||
|
||||
// The break this catches: a long session drawing every item it ever had, which in WebKit slows
|
||||
// each keystroke past 100ms, or the window dropping the newest items rather than the oldest
|
||||
test("a long transcript draws its latest items and says how many wait above", () => {
|
||||
const items = Array.from({ length: WINDOW + 5 }, (_, index) => index);
|
||||
const { hidden, drawn } = windowOf(items, WINDOW);
|
||||
assert.equal(hidden, 5);
|
||||
assert.equal(drawn.length, WINDOW);
|
||||
assert.deepEqual([drawn[0], drawn.at(-1)], [5, WINDOW + 4]);
|
||||
});
|
||||
|
||||
// The break this catches: a short session losing its first items to the window, or told there's
|
||||
// history above that isn't there
|
||||
test("a transcript that fits is drawn whole", () => {
|
||||
const items = [1, 2, 3];
|
||||
assert.deepEqual(windowOf(items, WINDOW), { hidden: 0, drawn: items });
|
||||
assert.deepEqual(windowOf(items, 3), { hidden: 0, drawn: items });
|
||||
});
|
||||
|
||||
// The break this catches: a duration written differently from the TUI's card beside it.
|
||||
test("durations read as the TUI writes them", () => {
|
||||
assert.deepEqual([0.4, 19, 1500, 63000].map(elapsed), ["<1ms", "19ms", "1.5s", "1m 3s"]);
|
||||
});
|
||||
24
crates/luxe-remote/app-tests/tsconfig.json
Normal file
24
crates/luxe-remote/app-tests/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
// Type-checks the phone app from its JSDoc; nothing is emitted, since the app ships as written.
|
||||
// The vendored libraries resolve to the same versions installed here, whose declarations stand in
|
||||
// for the minified files the browser runs. The tests have their own, looser, tsconfig.tests.json.
|
||||
"compilerOptions": {
|
||||
"target": "es2022",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["es2023", "dom", "dom.iterable"],
|
||||
"types": [],
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"paths": {
|
||||
"preact": ["./node_modules/preact"],
|
||||
"preact/hooks": ["./node_modules/preact/hooks"],
|
||||
"htm": ["./node_modules/htm"],
|
||||
"@preact/signals": ["./node_modules/@preact/signals"]
|
||||
}
|
||||
},
|
||||
"include": ["../app/*.js"]
|
||||
}
|
||||
11
crates/luxe-remote/app-tests/tsconfig.tests.json
Normal file
11
crates/luxe-remote/app-tests/tsconfig.tests.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
// The tests, checked against the app's types: a call with the wrong shape fails here, while a
|
||||
// fixture or a callback needs no annotation, since an assertion already catches what a null
|
||||
// check would.
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"],
|
||||
"strict": false
|
||||
},
|
||||
"include": ["../app/*.js", "*.mjs", "e2e/*.mjs"]
|
||||
}
|
||||
15
crates/luxe-remote/app-tests/tsconfig.worker.json
Normal file
15
crates/luxe-remote/app-tests/tsconfig.worker.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
// Type-checks the service worker, which runs with the worker globals rather than a page's.
|
||||
"compilerOptions": {
|
||||
"target": "es2022",
|
||||
"module": "esnext",
|
||||
"lib": ["es2023", "webworker"],
|
||||
"types": [],
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"noEmit": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["../app/worker/*.js"]
|
||||
}
|
||||
17
crates/luxe-remote/app-tests/vendor.test.mjs
Normal file
17
crates/luxe-remote/app-tests/vendor.test.mjs
Normal file
@@ -0,0 +1,17 @@
|
||||
// The libraries installed here only lend their type declarations to the check of the vendored
|
||||
// files the phone runs, so the two have to be the same versions.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
|
||||
const read = (path) => JSON.parse(readFileSync(new URL(path, import.meta.url), "utf8"));
|
||||
|
||||
// The break this catches: `scripts/remote-vendor.sh` moving Preact on while package.json stays
|
||||
// behind (or a bump here alone), so the app is checked against an API it doesn't run
|
||||
test("the type packages are the vendored versions", () => {
|
||||
const installed = read("package.json").devDependencies;
|
||||
for (const { package: name, version } of read("../app/vendor/manifest.json")) {
|
||||
assert.equal(installed[name], version, `${name} in package.json`);
|
||||
}
|
||||
});
|
||||
47
crates/luxe-remote/app-tests/viewport.test.mjs
Normal file
47
crates/luxe-remote/app-tests/viewport.test.mjs
Normal file
@@ -0,0 +1,47 @@
|
||||
// Keeping iOS from zooming into a focused field, and nothing else from pinching.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { holdFieldZoom, isAppleTouch } from "../app/viewport.js";
|
||||
|
||||
const IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15";
|
||||
const MAC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15";
|
||||
const ANDROID = "Mozilla/5.0 (Linux; Android 15; Pixel 9) AppleWebKit/537.36 Chrome/139.0";
|
||||
const START = "width=device-width, initial-scale=1, viewport-fit=cover";
|
||||
|
||||
/** A page with one viewport tag, and what it says after `holdFieldZoom`. */
|
||||
function zoomHeldOn(device, content = START) {
|
||||
const viewport = { content };
|
||||
const page = { querySelector: (selector) => (selector === 'meta[name="viewport"]' ? viewport : null) };
|
||||
holdFieldZoom(/** @type {any} */ (page), /** @type {any} */ (device));
|
||||
return viewport.content;
|
||||
}
|
||||
|
||||
// The break this catches: the iPhone's own name missed, so every field zooms the page on focus
|
||||
test("an iPhone is an Apple touch device", () => {
|
||||
assert.equal(isAppleTouch({ userAgent: IPHONE, platform: "iPhone", maxTouchPoints: 5 }), true);
|
||||
});
|
||||
|
||||
// The break this catches: an iPad, which names itself a Mac, taken for one, so its fields zoom
|
||||
test("an iPad is told from a Mac by its touch screen", () => {
|
||||
assert.equal(isAppleTouch({ userAgent: MAC, platform: "MacIntel", maxTouchPoints: 5 }), true);
|
||||
assert.equal(isAppleTouch({ userAgent: MAC, platform: "MacIntel", maxTouchPoints: 0 }), false);
|
||||
});
|
||||
|
||||
// The break this catches: the hold applied everywhere, which stops Android from pinching at all
|
||||
test("Android is left able to pinch", () => {
|
||||
const device = { userAgent: ANDROID, platform: "Linux armv8l", maxTouchPoints: 5 };
|
||||
assert.equal(zoomHeldOn(device), START);
|
||||
});
|
||||
|
||||
// The break this catches: the hold left out of the viewport tag on iOS, so a field still zooms
|
||||
test("iOS gets maximum-scale added to the viewport", () => {
|
||||
const device = { userAgent: IPHONE, platform: "iPhone", maxTouchPoints: 5 };
|
||||
assert.equal(zoomHeldOn(device), `${START}, maximum-scale=1`);
|
||||
});
|
||||
|
||||
// The break this catches: a second run adding the setting again, which a reload or a test would do
|
||||
test("the hold is added once", () => {
|
||||
const device = { userAgent: IPHONE, platform: "iPhone", maxTouchPoints: 5 };
|
||||
assert.equal(zoomHeldOn(device, `${START}, maximum-scale=1`), `${START}, maximum-scale=1`);
|
||||
});
|
||||
53
crates/luxe-remote/app-tests/wordmark.test.mjs
Normal file
53
crates/luxe-remote/app-tests/wordmark.test.mjs
Normal file
@@ -0,0 +1,53 @@
|
||||
// The wordmark, read from the file the terminal's art generates.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
import { driftPhase, loadWordmark, readDrawing } from "../app/wordmark.js";
|
||||
|
||||
const GENERATED = readFileSync(new URL("../app/generated/wordmark.svg", import.meta.url), "utf8");
|
||||
|
||||
// The break this catches: a letter, the box or the drift's depth lost between the generated file
|
||||
// and the page, which draws a mark missing a letter or swinging by nothing
|
||||
test("the generated wordmark gives its box, its depth and every letter", () => {
|
||||
const drawing = readDrawing(GENERATED);
|
||||
assert.equal(drawing.viewBox, "0 0 440 154");
|
||||
assert.equal(drawing.depth, "0.55");
|
||||
assert.equal(drawing.paths.length, 5);
|
||||
assert.ok(drawing.paths.every((d) => d.startsWith("M")), "each path is geometry, not a fill");
|
||||
});
|
||||
|
||||
// The break this catches: a file without the depth drawn anyway, its letters never moving
|
||||
test("a file without the drift's depth isn't drawn", () => {
|
||||
assert.equal(readDrawing(GENERATED.replace(/ data-drift-depth="[^"]+"/, "")), null);
|
||||
});
|
||||
|
||||
// The break this catches: a file with no letters drawn as an empty box where the name was
|
||||
test("a file without letters isn't drawn", () => {
|
||||
assert.equal(readDrawing(GENERATED.replace(/<path[^>]*>/g, "")), null);
|
||||
});
|
||||
|
||||
// The break this catches: the letters in step, which pulses the whole mark, or spread over a whole
|
||||
// swing, which makes it symmetrical about its middle the way the terminal's never is
|
||||
test("half a swing is spread from the first letter to the last", () => {
|
||||
assert.equal(driftPhase(0, 5), -1);
|
||||
assert.equal(driftPhase(4, 5), -0.5);
|
||||
assert.equal(driftPhase(2, 5), -0.75);
|
||||
});
|
||||
|
||||
// The break this catches: a one-letter mark dividing by nothing and losing its animation to NaN
|
||||
test("a single letter still has a phase", () => {
|
||||
assert.equal(driftPhase(0, 1), -1);
|
||||
});
|
||||
|
||||
// The break this catches: the drawing asked for somewhere the bridge doesn't serve it, or a
|
||||
// refusal taken for a drawing
|
||||
test("the wordmark is read from the app's generated folder", async () => {
|
||||
const asked = [];
|
||||
const get = async (url) => {
|
||||
asked.push(url);
|
||||
return new Response("missing", { status: 404 });
|
||||
};
|
||||
await assert.rejects(loadWordmark(get), { message: "the wordmark answered 404" });
|
||||
assert.deepEqual(asked, ["/app/generated/wordmark.svg"]);
|
||||
});
|
||||
116
crates/luxe-remote/app-tests/workspace.test.mjs
Normal file
116
crates/luxe-remote/app-tests/workspace.test.mjs
Normal file
@@ -0,0 +1,116 @@
|
||||
// The dock's state: what `workspace_updated` says, and the one diff open.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createWorkspace, diffRequest, hasDock, planScroll } from "../app/workspace.js";
|
||||
|
||||
/** Ten todos a line (10px) each, in `statuses` order, then pending. @param {string[]} statuses */
|
||||
const plan = (...statuses) => Array.from({ length: 10 }, (_, index) => ({ bottom: (index + 1) * 10, status: statuses[index] ?? "pending" }));
|
||||
|
||||
// The break this catches: a long plan scrolled to its end, or left at the top with the work in
|
||||
// hand below the box, or the follow keeping no lookahead, so the next todo is always out of view
|
||||
test("a long plan keeps the todo in hand and the next two in view", () => {
|
||||
const statuses = ["completed", "completed", "completed", "completed", "completed", "in-progress"];
|
||||
assert.equal(planScroll(plan(...statuses), 40), 40, "rows 6 to 8 end at 80, so 40 above a 40px box");
|
||||
});
|
||||
|
||||
// The break this catches: a short plan or one barely begun scrolled away from its first rows
|
||||
test("a plan whose work in hand fits stays at the top", () => {
|
||||
assert.equal(planScroll(plan("in-progress"), 40), 0);
|
||||
assert.equal(planScroll([], 40), 0);
|
||||
});
|
||||
|
||||
// The break this catches: a plan with nothing in progress following nothing, or following a done
|
||||
// todo, so the next thing to do isn't what shows
|
||||
test("with nothing in progress, the plan follows the first todo not done, then the last", () => {
|
||||
assert.equal(planScroll(plan("completed", "completed", "completed", "completed"), 40), 30);
|
||||
assert.equal(planScroll(plan(...Array(10).fill("completed")), 40), 60);
|
||||
});
|
||||
|
||||
// A `workspace_updated` frame's todos and changes, cut down from a live session
|
||||
const TODOS = { current: null, items: [{ id: "1", subject: "Read the notes", status: "completed", blocked_by: [] }], pending: 0, in_progress: 0, completed: 1, blocked: 0, total: 1, truncated: false };
|
||||
const CHANGES = { files: [{ path: "notes.txt", status: "added", additions: 1, deletions: 0, binary: false }], total_files: 1, additions: 1, deletions: 0, truncated: false };
|
||||
const DIFF = { path: "notes.txt", file: null, untracked: false };
|
||||
|
||||
const frame = (kind, content) => ({ kind, content });
|
||||
|
||||
function opened(path = "notes.txt") {
|
||||
const workspace = createWorkspace();
|
||||
const request = diffRequest(path);
|
||||
workspace.opened(request);
|
||||
return { workspace, id: request.content.request_id };
|
||||
}
|
||||
|
||||
// The break this catches: the dock left on the first snapshot, or todos and changes crossed
|
||||
test("the latest snapshot is what the dock shows", () => {
|
||||
const workspace = createWorkspace();
|
||||
workspace.apply(frame("workspace_updated", { todos: { total: 0 }, changes: { total_files: 0 } }));
|
||||
workspace.apply(frame("workspace_updated", { todos: TODOS, changes: CHANGES }));
|
||||
assert.equal(workspace.todos.value, TODOS);
|
||||
assert.equal(workspace.changes.value, CHANGES);
|
||||
});
|
||||
|
||||
// The break this catches: the project panel's branch left on the first snapshot, so a checkout or
|
||||
// a commit never shows
|
||||
test("the latest snapshot's project is the one the panel names", () => {
|
||||
const workspace = createWorkspace();
|
||||
const project = (branch, dirty) => ({ display_name: "luxe", git_branch: branch, git_dirty: dirty });
|
||||
workspace.apply(frame("workspace_updated", { todos: TODOS, changes: CHANGES, project: project("main", true) }));
|
||||
workspace.apply(frame("workspace_updated", { todos: TODOS, changes: CHANGES, project: project("remote-access", false) }));
|
||||
assert.deepEqual(workspace.project.value, project("remote-access", false));
|
||||
});
|
||||
|
||||
// The break this catches: another request's answer (a TUI's, or one this page gave up on) shown
|
||||
// as this file's diff
|
||||
test("a diff is matched to its answer by request id", () => {
|
||||
const { workspace, id } = opened();
|
||||
workspace.apply(frame("file_diff_loaded", { request_id: "someone-else", diff: DIFF }));
|
||||
assert.equal(workspace.diff.value.waiting, true);
|
||||
workspace.apply(frame("file_diff_loaded", { request_id: id, diff: DIFF }));
|
||||
assert.deepEqual(workspace.diff.value, { path: "notes.txt", requestId: id, waiting: false, diff: DIFF });
|
||||
});
|
||||
|
||||
// The break this catches: a failure left loading forever, or shown without core's reason
|
||||
test("a failed diff keeps the reason", () => {
|
||||
const { workspace, id } = opened();
|
||||
workspace.apply(frame("file_diff_failed", { request_id: id, path: "notes.txt", error: "too_large" }));
|
||||
assert.equal(workspace.diff.value.waiting, false);
|
||||
assert.equal(workspace.diff.value.error, "too_large");
|
||||
});
|
||||
|
||||
// The break this catches: a diff closed while loading reopened by its late answer
|
||||
test("a closed diff stays closed", () => {
|
||||
const { workspace, id } = opened();
|
||||
workspace.close();
|
||||
workspace.apply(frame("file_diff_loaded", { request_id: id, diff: DIFF }));
|
||||
assert.equal(workspace.diff.value, null);
|
||||
});
|
||||
|
||||
// The break this catches: a request lost with a dropped socket left loading forever, or a diff
|
||||
// already shown thrown away by reconnecting
|
||||
test("reconnecting gives up only on a diff still loading", () => {
|
||||
const { workspace, id } = opened();
|
||||
workspace.apply(frame("ready", {}));
|
||||
assert.equal(workspace.diff.value.lost, true);
|
||||
const shown = opened();
|
||||
shown.workspace.apply(frame("file_diff_loaded", { request_id: shown.id, diff: DIFF }));
|
||||
shown.workspace.apply(frame("ready", {}));
|
||||
assert.equal(shown.workspace.diff.value.lost, undefined);
|
||||
assert.notEqual(id, shown.id, "each request has its own id");
|
||||
});
|
||||
|
||||
// The break this catches: the request's path or kind wrong, so the host answers a different file
|
||||
test("a diff request names its file", () => {
|
||||
const request = diffRequest("src/a b.rs");
|
||||
assert.equal(request.kind, "load_file_diff");
|
||||
assert.equal(request.content.path, "src/a b.rs");
|
||||
});
|
||||
|
||||
// The break this catches: an empty dock taking the wide screen's right side, or a dock with only
|
||||
// a plan, or only changes, not shown
|
||||
test("the dock shows when there's a plan or a change", () => {
|
||||
assert.equal(hasDock(null, null), false);
|
||||
assert.equal(hasDock({ total: 0 }, { total_files: 0 }), false);
|
||||
assert.equal(hasDock(TODOS, { total_files: 0 }), true);
|
||||
assert.equal(hasDock({ total: 0 }, CHANGES), true);
|
||||
});
|
||||
20
crates/luxe-remote/app/app.js
Normal file
20
crates/luxe-remote/app/app.js
Normal file
@@ -0,0 +1,20 @@
|
||||
// @ts-check
|
||||
// The screens, picked by the address's hash so the back gesture and a home-screen reload
|
||||
// land where you were.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { NewSession } from "./folders.js";
|
||||
import { html } from "./html.js";
|
||||
import { SessionList } from "./sessions.js";
|
||||
import { SessionView } from "./session.js";
|
||||
|
||||
const route = signal(location.hash);
|
||||
addEventListener("hashchange", () => (route.value = location.hash));
|
||||
|
||||
export function App() {
|
||||
if (route.value === "#/new") return html`<${NewSession} />`;
|
||||
const match = /^#\/session\/(.+)$/.exec(route.value);
|
||||
if (!match) return html`<${SessionList} />`;
|
||||
const sessionId = decodeURIComponent(match[1]);
|
||||
return html`<${SessionView} key=${sessionId} sessionId=${sessionId} />`;
|
||||
}
|
||||
77
crates/luxe-remote/app/commands.js
Normal file
77
crates/luxe-remote/app/commands.js
Normal file
@@ -0,0 +1,77 @@
|
||||
// @ts-check
|
||||
// The slash commands the phone can carry out: the TUI's commands that the protocol has an action
|
||||
// for, and `/dock`, which works the app's own screen as the TUI's works the terminal's. Named and
|
||||
// worded as the TUI's are. The rest work the terminal's own screen, so they aren't offered, and a
|
||||
// message that only looks like one goes to the agent as written.
|
||||
|
||||
import { DOCK_VERBS } from "./layout.js";
|
||||
import { nextModeFrame } from "./status.js";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/**
|
||||
* A command the picker offers. One that `takes` words goes into the box to finish; one that
|
||||
* doesn't runs when picked.
|
||||
* @typedef {{ name: string, title: string, takes?: string }} Command
|
||||
* @typedef {{ frame: Frame } | { details: true } | { dock: string } | null} CommandAction
|
||||
* @typedef {{ send: (frame: Frame) => boolean, details: () => void, dock: (verb: string) => void }} CommandHooks
|
||||
*/
|
||||
|
||||
/** @type {Command[]} */
|
||||
export const COMMANDS = [
|
||||
{ name: "compact", title: "Compact the conversation", takes: "what the summary should keep" },
|
||||
{ name: "cost", title: "Session cost" },
|
||||
{ name: "dock", title: "Context Dock", takes: "show, hide, auto, left or right" },
|
||||
{ name: "mode", title: "Switch mode", takes: "plan or build" },
|
||||
{ name: "model", title: "Change model" },
|
||||
{ name: "thinking", title: "Set thinking level" },
|
||||
];
|
||||
|
||||
/** The commands `text` could be the start of: a slash and part of a name, nothing after. @param {string} text */
|
||||
export function matchCommands(text) {
|
||||
const typed = /^\/(\S*)$/.exec(text);
|
||||
if (!typed) return [];
|
||||
return COMMANDS.filter((command) => command.name.startsWith(typed[1].toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* What sending `text` does when it's one of the commands: a frame for the session, or the details
|
||||
* sheet. Null for a message, which includes a known command given words it doesn't take.
|
||||
* @param {string} text @param {string} mode The mode now, which a bare `/mode` moves on from
|
||||
* @returns {CommandAction}
|
||||
*/
|
||||
export function commandAction(text, mode) {
|
||||
const typed = /^\/([a-z]+)(?:\s+([\s\S]*))?$/i.exec(text.trim());
|
||||
if (!typed) return null;
|
||||
const [, name, words = ""] = typed;
|
||||
// a phone's keyboard capitalizes the start of a message
|
||||
switch (name.toLowerCase()) {
|
||||
case "compact": return { frame: words ? { kind: "compact_now", content: { focus: words } } : { kind: "compact_now" } };
|
||||
case "mode": return modeAction(words, mode);
|
||||
case "dock": return dockAction(words.toLowerCase());
|
||||
case "cost": case "model": case "thinking": return words ? null : { details: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carries out a command: null when `action` isn't one, else whether it went out.
|
||||
* @param {CommandAction} action @param {CommandHooks} hooks
|
||||
*/
|
||||
export function runCommand(action, { send, details, dock }) {
|
||||
if (!action) return null;
|
||||
if ("details" in action) return (details(), true);
|
||||
if ("dock" in action) return (dock(action.dock), true);
|
||||
return send(action.frame);
|
||||
}
|
||||
|
||||
/** A bare `/dock` toggles, as the TUI's does. @param {string} words @returns {CommandAction} */
|
||||
function dockAction(words) {
|
||||
if (!words) return { dock: "toggle" };
|
||||
return DOCK_VERBS.includes(words) ? { dock: words } : null;
|
||||
}
|
||||
|
||||
/** @param {string} words @param {string} mode @returns {CommandAction} */
|
||||
function modeAction(words, mode) {
|
||||
if (!words) return { frame: nextModeFrame(mode) };
|
||||
return words === "plan" || words === "build" ? { frame: { kind: "set_mode", content: words } } : null;
|
||||
}
|
||||
74
crates/luxe-remote/app/comments-view.js
Normal file
74
crates/luxe-remote/app/comments-view.js
Normal file
@@ -0,0 +1,74 @@
|
||||
// @ts-check
|
||||
// Commenting on a review chapter from the phone: the composer that writes a comment or a reply,
|
||||
// the buttons on the host's comment cards, and the guide's line offering to send what's unsent.
|
||||
|
||||
import { useState } from "preact/hooks";
|
||||
import { html, landedIn } from "./html.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { actEdit, anchorFor, anchorWords, commentEdit, labelOf, unsent } from "./comments.js";
|
||||
|
||||
/** @import { PanelHooks } from "./panel.js" */
|
||||
/** @import { LinePick } from "./lines.js" */
|
||||
/** @import { ReviewShown } from "./review.js" */
|
||||
/**
|
||||
* What the composer is writing: a new comment at `anchor`, or a reply on comment `reply`.
|
||||
* @typedef {{ heading: string, anchor?: any, reply?: string }} Composing
|
||||
*/
|
||||
|
||||
/** A new comment on `pick`, or on the chapter with none. @param {any} review @param {string} chapter @param {LinePick | null} pick @returns {Composing} */
|
||||
export function composeAt(review, chapter, pick) {
|
||||
const anchor = anchorFor(review, chapter, pick);
|
||||
return { heading: anchorWords(anchor, pick), anchor };
|
||||
}
|
||||
|
||||
/**
|
||||
* A tap on a comment card's button: a reply opens the composer, anything else is sent as it is.
|
||||
* @param {MouseEvent} event @param {PanelHooks} hooks @param {(composing: Composing) => void} compose
|
||||
*/
|
||||
export function tapCard(event, { review, send }, compose) {
|
||||
const button = landedIn(event, "[data-act]");
|
||||
const finding = button?.closest("[data-finding]")?.getAttribute("data-finding");
|
||||
const act = button?.getAttribute("data-act");
|
||||
if (!finding || !act) return;
|
||||
if (act === "reply") return compose({ heading: `Reply to ${labelOf(review.shown.value.session, finding)}`, reply: finding });
|
||||
const edit = actEdit(act, finding);
|
||||
if (edit) review.edit(send, edit);
|
||||
}
|
||||
|
||||
/** The edit the composer's words make. @param {Composing} composing @param {string} body @param {boolean} question @param {boolean} now */
|
||||
export function composedEdit(composing, body, question, now) {
|
||||
if (composing.reply) return actEdit("reply", composing.reply, body);
|
||||
return commentEdit(composing.anchor, body, question, now);
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer, at the foot of the chapter. A comment can be saved to send later or sent now; a
|
||||
* reply goes at once, as the TUI's does.
|
||||
* @param {{ composing: Composing, submit: (body: string, question: boolean, now: boolean) => void, cancel: () => void }} props
|
||||
*/
|
||||
export function CommentSheet({ composing, submit, cancel }) {
|
||||
const [body, setBody] = useState("");
|
||||
const [question, setQuestion] = useState(false);
|
||||
const words = body.trim();
|
||||
const kind = (/** @type {boolean} */ asks, /** @type {string} */ label) =>
|
||||
html`<button type="button" class="mention" aria-pressed=${question === asks} onClick=${() => setQuestion(asks)}>${label}</button>`;
|
||||
return html`<div class="rv-compose" role="group" aria-label=${composing.heading}>
|
||||
<header class="bar"><span class="title">${composing.heading}</span>
|
||||
<button type="button" class="close" aria-label="Cancel" onClick=${cancel}><${Icon} name="close" /></button></header>
|
||||
${composing.reply ? null : html`<p class="rv-kinds">${kind(false, "Comment")}${kind(true, "Question")}</p>`}
|
||||
<textarea rows="4" aria-label=${composing.heading} value=${body} onInput=${(/** @type {any} */ event) => setBody(event.target.value)}></textarea>
|
||||
<p class="rv-compose-acts">
|
||||
${composing.reply ? null : html`<button type="button" class="mention" disabled=${!words} onClick=${() => submit(words, question, false)}>Save</button>`}
|
||||
<button type="button" class="mention" disabled=${!words} onClick=${() => submit(words, question, true)}>Send</button>
|
||||
</p>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The guide's line for comments not sent yet, and the button that sends them all. @param {{ shown: ReviewShown, hooks: PanelHooks }} props */
|
||||
export function Unsent({ shown, hooks }) {
|
||||
const ids = unsent(shown.session);
|
||||
if (!ids.length) return null;
|
||||
const words = ids.length === 1 ? "1 unsent comment" : `${ids.length} unsent comments`;
|
||||
return html`<p class="rv-unsent">${words}
|
||||
<button type="button" class="mention" onClick=${() => hooks.review.edit(hooks.send, { edit: "send", finding_ids: ids })}>Send</button></p>`;
|
||||
}
|
||||
65
crates/luxe-remote/app/comments.js
Normal file
65
crates/luxe-remote/app/comments.js
Normal file
@@ -0,0 +1,65 @@
|
||||
// @ts-check
|
||||
// Comments on the open review from the phone: where a new one goes, and the `edit_review` edit each
|
||||
// action sends. The review desk answers every edit with the whole session, so nothing here keeps
|
||||
// comments of its own.
|
||||
|
||||
/** @import { LinePick } from "./lines.js" */
|
||||
|
||||
/**
|
||||
* Where a comment on `pick` goes: a line for one picked line, its hunk for a run inside one hunk,
|
||||
* and the chapter for anything wider or for no pick at all. A line is the new side's, the only
|
||||
* side a pick can name.
|
||||
* @param {any} review @param {string} chapterId @param {LinePick | null} pick
|
||||
*/
|
||||
export function anchorFor(review, chapterId, pick) {
|
||||
const chapter = { kind: "chapter", chapter_id: chapterId };
|
||||
const file = pick && review.files.find((/** @type {any} */ it) => it.new_path === pick.path);
|
||||
const holds = (/** @type {any} */ hunk, /** @type {number} */ line) => hunk.lines.some((/** @type {any} */ it) => it.new_line === line);
|
||||
const hunk = pick && file?.hunks.find((/** @type {any} */ it) => holds(it, pick.first));
|
||||
if (!pick || !hunk) return chapter;
|
||||
if (pick.first === pick.last) return { kind: "line", file_id: file.id, hunk_id: hunk.id, side: "new", line: pick.first };
|
||||
return holds(hunk, pick.last) ? { kind: "hunk", file_id: file.id, hunk_id: hunk.id } : chapter;
|
||||
}
|
||||
|
||||
/** The composer's heading for a comment at `anchor`. @param {any} anchor @param {LinePick | null} pick */
|
||||
export function anchorWords(anchor, pick) {
|
||||
if (anchor.kind === "line") return `Comment on line ${anchor.line}`;
|
||||
if (anchor.kind === "hunk" && pick) return `Comment on lines ${pick.first}–${pick.last}`;
|
||||
return "Comment on this chapter";
|
||||
}
|
||||
|
||||
/**
|
||||
* A new comment, unsent unless `send`. A question asks for an answer; anything else is an issue,
|
||||
* the review desk's default for a comment.
|
||||
* @param {any} anchor @param {string} body @param {boolean} question @param {boolean} send
|
||||
*/
|
||||
export function commentEdit(anchor, body, question, send) {
|
||||
return { edit: "comment", anchor, body, severity: question ? "question" : "issue", send };
|
||||
}
|
||||
|
||||
/**
|
||||
* The edit a card's button asks for. A reply goes to the agent at once, as a thread reply does in
|
||||
* the TUI.
|
||||
* @param {string} act @param {string} findingId @param {string} [body]
|
||||
*/
|
||||
export function actEdit(act, findingId, body = "") {
|
||||
switch (act) {
|
||||
case "send": return { edit: "send", finding_ids: [findingId] };
|
||||
case "delete": return { edit: "delete_comment", finding_id: findingId };
|
||||
case "resolve": return { edit: "resolve", finding_id: findingId };
|
||||
case "reopen": return { edit: "reopen", finding_id: findingId };
|
||||
case "reply": return { edit: "reply", finding_id: findingId, body, send: true };
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The comments not sent yet, which Send all sends. A posted one is GitHub's. @param {any} session @returns {string[]} */
|
||||
export function unsent(session) {
|
||||
const drafts = (session?.findings ?? []).filter((/** @type {any} */ it) => it.state === "draft" && !it.posted);
|
||||
return drafts.map((/** @type {any} */ it) => it.id);
|
||||
}
|
||||
|
||||
/** A card's label, for the reply composer's heading. @param {any} session @param {string} findingId */
|
||||
export function labelOf(session, findingId) {
|
||||
return session?.findings?.find((/** @type {any} */ it) => it.id === findingId)?.label ?? "";
|
||||
}
|
||||
210
crates/luxe-remote/app/composer.js
Normal file
210
crates/luxe-remote/app/composer.js
Normal file
@@ -0,0 +1,210 @@
|
||||
// @ts-check
|
||||
// Where you write to the agent. Idle, Send starts a turn; while one runs, what you send steers it
|
||||
// between tool calls, as typing into the TUI's composer does, and Stop ends it. Steering carries
|
||||
// only words, so a message with photos waits for the turn to end and starts the next one.
|
||||
//
|
||||
// Return is a new line, since a phone's keyboard has no other way to make one; Command- or
|
||||
// Control-Return sends from a hardware keyboard. The line beside the buttons says what sending
|
||||
// does while a turn runs, since the buttons are icons. A message that's one of the slash commands
|
||||
// the phone can carry out does that instead of going to the agent.
|
||||
//
|
||||
// One panel, as the TUI's composer is one box: the box takes the whole width, with the buttons
|
||||
// along its foot, since a narrow phone (or a closed iPhone Duo beside its side bar) has no room
|
||||
// for both in a row.
|
||||
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
|
||||
import { withMention } from "./files.js";
|
||||
import { fieldOf, html } from "./html.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { messageFrame } from "./pending.js";
|
||||
import { forTheWire, usePhotos } from "./photos.js";
|
||||
import { Picker } from "./picker.js";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @import { Draft, Listings } from "./picker.js" */
|
||||
/** @typedef {ReturnType<typeof usePhotos>} Photos */
|
||||
|
||||
/** @type {Draft} */
|
||||
const EMPTY = { text: "", caret: 0 };
|
||||
|
||||
/** The rows the box grows to before it scrolls. */
|
||||
const MOST_ROWS = 8;
|
||||
|
||||
/**
|
||||
* `run` carries out a slash command: null when the text isn't one, else whether it went out.
|
||||
* `mention` is what a mention from elsewhere (the project panel) adds to the draft, added and
|
||||
* then `taken`.
|
||||
* @param {{ busy: boolean, live: boolean, steering: number, listings: Listings,
|
||||
* send: (frame: Frame) => boolean, run: (text: string) => boolean | null, onSteered: () => void,
|
||||
* onDropped: () => void, mention: string | null, taken: () => void }} props
|
||||
*/
|
||||
export function Composer({ busy, live, steering, listings, send, run, onSteered, onDropped, mention, taken }) {
|
||||
const [draft, setDraft] = useState(EMPTY);
|
||||
useMentioned(mention, setDraft, taken);
|
||||
const photos = usePhotos();
|
||||
const clear = () => setDraft(EMPTY);
|
||||
const submit = useSubmit({ text: draft.text, photos, busy, send, run, onSent: clear, onSteered });
|
||||
const withPhotos = photos.list.length > 0;
|
||||
const ready = live && (draft.text.trim() !== "" || withPhotos);
|
||||
return html`<form class="composer" onSubmit=${submit}>
|
||||
<${Picker} draft=${draft} listings=${listings} send=${send} place=${setDraft} run=${(/** @type {string} */ text) => run(text) && clear()} />
|
||||
<div class="composer-panel">
|
||||
<${PhotoStrip} photos=${photos} />
|
||||
<${MessageBox} draft=${draft} setDraft=${setDraft} busy=${busy} live=${live} submit=${submit} />
|
||||
<${Tools} live=${live} busy=${busy} ready=${ready} steering=${steering} photos=${photos} send=${send} onDropped=${onDropped} />
|
||||
</div>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel's foot: a photo, the steering line, then Stop and Send.
|
||||
* @param {{ live: boolean, busy: boolean, ready: boolean, steering: number, photos: Photos,
|
||||
* send: (frame: Frame) => boolean, onDropped: () => void }} props
|
||||
*/
|
||||
function Tools({ live, busy, ready, steering, photos, send, onDropped }) {
|
||||
const withPhotos = photos.list.length > 0;
|
||||
return html`<div class="composer-tools">
|
||||
<${Attach} live=${live} onPick=${photos.add} />
|
||||
<${Steering} line=${steeringLine(busy, steering, withPhotos)} count=${steering}
|
||||
withdraw=${() => send({ kind: "withdraw_steering" }) && onDropped()} />
|
||||
<${Actions} label=${sendLabel(busy, withPhotos)} busy=${busy} ready=${ready} stop=${() => send({ kind: "cancel" }) && onDropped()} />
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The box you write in, growing with what's written; Command- or Control-Return sends. It keeps
|
||||
* where the caret is, which is what an `@` mention is read back from.
|
||||
* @param {{ draft: Draft, setDraft: (draft: Draft) => void, busy: boolean, live: boolean,
|
||||
* submit: (event: Event) => void }} props
|
||||
*/
|
||||
function MessageBox({ draft, setDraft, busy, live, submit }) {
|
||||
const box = useRef(/** @type {HTMLTextAreaElement | null} */ (null));
|
||||
useGrowing(box, draft.text);
|
||||
usePlacedCaret(box, draft);
|
||||
/** @param {KeyboardEvent} event */
|
||||
const onKey = (event) => event.key === "Enter" && (event.metaKey || event.ctrlKey) && submit(event);
|
||||
/** @param {Event} event */
|
||||
const onInput = (event) => {
|
||||
const field = fieldOf(event);
|
||||
setDraft({ text: field.value, caret: field.selectionStart ?? field.value.length });
|
||||
};
|
||||
return html`<textarea ref=${box} rows="2" value=${draft.text} disabled=${!live} enterkeyhint="enter"
|
||||
placeholder=${busy ? "Steer the agent" : "Message the agent"} aria-label="Message"
|
||||
onInput=${onInput} onKeyDown=${onKey} />`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a mention made outside the composer to the end of the draft.
|
||||
* @param {string | null} mention @param {(change: (draft: Draft) => Draft) => void} setDraft
|
||||
* @param {() => void} taken
|
||||
*/
|
||||
function useMentioned(mention, setDraft, taken) {
|
||||
useEffect(() => {
|
||||
if (mention === null) return;
|
||||
setDraft((draft) => withMention(draft.text, mention));
|
||||
taken();
|
||||
}, [mention]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the caret after what a pick inserted; typing leaves it where the keyboard put it.
|
||||
* @param {{ current: HTMLTextAreaElement | null }} box @param {Draft} draft
|
||||
*/
|
||||
function usePlacedCaret(box, draft) {
|
||||
useLayoutEffect(() => {
|
||||
if (draft.placed) box.current?.setSelectionRange(draft.caret, draft.caret);
|
||||
}, [draft]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends what's written and attached, clearing both only once it went out. Words alone that make
|
||||
* one of the phone's commands carry it out instead.
|
||||
* @param {{ text: string, photos: Photos, busy: boolean, send: (frame: Frame) => boolean,
|
||||
* run: (text: string) => boolean | null, onSent: () => void, onSteered: () => void }} props
|
||||
*/
|
||||
function useSubmit({ text, photos, busy, send, run, onSent, onSteered }) {
|
||||
return (/** @type {Event | undefined} */ event) => {
|
||||
event?.preventDefault();
|
||||
const attached = photos.list;
|
||||
if (!text.trim() && !attached.length) return;
|
||||
const ran = attached.length ? null : run(text);
|
||||
if (ran !== null) return void (ran && onSent());
|
||||
if (!send(messageFrame(text, busy, forTheWire(attached)))) return;
|
||||
onSent();
|
||||
photos.clear();
|
||||
if (busy && !attached.length) onSteered();
|
||||
};
|
||||
}
|
||||
|
||||
/** What the send button says to a screen reader. @param {boolean} busy @param {boolean} withPhotos */
|
||||
export function sendLabel(busy, withPhotos) {
|
||||
if (!busy) return "Send";
|
||||
return withPhotos ? "Queue" : "Steer";
|
||||
}
|
||||
|
||||
/**
|
||||
* The line over the box: steering this device sent that hasn't reached the agent yet, or else
|
||||
* what sending does while a turn runs. Empty when there's nothing to say.
|
||||
* @param {boolean} busy @param {number} count @param {boolean} withPhotos
|
||||
*/
|
||||
export function steeringLine(busy, count, withPhotos) {
|
||||
if (count) return count === 1 ? "1 message waiting to steer" : `${count} messages waiting to steer`;
|
||||
if (!busy) return "";
|
||||
return withPhotos ? "Photos wait for the turn" : "Send steers the turn";
|
||||
}
|
||||
|
||||
/** @param {{ live: boolean, onPick: (files: FileList) => void }} props */
|
||||
function Attach({ live, onPick }) {
|
||||
/** @param {Event} event */
|
||||
const picked = (event) => {
|
||||
const field = fieldOf(event);
|
||||
if (field.files) onPick(field.files);
|
||||
field.value = "";
|
||||
};
|
||||
return html`<label class=${`attach ${live ? "" : "off"}`}><${Icon} name="attach" />
|
||||
<input type="file" accept="image/*" multiple aria-label="Add a photo" disabled=${!live} onChange=${picked} /></label>`;
|
||||
}
|
||||
|
||||
/** @param {{ label: string, busy: boolean, ready: boolean, stop: () => void }} props */
|
||||
function Actions({ label, busy, ready, stop }) {
|
||||
return html`<div class="composer-actions">
|
||||
${busy ? html`<button type="button" class="stop" aria-label="Stop" onClick=${stop}><${Icon} name="stop" /></button>` : null}
|
||||
<button type="submit" class="send" aria-label=${label} disabled=${!ready}><${Icon} name="send" /></button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** The photos attached so far, each with a way to take it off. @param {{ photos: Photos }} props */
|
||||
function PhotoStrip({ photos }) {
|
||||
if (!photos.list.length && !photos.problem) return null;
|
||||
return html`<div class="photos">
|
||||
${photos.problem ? html`<p class="problem">${photos.problem}</p>` : null}
|
||||
${photos.list.map((photo, index) => html`<figure class="photo" key=${photo.preview.slice(-32)}>
|
||||
<img src=${photo.preview} alt=${photo.name ?? "photo"} />
|
||||
<button type="button" class="unattach" aria-label="Remove photo" onClick=${() => photos.remove(index)}><${Icon} name="close" /></button>
|
||||
</figure>`)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The steering line, with a way to take back what's waiting.
|
||||
* @param {{ line: string, count: number, withdraw: () => void }} props
|
||||
*/
|
||||
function Steering({ line, count, withdraw }) {
|
||||
if (!line) return null;
|
||||
return html`<p class="steering">${line}
|
||||
${count ? html`<button type="button" class="withdraw" onClick=${withdraw}>withdraw</button>` : null}</p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The box grows with what's written, up to MOST_ROWS, then scrolls.
|
||||
* @param {{ current: HTMLTextAreaElement | null }} box @param {string} text
|
||||
*/
|
||||
function useGrowing(box, text) {
|
||||
useLayoutEffect(() => {
|
||||
const element = box.current;
|
||||
if (!element) return;
|
||||
element.style.height = "auto";
|
||||
const most = parseFloat(getComputedStyle(element).lineHeight) * MOST_ROWS;
|
||||
element.style.height = `${Math.min(element.scrollHeight, most)}px`;
|
||||
}, [text]);
|
||||
}
|
||||
153
crates/luxe-remote/app/connection.js
Normal file
153
crates/luxe-remote/app/connection.js
Normal file
@@ -0,0 +1,153 @@
|
||||
// One session's socket, and what to do when it closes.
|
||||
//
|
||||
// How it closed says what next: 1000 is the session ending, 4001 this device being unpaired, and
|
||||
// anything else a dropped connection, the one case worth retrying. A drop can also hide one of
|
||||
// the other two (the upgrade is refused before a close code can say so), so a retry first asks
|
||||
// the session list.
|
||||
//
|
||||
// The socket is closed while the app is out of sight and opened again on the way back, which iOS
|
||||
// would mostly do anyway: an open socket is how the bridge knows you're looking at a session, and
|
||||
// so whether to send this device a notification about it instead.
|
||||
|
||||
const UNPAIRED = 4001;
|
||||
const LONGEST_WAIT_MS = 15000;
|
||||
|
||||
/**
|
||||
* One protocol message, either way: an event from the session or an action for it.
|
||||
* @typedef {{ kind: string, content?: any }} Frame
|
||||
* @typedef {"connecting" | "live" | "reconnecting" | "ended" | "unpaired"} Status
|
||||
* @typedef {(frame: Frame) => void} OnFrame
|
||||
* @typedef {(status: Status) => void} OnStatus
|
||||
* @typedef {{
|
||||
* socket: WebSocket | null, attempts: number, timer: ReturnType<typeof setTimeout> | undefined,
|
||||
* stopped: boolean,
|
||||
* }} Link
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {string} sessionId
|
||||
* @param {{ onFrame: OnFrame, onStatus: OnStatus }} callbacks
|
||||
*/
|
||||
export function connect(sessionId, { onFrame, onStatus }) {
|
||||
/** @type {Link} */
|
||||
const link = { socket: null, attempts: 0, timer: undefined, stopped: false };
|
||||
const open = () => {
|
||||
if (document.visibilityState === "hidden") return;
|
||||
openSocket(link, sessionId, onFrame, onStatus, () => retry(link, sessionId, open, onStatus));
|
||||
};
|
||||
const resume = () => {
|
||||
if (link.stopped || link.socket) return;
|
||||
clearTimeout(link.timer);
|
||||
open();
|
||||
};
|
||||
const seen = () => (document.visibilityState === "visible" ? resume() : rest(link));
|
||||
document.addEventListener("visibilitychange", seen);
|
||||
open();
|
||||
return controls(link, seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the socket while the app is out of sight. Its handlers go first, so the close isn't taken
|
||||
* for the session ending and a return before it finishes opens a new one.
|
||||
* @param {Link} link
|
||||
*/
|
||||
function rest(link) {
|
||||
clearTimeout(link.timer);
|
||||
const socket = link.socket;
|
||||
if (!socket) return;
|
||||
link.socket = null;
|
||||
socket.onclose = null;
|
||||
socket.onmessage = null;
|
||||
socket.close(1000);
|
||||
}
|
||||
|
||||
/** @param {Link} link @param {() => void} seen */
|
||||
function controls(link, seen) {
|
||||
return {
|
||||
/**
|
||||
* Whether `frame` went out: false while the socket is down, so nothing typed is lost.
|
||||
* @param {Frame} frame
|
||||
*/
|
||||
send(frame) {
|
||||
if (link.socket?.readyState !== WebSocket.OPEN) return false;
|
||||
link.socket.send(JSON.stringify(frame));
|
||||
return true;
|
||||
},
|
||||
close() {
|
||||
link.stopped = true;
|
||||
clearTimeout(link.timer);
|
||||
document.removeEventListener("visibilitychange", seen);
|
||||
link.socket?.close(1000);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Link} link @param {string} sessionId @param {OnFrame} onFrame @param {OnStatus} onStatus
|
||||
* @param {() => void} onDrop
|
||||
*/
|
||||
function openSocket(link, sessionId, onFrame, onStatus, onDrop) {
|
||||
const scheme = location.protocol === "https:" ? "wss" : "ws";
|
||||
const socket = new WebSocket(`${scheme}://${location.host}/api/sessions/${encodeURIComponent(sessionId)}/socket`);
|
||||
link.socket = socket;
|
||||
onStatus(link.attempts ? "reconnecting" : "connecting");
|
||||
listen(socket, link, onFrame, onStatus, onDrop);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {WebSocket} socket @param {Link} link @param {OnFrame} onFrame @param {OnStatus} onStatus
|
||||
* @param {() => void} onDrop
|
||||
*/
|
||||
function listen(socket, link, onFrame, onStatus, onDrop) {
|
||||
socket.onopen = () => {
|
||||
link.attempts = 0;
|
||||
onStatus("live");
|
||||
};
|
||||
socket.onmessage = (event) => {
|
||||
const frame = parse(event.data);
|
||||
if (frame) onFrame(frame);
|
||||
};
|
||||
socket.onclose = (event) => {
|
||||
link.socket = null;
|
||||
if (link.stopped) return;
|
||||
if (event.code === 1000) return onStatus("ended");
|
||||
if (event.code === UNPAIRED) return onStatus("unpaired");
|
||||
onDrop();
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {Link} link @param {string} sessionId @param {() => void} open @param {OnStatus} onStatus */
|
||||
async function retry(link, sessionId, open, onStatus) {
|
||||
link.attempts += 1;
|
||||
onStatus("reconnecting");
|
||||
const verdict = await stillThere(sessionId);
|
||||
if (link.stopped) return;
|
||||
if (verdict !== "yes") return onStatus(verdict);
|
||||
const wait = Math.min(LONGEST_WAIT_MS, 1000 * 2 ** (link.attempts - 1));
|
||||
link.timer = setTimeout(open, wait);
|
||||
}
|
||||
|
||||
/** @param {string} sessionId @returns {Promise<"yes" | "ended" | "unpaired">} */
|
||||
async function stillThere(sessionId) {
|
||||
try {
|
||||
const response = await fetch("/api/sessions");
|
||||
if (response.status === 401 || response.status === 403) return "unpaired";
|
||||
if (!response.ok) return "yes";
|
||||
/** @type {{ session_id: string }[]} */
|
||||
const sessions = await response.json();
|
||||
return sessions.some((session) => session.session_id === sessionId) ? "yes" : "ended";
|
||||
} catch {
|
||||
// Offline: the list can't say either way, so keep trying
|
||||
return "yes";
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {string} text @returns {Frame | null} */
|
||||
function parse(text) {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
console.warn("ignoring a frame that isn't JSON", text.slice(0, 80));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
483
crates/luxe-remote/app/controls.css
Normal file
483
crates/luxe-remote/app/controls.css
Normal file
@@ -0,0 +1,483 @@
|
||||
/* What you answer and write with: the prompt card and the composer, kept at the foot of the screen
|
||||
the way the TUI keeps them under the transcript. Fields are the page's size; `viewport.js` keeps
|
||||
iOS from zooming into one under 16px. */
|
||||
|
||||
.controls {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
z-index: 1;
|
||||
/* The body pads for the home indicator; this takes that padding over so nothing shows under it */
|
||||
margin-bottom: calc(-1 * env(safe-area-inset-bottom));
|
||||
padding: 0.5lh 1ch calc(0.5lh + env(safe-area-inset-bottom));
|
||||
background: var(--luxe-background, #12100e);
|
||||
border-top: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
/* The picker over one panel: any photos, the box across the whole width, then a foot of buttons
|
||||
with the steering line between them. The buttons are drawn at --button, in scale with the box,
|
||||
and answer taps across --tap, Apple's 44 points */
|
||||
.composer {
|
||||
--button: 1.9lh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5lh;
|
||||
}
|
||||
|
||||
.composer-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
.composer-panel:focus-within {
|
||||
border-color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.composer textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
resize: none;
|
||||
padding: 0.5lh 1.5ch 0;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
line-height: var(--cell);
|
||||
color: inherit;
|
||||
background: none;
|
||||
border: none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.composer-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1ch;
|
||||
padding: 0.25lh;
|
||||
}
|
||||
|
||||
/* Boxes and controls round their corners as the TUI's panels do; filled blocks in the transcript
|
||||
stay square, as filled cells are in a terminal */
|
||||
.composer-panel,
|
||||
.send,
|
||||
.stop,
|
||||
.attach,
|
||||
.own-answer button,
|
||||
.other-folder button,
|
||||
.notifications button,
|
||||
.pair-link button,
|
||||
.photo img,
|
||||
.unattach,
|
||||
.picker,
|
||||
.options button,
|
||||
.models button,
|
||||
.prompt,
|
||||
.choice,
|
||||
.own-answer input,
|
||||
.other-folder input,
|
||||
.pair-link input {
|
||||
border-radius: var(--corner);
|
||||
}
|
||||
|
||||
.own-answer input:focus,
|
||||
.other-folder input:focus,
|
||||
.pair-link input:focus {
|
||||
outline: none;
|
||||
border-color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.composer-actions {
|
||||
display: flex;
|
||||
gap: 1ch;
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
.icon {
|
||||
display: block;
|
||||
width: 1.3lh;
|
||||
height: 1.3lh;
|
||||
}
|
||||
|
||||
.send,
|
||||
.stop,
|
||||
.attach {
|
||||
position: relative;
|
||||
display: grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
width: var(--button);
|
||||
height: var(--button);
|
||||
}
|
||||
|
||||
.composer-tools .icon {
|
||||
width: 1.1lh;
|
||||
height: 1.1lh;
|
||||
}
|
||||
|
||||
/* a pad past the drawn button, so a tap a little off it still lands */
|
||||
.stop::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: calc((var(--button) - var(--tap)) / 2);
|
||||
}
|
||||
|
||||
/* Send and photo draw only their icons, so each box can be the whole tap area; the negative
|
||||
margin keeps them to the drawn buttons' height in the row */
|
||||
.send,
|
||||
.attach {
|
||||
width: var(--tap);
|
||||
height: var(--tap);
|
||||
margin-block: calc((var(--button) - var(--tap)) / 2);
|
||||
}
|
||||
|
||||
.send {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.send:disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.stop {
|
||||
color: var(--luxe-error, #e68485);
|
||||
border: 1px solid currentColor;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.own-answer button,
|
||||
.other-folder button,
|
||||
.notifications button,
|
||||
.pair-link button {
|
||||
padding: 0.25lh 1.5ch;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.own-answer button,
|
||||
.other-folder button,
|
||||
.notifications button,
|
||||
.pair-link button {
|
||||
color: var(--luxe-background, #12100e);
|
||||
background: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
/* turning something off is the lesser action, so it doesn't shout */
|
||||
.notifications button.quiet {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
background: none;
|
||||
border: 1px solid currentColor;
|
||||
}
|
||||
|
||||
.own-answer button:disabled,
|
||||
.other-folder button:disabled,
|
||||
.notifications button:disabled,
|
||||
.pair-link button:disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
/* The file input is the control, so the camera and the library open from one tap on the icon.
|
||||
Clipped, since WebKit draws a file input's hit area wider than its box, over the box beside it. */
|
||||
.attach {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.attach.off {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
.attach input {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.photos {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1ch;
|
||||
padding: 0.5lh 1.5ch 0;
|
||||
}
|
||||
|
||||
.photo {
|
||||
position: relative;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.photo img {
|
||||
display: block;
|
||||
height: 4lh;
|
||||
}
|
||||
|
||||
.unattach {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
padding: 0.2lh;
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
background: var(--luxe-background, #12100e);
|
||||
}
|
||||
|
||||
.unattach .icon {
|
||||
width: 1lh;
|
||||
height: 1lh;
|
||||
}
|
||||
|
||||
/* Suggestions over the box, as the TUI's flyout sits over its composer */
|
||||
.picker {
|
||||
max-height: 10lh;
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
.picker li.dim {
|
||||
padding: 0.4lh 1.5ch;
|
||||
}
|
||||
|
||||
.picker button {
|
||||
width: 100%;
|
||||
padding: 0.4lh 1.5ch;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.picker button:active {
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
}
|
||||
|
||||
.picker .name {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.steering {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.withdraw {
|
||||
margin-inline-start: 1ch;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* The status line, the TUI's bar's right-hand side, in one row: the mode, then the facts in the
|
||||
bar's order. On a phone the cost waits in the details sheet and the model's name gives way
|
||||
first. */
|
||||
|
||||
.status-line {
|
||||
display: flex;
|
||||
gap: 2ch;
|
||||
align-items: baseline;
|
||||
margin-top: 0.5lh;
|
||||
white-space: nowrap;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.mode {
|
||||
flex: none;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.mode-plan {
|
||||
color: var(--luxe-accent-secondary, #d2a5cd);
|
||||
}
|
||||
|
||||
.status-line .segments {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
gap: 2ch;
|
||||
justify-content: flex-end;
|
||||
align-items: baseline;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.seg {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.seg-model {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@media (max-width: 40rem) {
|
||||
.status-line .seg-cost {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* The details sheet: each choice a button, the current one in the accent */
|
||||
.details section {
|
||||
padding: 0 1ch 1lh;
|
||||
}
|
||||
|
||||
.details .section-head {
|
||||
margin: 0 0 0.5lh;
|
||||
}
|
||||
|
||||
.details h3 {
|
||||
margin: 0.5lh 0;
|
||||
font-size: inherit;
|
||||
font-weight: normal;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.options {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1ch;
|
||||
}
|
||||
|
||||
.models {
|
||||
display: grid;
|
||||
gap: 0.5lh;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.options button,
|
||||
.models button {
|
||||
padding: 0.5lh 1.5ch;
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
.models button {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 2ch;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.options button[aria-pressed="true"],
|
||||
.models button[aria-pressed="true"] {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
border-color: currentColor;
|
||||
}
|
||||
|
||||
.readings {
|
||||
display: grid;
|
||||
gap: 0.25lh;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* the sheet has its own pickers for these */
|
||||
.readings .seg-model,
|
||||
.readings .seg-thinking {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.close .icon {
|
||||
width: 1lh;
|
||||
height: 1lh;
|
||||
}
|
||||
|
||||
.tone-warning {
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
}
|
||||
|
||||
.tone-error {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
/* The prompt card, styled as the TUI's: plain chrome, with only the action in question in the
|
||||
warning color */
|
||||
|
||||
.prompt {
|
||||
margin-bottom: 0.5lh;
|
||||
padding: 0.5lh 1ch;
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.prompt p {
|
||||
margin: 0 0 0.5lh;
|
||||
}
|
||||
|
||||
.prompt-title {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.prompt-summary {
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.choices {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.choice {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0.35lh 1ch;
|
||||
}
|
||||
|
||||
.choice:active:not(:disabled),
|
||||
.choice.picked {
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
}
|
||||
|
||||
.choice:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.choice-label {
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
}
|
||||
|
||||
.choice.reject .choice-label {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
.choice-hint {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.recommended,
|
||||
.check {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.own-answer,
|
||||
.other-folder,
|
||||
.pair-link {
|
||||
display: flex;
|
||||
gap: 1ch;
|
||||
margin-top: 0.5lh;
|
||||
}
|
||||
|
||||
.own-answer input,
|
||||
.other-folder input,
|
||||
.pair-link input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0.25lh 1ch;
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
line-height: var(--cell);
|
||||
color: inherit;
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
.dismiss {
|
||||
margin-top: 0.5lh;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
text-decoration: underline;
|
||||
}
|
||||
93
crates/luxe-remote/app/details.js
Normal file
93
crates/luxe-remote/app/details.js
Normal file
@@ -0,0 +1,93 @@
|
||||
// @ts-check
|
||||
// The status line's details: the mode, the thinking level and the model, each a tap to change,
|
||||
// and the readings the compact line leaves out. Changes go to the session as they're picked; the
|
||||
// sheet shows what the session reports back, so a refused change never looks made.
|
||||
|
||||
import { html } from "./html.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { useEscape } from "./dock.js";
|
||||
import { isCurrent, selectModelFrame, thinkingFrame, thinkingLevels } from "./models.js";
|
||||
import { useRendered } from "./render.js";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @import { Listing, ModelChoice } from "./models.js" */
|
||||
|
||||
/** The modes `set_mode` takes. */
|
||||
export const MODES = ["build", "plan"];
|
||||
|
||||
/**
|
||||
* @param {{ facts: Record<string, any>, mode: string, listing: Listing,
|
||||
* send: (frame: Frame) => boolean, close: () => void }} props
|
||||
*/
|
||||
export function DetailsSheet({ facts, mode, listing, send, close }) {
|
||||
useEscape(close);
|
||||
const levels = thinkingLevels(listing.models, facts.model);
|
||||
return html`<div class="sheet" role="dialog" aria-modal="true" aria-label="Session details">
|
||||
<header class="bar">
|
||||
<span class="title">Details</span>
|
||||
<button type="button" class="close" aria-label="Close the details" onClick=${close}><${Icon} name="close" /></button>
|
||||
</header>
|
||||
<div class="sheet-body details">
|
||||
<section><h2 class="section-head"><span class="badge">Model</span></h2>
|
||||
<${Choices} title="Mode" options=${MODES} current=${mode} pick=${(/** @type {string} */ next) => send({ kind: "set_mode", content: next })} />
|
||||
<${Choices} title="Thinking" options=${levels} current=${facts.thinking} pick=${(/** @type {string} */ level) => send(thinkingFrame(level))} />
|
||||
<${ModelPicker} listing=${listing} current=${facts.model} pick=${(/** @type {ModelChoice} */ choice) => send(selectModelFrame(choice))} />
|
||||
</section>
|
||||
<${Readings} facts=${facts} />
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A row of choices with the current one marked; nothing when there's nothing to choose.
|
||||
* @param {{ title: string, options: string[], current: string, pick: (option: string) => void }} props
|
||||
*/
|
||||
function Choices({ title, options, current, pick }) {
|
||||
if (!options.length) return null;
|
||||
return html`<h3>${title}</h3><div class="options" role="group" aria-label=${title}>
|
||||
${options.map((option) => html`<button type="button" key=${option} aria-pressed=${option === current}
|
||||
onClick=${() => pick(option)}>${option}</button>`)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ listing: Listing, current: import("./models.js").CurrentModel | undefined,
|
||||
* pick: (choice: ModelChoice) => void }} props
|
||||
*/
|
||||
function ModelPicker({ listing, current, pick }) {
|
||||
return html`<h3>Model</h3>
|
||||
<${ListingNote} state=${listing.state} empty=${!listing.models.length} />
|
||||
<ul class="models">${listing.models.map((choice) => html`<li key=${`${choice.provider}/${choice.model}`}>
|
||||
<button type="button" aria-pressed=${isCurrent(choice, current)} onClick=${() => pick(choice)}>
|
||||
<span class="name">${choice.name}</span> <span class="dim">${choice.provider}</span>
|
||||
</button></li>`)}
|
||||
</ul>`;
|
||||
}
|
||||
|
||||
/** What the model list is waiting on, when it's not just a list. @param {{ state: string, empty: boolean }} props */
|
||||
function ListingNote({ state, empty }) {
|
||||
if (state === "unsupported") return html`<p class="dim">Update Luxe on your computer to switch models from here.</p>`;
|
||||
if (state === "lost") return html`<p class="dim">Not connected.</p>`;
|
||||
if (state === "asking" && empty) return html`<p class="dim">Loading models…</p>`;
|
||||
if (state === "listed" && empty) return html`<p class="dim">No other models configured.</p>`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the rendered line holds a reading: a session that has spent nothing yet reports a total
|
||||
* the host words as no segment at all. @param {string | null | undefined} rendered
|
||||
*/
|
||||
export function hasReadings(rendered) {
|
||||
return /\bseg-(context|cost)\b/.test(rendered ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The context and cost, worded as the line words them: the line's own render, the same request,
|
||||
* with the model and thinking left to the pickers above. @param {{ facts: Record<string, any> }} props
|
||||
*/
|
||||
function Readings({ facts }) {
|
||||
const rendered = useRendered({ kind: "status", ...facts }, true);
|
||||
if (!hasReadings(rendered)) return null;
|
||||
return html`<section><h2 class="section-head"><span class="badge recessed">Session</span></h2>
|
||||
<p class="readings" dangerouslySetInnerHTML=${{ __html: rendered }}></p></section>`;
|
||||
}
|
||||
216
crates/luxe-remote/app/dock.css
Normal file
216
crates/luxe-remote/app/dock.css
Normal file
@@ -0,0 +1,216 @@
|
||||
/* The dock (plan and changed files) and the diff sheet, colored as the TUI's dock colors them */
|
||||
|
||||
.dock {
|
||||
display: none;
|
||||
padding: 0 1.5ch 1lh;
|
||||
background: var(--luxe-tool-bg, #1a1815);
|
||||
}
|
||||
|
||||
.dock-toggle {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
align-self: center;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.dock-toggle .icon {
|
||||
width: 1.1lh;
|
||||
height: 1.1lh;
|
||||
}
|
||||
|
||||
.dock-toggle.on {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
/* the icon's rail sits on the dock's side */
|
||||
:root[data-dock-side="right"] .dock-toggle .icon {
|
||||
transform: scaleX(-1);
|
||||
}
|
||||
|
||||
/* in the phone's project panel, at the rail's indent */
|
||||
.dock-tab {
|
||||
padding: 0 1.5ch 1lh;
|
||||
}
|
||||
|
||||
.dock-empty {
|
||||
margin-top: 1lh !important;
|
||||
}
|
||||
|
||||
/* Wide enough for both: the dock is a rail beside the conversation, on the side the TUI's config
|
||||
puts it. An open iPhone Duo (951 by 669 points) and an iPad qualify; a phone on its side is too
|
||||
short for a rail. layout.js's WIDE is this same query */
|
||||
@media (min-width: 50rem) and (min-height: 30rem) {
|
||||
#app:has(> .dock.shown) {
|
||||
padding-left: 24rem;
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] #app:has(> .dock.shown) {
|
||||
padding-left: 0;
|
||||
padding-right: 24rem;
|
||||
}
|
||||
|
||||
/* the rail takes the inset on its side too, so its content lines up with the conversation's.
|
||||
On a phone the dock is the project panel's Dock tab, so only here does it show by itself */
|
||||
.dock.shown {
|
||||
display: block;
|
||||
position: fixed;
|
||||
inset: 0 auto 0 0;
|
||||
width: calc(24rem + env(safe-area-inset-left));
|
||||
box-sizing: border-box;
|
||||
overflow-y: auto;
|
||||
padding: env(safe-area-inset-top) 1.5ch calc(env(safe-area-inset-bottom) + 1lh)
|
||||
calc(1.5ch + env(safe-area-inset-left));
|
||||
border-right: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] .dock.shown {
|
||||
inset: 0 0 0 auto;
|
||||
width: calc(24rem + env(safe-area-inset-right));
|
||||
padding-right: calc(1.5ch + env(safe-area-inset-right));
|
||||
padding-left: 1.5ch;
|
||||
border-right: none;
|
||||
border-left: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
}
|
||||
|
||||
.dock-section p,
|
||||
.dock-section ol,
|
||||
.dock-section ul {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* what a heading sums up rides muted beside its badge, as on the TUI's rail */
|
||||
.dock-head {
|
||||
margin-top: 1lh !important;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.dock-sub {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.todos,
|
||||
.changes {
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* A long plan scrolls in a box of its own, the TUI's budget of 8 todos and 4 wrapped lines, so
|
||||
the changes stay close below; dock.js keeps the work in hand in view. Positioned, so each todo's
|
||||
offset is measured from the list */
|
||||
.todos {
|
||||
position: relative;
|
||||
max-height: 12lh;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
/* A wrapped subject hangs under its own first word, past the mark */
|
||||
.todo {
|
||||
padding-left: 2ch;
|
||||
text-indent: -2ch;
|
||||
}
|
||||
|
||||
.todo-completed { color: var(--luxe-success, #81caa0); }
|
||||
.todo-completed .todo-subject { text-decoration: line-through; }
|
||||
.todo-in-progress { font-weight: bold; }
|
||||
.todo-blocked { color: var(--luxe-warning, #faaa51); }
|
||||
.todo-pending { color: var(--luxe-muted, #97938c); }
|
||||
|
||||
.change {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
gap: 1ch;
|
||||
padding: 0.25lh 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.change-path {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.change-added, .change-untracked { color: var(--luxe-success, #81caa0); }
|
||||
.change-modified { color: var(--luxe-warning, #faaa51); }
|
||||
.change-deleted { color: var(--luxe-error, #e68485); }
|
||||
.change-renamed { color: var(--luxe-info, #85c7d7); }
|
||||
.add { color: var(--luxe-success, #81caa0); }
|
||||
.del { color: var(--luxe-error, #e68485); }
|
||||
|
||||
.sheet {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 4;
|
||||
overflow-y: auto;
|
||||
padding: 0 env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
|
||||
background: var(--luxe-background, #12100e);
|
||||
}
|
||||
|
||||
.close {
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
}
|
||||
|
||||
.sheet-body {
|
||||
padding: 1lh 0;
|
||||
}
|
||||
|
||||
.diff-note {
|
||||
padding: 0 1ch;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.retry {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Lines keep their columns and scroll sideways together; each tint runs the width of the widest */
|
||||
.diff {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.hunk {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
margin-bottom: 1lh;
|
||||
}
|
||||
|
||||
.hunk-head {
|
||||
margin: 0;
|
||||
padding: 0 1ch;
|
||||
color: var(--luxe-info, #85c7d7);
|
||||
}
|
||||
|
||||
.dl {
|
||||
display: flex;
|
||||
margin: 0;
|
||||
white-space: pre;
|
||||
tab-size: 4;
|
||||
}
|
||||
|
||||
.dl code {
|
||||
font: inherit;
|
||||
padding-right: 1ch;
|
||||
}
|
||||
|
||||
.ln {
|
||||
flex: none;
|
||||
width: 5ch;
|
||||
padding-right: 1ch;
|
||||
text-align: right;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.sign {
|
||||
flex: none;
|
||||
width: 2ch;
|
||||
}
|
||||
|
||||
.dl-addition { background: var(--luxe-diff-add-bg, #1d2a20); }
|
||||
.dl-addition .sign { color: var(--luxe-success, #81caa0); }
|
||||
.dl-deletion { background: var(--luxe-diff-del-bg, #2d1d1d); }
|
||||
.dl-deletion .sign { color: var(--luxe-error, #e68485); }
|
||||
.dl-note { padding-left: 13ch; color: var(--luxe-muted, #97938c); }
|
||||
129
crates/luxe-remote/app/dock.js
Normal file
129
crates/luxe-remote/app/dock.js
Normal file
@@ -0,0 +1,129 @@
|
||||
// @ts-check
|
||||
// The dock: the plan and the changed files, as the host renders them. A rail beside the transcript
|
||||
// on a wide screen, shown and hidden by the header's button and `/dock` (layout.js); the project
|
||||
// panel's Dock tab on a phone. A long plan scrolls in its own box, and a changed file opens its
|
||||
// diff.
|
||||
|
||||
import { useLayoutEffect, useRef } from "preact/hooks";
|
||||
import { html, landedIn } from "./html.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { useRendered } from "./render.js";
|
||||
import { PickablePiece } from "./lines-view.js";
|
||||
import { hasDock, planScroll } from "./workspace.js";
|
||||
import { useWide } from "./layout.js";
|
||||
|
||||
/** @import { Changes, OpenDiff, Todos } from "./workspace.js" */
|
||||
|
||||
/** @param {{ todos: Todos | null, changes: Changes | null, shown: boolean, open: (path: string) => void }} props */
|
||||
export function Dock({ todos, changes, shown, open }) {
|
||||
return html`<aside class=${shown ? "dock shown" : "dock"} aria-label="Context Dock"
|
||||
onClick=${(/** @type {Event} */ event) => pickChange(event, open)}>
|
||||
<${DockSections} todos=${todos} changes=${changes} />
|
||||
</aside>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The dock as the project panel's Dock tab, on a phone, where the panel is the one way in.
|
||||
* @param {{ hooks: { todos: Todos | null, changes: Changes | null, openDiff: (path: string) => void } }} props
|
||||
*/
|
||||
export function DockTab({ hooks: { todos, changes, openDiff } }) {
|
||||
return html`<div class="dock-tab" onClick=${(/** @type {Event} */ event) => pickChange(event, openDiff)}>
|
||||
<${DockSections} todos=${todos} changes=${changes} />
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ todos: Todos | null, changes: Changes | null }} props */
|
||||
function DockSections({ todos, changes }) {
|
||||
return html`
|
||||
${hasDock(todos, changes) ? null : html`<p class="dim dock-empty">No plan or changes yet.</p>`}
|
||||
${todos?.total ? html`<${Section} piece=${{ kind: "plan", todos }} />` : null}
|
||||
${changes?.total_files ? html`<${Section} piece=${{ kind: "changes", changes }} />` : null}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows are host HTML, so a tap is read off the button it landed in.
|
||||
* @param {Event} event @param {(path: string) => void} open
|
||||
*/
|
||||
function pickChange(event, open) {
|
||||
const path = landedIn(event, "button.change")?.dataset.path;
|
||||
if (path) open(path);
|
||||
}
|
||||
|
||||
/** @param {{ piece: import("./render.js").Piece }} props */
|
||||
function Section({ piece }) {
|
||||
const rendered = useRendered(piece, true);
|
||||
const section = useRef(/** @type {HTMLElement | null} */ (null));
|
||||
const handsOn = usePlanFollow(section, rendered);
|
||||
return html`<section class="dock-section" ref=${section} onTouchStart=${handsOn} onWheel=${handsOn}
|
||||
dangerouslySetInnerHTML=${{ __html: rendered ?? "" }}></section>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scrolls a long plan to the work in hand each time it's drawn, as the TUI's rail does, until the
|
||||
* reader scrolls it themselves. Returns what marks that.
|
||||
* @param {{ current: HTMLElement | null }} section @param {string | null | undefined} rendered
|
||||
*/
|
||||
function usePlanFollow(section, rendered) {
|
||||
const moved = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
const list = section.current?.querySelector(".todos");
|
||||
if (!(list instanceof HTMLElement) || moved.current) return;
|
||||
const rows = [...list.children].map((row) => ({
|
||||
bottom: /** @type {HTMLElement} */ (row).offsetTop + /** @type {HTMLElement} */ (row).offsetHeight,
|
||||
status: row.className.match(/todo-(\S+)/)?.[1] ?? "",
|
||||
}));
|
||||
list.scrollTop = planScroll(rows, list.clientHeight);
|
||||
}, [rendered]);
|
||||
return () => (moved.current = true);
|
||||
}
|
||||
|
||||
/** The header's button that shows and hides the dock. @param {{ shown: boolean, toggle: () => void }} props */
|
||||
export function DockToggle({ shown, toggle }) {
|
||||
return html`<button type="button" class=${shown ? "dock-toggle on" : "dock-toggle"}
|
||||
aria-label=${shown ? "Hide the Context Dock" : "Show the Context Dock"} aria-expanded=${shown}
|
||||
onClick=${toggle}><${Icon} name="dock" /></button>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One file's diff until it's closed: over the page on a phone, beside the dock on a wide screen.
|
||||
* @param {{ open: OpenDiff | null, close: () => void, retry: () => void, ask: (words: string) => void }} props
|
||||
*/
|
||||
export function DiffSheet({ open, close, retry, ask }) {
|
||||
const wide = useWide();
|
||||
useEscape(open ? close : null);
|
||||
if (!open) return null;
|
||||
return html`<div class="sheet peek" role="dialog" aria-modal=${!wide} aria-label=${`Changes to ${open.path}`}>
|
||||
<header class="bar">
|
||||
<span class="title">${open.path}</span>
|
||||
<button type="button" class="close" aria-label="Close the diff" onClick=${close}><${Icon} name="close" /></button>
|
||||
</header>
|
||||
<div class="sheet-body"><${DiffBody} open=${open} retry=${retry} ask=${ask} /></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ open: OpenDiff, retry: () => void, ask: (words: string) => void }} props */
|
||||
function DiffBody({ open, retry, ask }) {
|
||||
if (open.lost) {
|
||||
return html`<p class="diff-note">Connection lost before the diff loaded.
|
||||
<button type="button" class="retry" onClick=${retry}>Try again</button></p>`;
|
||||
}
|
||||
if (open.waiting) return html`<p class="diff-note">Loading diff…</p>`;
|
||||
/** @type {import("./render.js").Piece} */
|
||||
const piece = open.diff ? { kind: "diff", diff: open.diff } : { kind: "diff_failed", error: open.error };
|
||||
return html`<${PickablePiece} piece=${piece} ask=${ask} />`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape closes the sheet, for an iPad with a keyboard. Armed as the sheet reaches the page rather
|
||||
* than after the next paint, so an Escape pressed straight after a pane opens or closes isn't lost.
|
||||
* @param {(() => void) | null} onEscape
|
||||
*/
|
||||
export function useEscape(onEscape) {
|
||||
useLayoutEffect(() => {
|
||||
if (!onEscape) return;
|
||||
/** @param {KeyboardEvent} event */
|
||||
const listener = (event) => event.key === "Escape" && onEscape();
|
||||
addEventListener("keydown", listener);
|
||||
return () => removeEventListener("keydown", listener);
|
||||
}, [onEscape]);
|
||||
}
|
||||
85
crates/luxe-remote/app/files-view.js
Normal file
85
crates/luxe-remote/app/files-view.js
Normal file
@@ -0,0 +1,85 @@
|
||||
// @ts-check
|
||||
// The Files tab: the project as the TUI's FILES tree, drawn by the host so its guides, marks and
|
||||
// change counts are the TUI's, with folders unfolding in place, and a file read in place,
|
||||
// highlighted as the host renders it, with a way to mention it to the agent.
|
||||
|
||||
import { useEffect } from "preact/hooks";
|
||||
import { useRendered } from "./render.js";
|
||||
import { fileMention, treeRows } from "./files.js";
|
||||
import { html, landedIn } from "./html.js";
|
||||
import { useEscape } from "./dock.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { PickablePiece } from "./lines-view.js";
|
||||
|
||||
/** @import { PanelHooks } from "./panel.js" */
|
||||
/** @import { OpenFile } from "./files.js" */
|
||||
|
||||
/** @param {{ hooks: PanelHooks }} props */
|
||||
export function FilesTab({ hooks }) {
|
||||
return html`<${TreeView} hooks=${hooks} />`;
|
||||
}
|
||||
|
||||
/** @param {{ hooks: PanelHooks }} props */
|
||||
function TreeView({ hooks }) {
|
||||
const { files, listings, changes } = hooks;
|
||||
useFreshFolders(hooks);
|
||||
const rows = treeRows(listings.folders.value, files.unfolded.value);
|
||||
const rendered = useRendered({ kind: "tree", rows, changes }, false);
|
||||
return html`<div class="tree-view" onClick=${(/** @type {MouseEvent} */ event) => tapRow(event, hooks)}
|
||||
dangerouslySetInnerHTML=${{ __html: rendered ?? "" }}></div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the root and every open folder afresh when the tree is shown, since the agent may have
|
||||
* changed them since. @param {PanelHooks} hooks
|
||||
*/
|
||||
function useFreshFolders({ files, listings, send }) {
|
||||
useEffect(() => {
|
||||
for (const folder of ["", ...files.unfolded.value]) listings.ask(folder, send, { fresh: true });
|
||||
}, []);
|
||||
}
|
||||
|
||||
/** A tap on a folder unfolds or folds it; one on a file opens it. @param {MouseEvent} event @param {PanelHooks} hooks */
|
||||
export function tapRow(event, { files, github, review, listings, send }) {
|
||||
const row = landedIn(event, "button.tree-row");
|
||||
const folder = row?.dataset.folder;
|
||||
if (folder !== undefined) {
|
||||
files.toggle(folder);
|
||||
if (files.unfolded.value.has(folder)) listings.ask(folder, send, { fresh: true });
|
||||
return;
|
||||
}
|
||||
const file = row?.dataset.file;
|
||||
if (file === undefined) return;
|
||||
github.close();
|
||||
review.close();
|
||||
files.read(file, send);
|
||||
}
|
||||
|
||||
/**
|
||||
* The open file, in the pane a diff opens in: over the page on a phone, beside the tree on a wide
|
||||
* screen, as the TUI peeks a file beside its dock. Escape closes it before the panel.
|
||||
* @param {{ hooks: PanelHooks, wide: boolean }} props
|
||||
*/
|
||||
export function FilePeek({ hooks, wide }) {
|
||||
const { files, send } = hooks;
|
||||
const open = files.open.value;
|
||||
useEscape(open ? files.close : null);
|
||||
if (!open) return null;
|
||||
return html`<div class="sheet peek" role="dialog" aria-modal=${!wide} aria-label=${open.path}>
|
||||
<header class="bar">
|
||||
<span class="title">${open.path}</span>
|
||||
<button type="button" class="mention" onClick=${() => hooks.mention(fileMention(open.path))}>Mention</button>
|
||||
<button type="button" class="close" aria-label="Close the file" onClick=${files.close}><${Icon} name="close" /></button>
|
||||
</header>
|
||||
<div class="sheet-body"><${FileBody} open=${open} retry=${() => files.read(open.path, send)} ask=${hooks.mention} /></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ open: OpenFile, retry: () => void, ask: (words: string) => void }} props */
|
||||
function FileBody({ open, retry, ask }) {
|
||||
if (open.state === "asking") return html`<p class="diff-note">Loading file…</p>`;
|
||||
if (open.state === "lost") {
|
||||
return html`<p class="diff-note">Connection lost. <button type="button" class="retry" onClick=${retry}>Try again</button></p>`;
|
||||
}
|
||||
return html`<${PickablePiece} piece=${open.state === "read" ? { kind: "file", file: open.file } : { kind: "file_failed", error: open.error }} ask=${ask} />`;
|
||||
}
|
||||
109
crates/luxe-remote/app/files.js
Normal file
109
crates/luxe-remote/app/files.js
Normal file
@@ -0,0 +1,109 @@
|
||||
// @ts-check
|
||||
// The Files tab's state: which folders of the tree are open, as the TUI's FILES unfolds them in
|
||||
// place, and the one file open, read with `read_project_file` and matched to its answer by an id no
|
||||
// other client shares, so a late answer for a closed file is dropped. Folders come from the
|
||||
// listings the `@` picker keeps (mentions.js).
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @import { Entry, Listing } from "./mentions.js" */
|
||||
/**
|
||||
* @typedef {{ path: string, requestId: string, state: "asking" | "read" | "failed" | "lost",
|
||||
* file?: any, error?: any }} OpenFile
|
||||
* @typedef {{ kind: "folder", path: string, name: string, depth: number, open: boolean }
|
||||
* | { kind: "file", path: string, name: string, depth: number }
|
||||
* | { kind: "note", depth: number, text: string }} TreeRow
|
||||
*/
|
||||
|
||||
/** Every folder closed and no file open. */
|
||||
export function createFiles() {
|
||||
const unfolded = signal(/** @type {ReadonlySet<string>} */ (new Set()));
|
||||
const open = signal(/** @type {OpenFile | null} */ (null));
|
||||
/** Asks for `path`, showing it as loading until the answer. @param {string} path @param {(frame: Frame) => boolean} send */
|
||||
const read = (path, send) => {
|
||||
const request_id = `file:${crypto.randomUUID()}`;
|
||||
const state = send({ kind: "read_project_file", content: { request_id, path } }) ? "asking" : "lost";
|
||||
open.value = { path, requestId: request_id, state };
|
||||
};
|
||||
/** @param {Frame} frame */
|
||||
const apply = (frame) => (open.value = applyRead(open.value, frame));
|
||||
/** Opens `path` if it's closed and closes it if it's open. @param {string} path */
|
||||
const toggle = (path) => (unfolded.value = toggled(unfolded.value, path));
|
||||
return { unfolded, toggle, open, read, apply, close: () => (open.value = null) };
|
||||
}
|
||||
|
||||
/** `set` with `path` in it if it wasn't, and without it if it was. @param {ReadonlySet<string>} set @param {string} path */
|
||||
export function toggled(set, path) {
|
||||
const next = new Set(set);
|
||||
if (!next.delete(path)) next.add(path);
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows the tree shows: `folder`'s entries at `depth`, and inside each open folder its own, as
|
||||
* the TUI's FILES unfolds in place. A folder with nothing to list yet shows a note instead.
|
||||
* @param {Record<string, Listing>} folders @param {ReadonlySet<string>} unfolded
|
||||
* @param {string} [folder] @param {number} [depth] @returns {TreeRow[]}
|
||||
*/
|
||||
export function treeRows(folders, unfolded, folder = "", depth = 0) {
|
||||
const listing = folders[folder];
|
||||
const note = entriesNote(listing);
|
||||
if (note || !listing) return [{ kind: "note", depth, text: note }];
|
||||
return listing.entries.flatMap((entry) => entryRows(entry, { folders, unfolded, folder, depth }));
|
||||
}
|
||||
|
||||
/**
|
||||
* An entry's row, then, for an open folder, the rows inside it.
|
||||
* @param {Entry} entry
|
||||
* @param {{ folders: Record<string, Listing>, unfolded: ReadonlySet<string>, folder: string, depth: number }} at
|
||||
* @returns {TreeRow[]}
|
||||
*/
|
||||
function entryRows(entry, { folders, unfolded, folder, depth }) {
|
||||
const path = childPath(folder, entry.name);
|
||||
if (entry.kind !== "directory") return [{ kind: "file", path, name: entry.name, depth }];
|
||||
const open = unfolded.has(path);
|
||||
/** @type {TreeRow} */
|
||||
const row = { kind: "folder", path, name: entry.name, depth, open };
|
||||
return open ? [row, ...treeRows(folders, unfolded, path, depth + 1)] : [row];
|
||||
}
|
||||
|
||||
/** What to say in place of a folder's entries, or "" when there are some to show. @param {Listing | undefined} listing */
|
||||
export function entriesNote(listing) {
|
||||
if (listing?.entries.length) return "";
|
||||
if (!listing || listing.state === "asking") return "Loading…";
|
||||
return listing.state === "failed" ? "Couldn't list this folder" : "Empty folder";
|
||||
}
|
||||
|
||||
/**
|
||||
* The open file after `frame`: answered, or lost when the connection began again before it was.
|
||||
* @param {OpenFile | null} open @param {Frame} frame @returns {OpenFile | null}
|
||||
*/
|
||||
export function applyRead(open, { kind, content }) {
|
||||
if (open?.state !== "asking") return open;
|
||||
if (kind === "ready") return { ...open, state: "lost" };
|
||||
if (content?.request_id !== open.requestId) return open;
|
||||
if (kind === "project_file_read") return { ...open, state: "read", file: content.file };
|
||||
if (kind === "project_file_read_failed") return { ...open, state: "failed", error: content.error };
|
||||
return open;
|
||||
}
|
||||
|
||||
/** `name` inside `folder`, as the protocol writes a project path. @param {string} folder @param {string} name */
|
||||
export function childPath(folder, name) {
|
||||
return folder ? `${folder}/${name}` : name;
|
||||
}
|
||||
|
||||
/** What a mention of the file at `path` adds to the draft, as a picked `@` mention writes it. @param {string} path */
|
||||
export function fileMention(path) {
|
||||
return `\`${path}\``;
|
||||
}
|
||||
|
||||
/**
|
||||
* `text` with `words` added at its end, a space apart, and the caret after.
|
||||
* @param {string} text @param {string} words
|
||||
*/
|
||||
export function withMention(text, words) {
|
||||
const gap = text && !/\s$/.test(text) ? " " : "";
|
||||
const next = `${text}${gap}${words} `;
|
||||
return { text: next, caret: next.length, placed: true };
|
||||
}
|
||||
135
crates/luxe-remote/app/folders.js
Normal file
135
crates/luxe-remote/app/folders.js
Normal file
@@ -0,0 +1,135 @@
|
||||
// @ts-check
|
||||
// Starting a session: a page of its own, with the folders you've worked in narrowed by what you
|
||||
// type, and any other folder you type.
|
||||
//
|
||||
// The bridge answers a start once the session can be joined, which takes a few seconds, so the
|
||||
// page says which folder it's starting in meanwhile and opens the session when it's ready.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { fieldOf, html } from "./html.js";
|
||||
|
||||
/**
|
||||
* A place a session can start, as `GET /api/folders` lists it.
|
||||
* @typedef {{ path: string, name: string, sessions: number }} Folder
|
||||
* @typedef {{ folders: Folder[], herdr: boolean }} Folders
|
||||
*/
|
||||
|
||||
/** @type {import("@preact/signals").Signal<Folders | null>} */
|
||||
const folders = signal(null);
|
||||
/** Whether this bridge starts sessions at all; one run without a launcher says not. */
|
||||
export const offered = signal(true);
|
||||
const starting = signal("");
|
||||
const problem = signal("");
|
||||
|
||||
/** Reads the folders again. @param {typeof fetch} get */
|
||||
export async function refreshFolders(get = fetch) {
|
||||
const response = await get("/api/folders");
|
||||
if (response.status === 501) offered.value = false;
|
||||
if (!response.ok) return;
|
||||
folders.value = await response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a session in `folder`, resolving to its id once it can be joined; the host's reason
|
||||
* when it can't. @param {string} folder @param {typeof fetch} post
|
||||
*/
|
||||
export async function startIn(folder, post = fetch) {
|
||||
const response = await post("/api/sessions", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ folder }),
|
||||
});
|
||||
if (!response.ok) throw new Error((await response.text()) || `starting failed: ${response.status}`);
|
||||
return (await response.json()).session.session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders `typed` could mean, best first: a name that starts with it, then a name holding it,
|
||||
* then a path holding it; nothing typed starts every name, so all of them come back in order.
|
||||
* A leading `~/` is dropped, since the phone can't know which folder is home, and the rest still
|
||||
* finds the path under it. @param {Folder[]} all @param {string} typed
|
||||
*/
|
||||
export function matchFolders(all, typed) {
|
||||
const needle = typed.trim().replace(/^~[\\/]?/, "").toLowerCase();
|
||||
/** @param {Folder} folder */
|
||||
const rank = (folder) => {
|
||||
const name = folder.name.toLowerCase();
|
||||
if (name.startsWith(needle)) return 0;
|
||||
if (name.includes(needle)) return 1;
|
||||
return folder.path.toLowerCase().includes(needle) ? 2 : 3;
|
||||
};
|
||||
const ranked = all.map((folder) => ({ folder, rank: rank(folder) })).filter((entry) => entry.rank < 3);
|
||||
return ranked.sort((a, b) => a.rank - b.rank).map((entry) => entry.folder);
|
||||
}
|
||||
|
||||
/** @param {string} folder */
|
||||
async function start(folder) {
|
||||
starting.value = folder;
|
||||
problem.value = "";
|
||||
try {
|
||||
location.hash = `#/session/${encodeURIComponent(await startIn(folder))}`;
|
||||
} catch (error) {
|
||||
problem.value = /** @type {Error} */ (error).message;
|
||||
} finally {
|
||||
starting.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
export function NewSession() {
|
||||
const [typed, setTyped] = useState("");
|
||||
useEffect(() => {
|
||||
refreshFolders().catch((error) => (problem.value = `couldn't read the folders: ${error}`));
|
||||
}, []);
|
||||
return html`
|
||||
<header class="bar"><a class="back" href="#/" aria-label="Sessions">‹</a><span class="title">New session</span></header>
|
||||
<main class="new-session">
|
||||
<${FolderField} typed=${typed} setTyped=${setTyped} />
|
||||
${problem.value ? html`<p class="problem">${problem.value}</p>` : null}
|
||||
<${Where} />
|
||||
<${Suggestions} typed=${typed} />
|
||||
</main>`;
|
||||
}
|
||||
|
||||
/** @param {{ typed: string, setTyped: (typed: string) => void }} props */
|
||||
function FolderField({ typed, setTyped }) {
|
||||
const asked = typed.trim();
|
||||
/** @param {SubmitEvent} event */
|
||||
const submit = (event) => {
|
||||
event.preventDefault();
|
||||
if (asked) start(asked);
|
||||
};
|
||||
return html`<form class="other-folder" onSubmit=${submit}>
|
||||
<input type="text" placeholder="Folder path, like ~/code/app" value=${typed} autocapitalize="off"
|
||||
autocorrect="off" spellcheck="false" enterkeyhint="go" aria-label="Folder"
|
||||
onInput=${(/** @type {Event} */ event) => setTyped(fieldOf(event).value)} />
|
||||
<button type="submit" disabled=${!asked || starting.value !== ""}>
|
||||
${starting.value === asked && asked ? "Starting…" : "Start"}</button>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
function Where() {
|
||||
if (!folders.value) return null;
|
||||
const herdr = folders.value.herdr;
|
||||
return html`<p class="dim">${herdr ? "Opens in a herdr pane on your computer." : "Runs until luxe remote stops."}</p>`;
|
||||
}
|
||||
|
||||
/** @param {{ typed: string }} props */
|
||||
function Suggestions({ typed }) {
|
||||
if (!folders.value) return html`<p class="dim">Loading folders…</p>`;
|
||||
const matched = matchFolders(folders.value.folders, typed);
|
||||
if (!matched.length) return html`<p class="dim">${typed.trim() ? "No matching folders." : "No recent folders."}</p>`;
|
||||
return html`<ul class="sessions">
|
||||
${matched.map((folder) => html`<li key=${folder.path}><${FolderRow} folder=${folder} /></li>`)}
|
||||
</ul>`;
|
||||
}
|
||||
|
||||
/** @param {{ folder: Folder }} props */
|
||||
function FolderRow({ folder }) {
|
||||
const busy = starting.value !== "";
|
||||
const running = folder.sessions ? ` · ${folder.sessions} running` : "";
|
||||
return html`<button type="button" class="session folder" disabled=${busy} onClick=${() => start(folder.path)}>
|
||||
<span class="name">${starting.value === folder.path ? `Starting in ${folder.name}…` : folder.name}</span>
|
||||
<span class="dim path">${folder.path}${running}</span>
|
||||
</button>`;
|
||||
}
|
||||
29
crates/luxe-remote/app/fonts/LICENSES.md
Normal file
29
crates/luxe-remote/app/fonts/LICENSES.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# Fonts
|
||||
|
||||
Subset copies built by `scripts/remote-fonts.sh`, of the same two faces the website uses. The
|
||||
licensing is as `web/public/fonts/LICENSES.md` sets out: both are SIL Open Font License 1.1 with no
|
||||
Reserved Font Name, so a subset may keep its name, and the notice and license travel with the
|
||||
files, hence this file and the two `OFL-*.txt` beside it.
|
||||
|
||||
## JetBrains Mono Nerd Font Mono
|
||||
|
||||
Copyright 2020 The JetBrains Mono Project Authors <https://github.com/JetBrains/JetBrainsMono> ·
|
||||
SIL Open Font License 1.1 · full text in `OFL-JetBrainsMono.txt`.
|
||||
|
||||
Patched with [Nerd Fonts](https://github.com/ryanoasis/nerd-fonts) 3.5.1, whose patcher is MIT
|
||||
licensed and whose added glyph sets carry their own licenses. The private-use codepoints this
|
||||
subset keeps come from Material Design Icons (Apache-2.0), Font Awesome (OFL-1.1), Powerline
|
||||
Extra (MIT) and [Codicons](https://github.com/microsoft/vscode-codicons) (© Microsoft Corporation,
|
||||
CC BY 4.0).
|
||||
|
||||
Subset to Latin, Greek, Cyrillic, punctuation, arrows, maths and box drawing, plus every glyph Luxe
|
||||
draws. Regular (400), Bold (700) and Italic.
|
||||
|
||||
## Adwaita Mono Nerd Font Mono
|
||||
|
||||
Copyright (c) 2016, The Inter Project Authors · Copyright (c) 2015-2025, Renzhi Li (aka. Belleve
|
||||
Invis) · Copyright (c) 2025, Jamie Gravendeel · Copyright (c) 2025, Florian Müllner ·
|
||||
<https://gitlab.gnome.org/GNOME/adwaita-fonts> · SIL Open Font License 1.1 · full text in
|
||||
`OFL-AdwaitaMono.txt`. Patched with Nerd Fonts, as above.
|
||||
|
||||
Subset to only the marks Luxe draws that JetBrains Mono lacks, on the same 0.6em cell.
|
||||
96
crates/luxe-remote/app/fonts/OFL-AdwaitaMono.txt
Normal file
96
crates/luxe-remote/app/fonts/OFL-AdwaitaMono.txt
Normal file
@@ -0,0 +1,96 @@
|
||||
Copyright (c) 2016, The Inter Project Authors (https://github.com/rsms/inter)
|
||||
Copyright (c) 2015-2025, Renzhi Li (aka. Belleve Invis, belleve@typeof.net)
|
||||
Copyright (c) 2025, Jamie Gravendeel (https://jamie.garden)
|
||||
Copyright (c) 2025, Florian Müllner
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
93
crates/luxe-remote/app/fonts/OFL-JetBrainsMono.txt
Normal file
93
crates/luxe-remote/app/fonts/OFL-JetBrainsMono.txt
Normal file
@@ -0,0 +1,93 @@
|
||||
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://openfontlicense.org
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
crates/luxe-remote/app/fonts/adwaita-mono-bold.woff2
Normal file
BIN
crates/luxe-remote/app/fonts/adwaita-mono-bold.woff2
Normal file
Binary file not shown.
BIN
crates/luxe-remote/app/fonts/adwaita-mono-regular.woff2
Normal file
BIN
crates/luxe-remote/app/fonts/adwaita-mono-regular.woff2
Normal file
Binary file not shown.
BIN
crates/luxe-remote/app/fonts/jetbrains-mono-bold.woff2
Normal file
BIN
crates/luxe-remote/app/fonts/jetbrains-mono-bold.woff2
Normal file
Binary file not shown.
BIN
crates/luxe-remote/app/fonts/jetbrains-mono-italic.woff2
Normal file
BIN
crates/luxe-remote/app/fonts/jetbrains-mono-italic.woff2
Normal file
Binary file not shown.
BIN
crates/luxe-remote/app/fonts/jetbrains-mono-regular.woff2
Normal file
BIN
crates/luxe-remote/app/fonts/jetbrains-mono-regular.woff2
Normal file
Binary file not shown.
8
crates/luxe-remote/app/generated/wordmark.svg
Normal file
8
crates/luxe-remote/app/generated/wordmark.svg
Normal file
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 154" width="440" height="154" data-cell="10 22" data-drift-depth="0.55" role="img" aria-label="Luxe">
|
||||
<title>Luxe</title>
|
||||
<path fill="var(--luxe-wordmark-1, currentColor)" d="M10 11h10v11h-10z M20 11h10v11h-10z M30 11h10v11h-10z M40 11h10v11h-10z M10 22h10v11h-10z M20 22h10v11h-10z M30 22h20v22h-20z M30 44h20v22h-20z M30 66h20v22h-20z M30 88h20v22h-20z M30 110h20v22h-20z M50 121h10v11h-10z M60 121h10v11h-10z M70 121h10v11h-10z M40 132h10v11h-10z M50 132h10v11h-10z M60 132h10v11h-10z M70 132h10v11h-10z"/>
|
||||
<path fill="var(--luxe-wordmark-2, currentColor)" d="M110 44h20v22h-20z M170 44h20v22h-20z M110 66h20v22h-20z M170 66h20v22h-20z M110 88h20v22h-20z M170 88h20v22h-20z M110 110h20v22h-20z M130 121h10v11h-10z M140 121h10v11h-10z M150 121h10v11h-10z M160 110h30v22h-30z M120 132h10v11h-10z M130 132h10v11h-10z M140 132h10v11h-10z M150 132h10v11h-10z M170 132h10v11h-10z M180 132h10v11h-10z"/>
|
||||
<path fill="var(--luxe-wordmark-3, currentColor)" d="M210 44h10v11h-10z M220 44h20v22h-20z M260 44h20v22h-20z M280 44h10v11h-10z M230 66h40v22h-40z M230 99h10v11h-10z M240 88h20v22h-20z M260 99h10v11h-10z M220 121h10v11h-10z M230 110h10v22h-10z M240 110h10v11h-10z M250 110h10v11h-10z M260 110h10v22h-10z M270 121h10v11h-10z M210 132h10v11h-10z M220 132h10v11h-10z M230 132h10v11h-10z M260 132h10v11h-10z M270 132h10v11h-10z M280 132h10v11h-10z"/>
|
||||
<path fill="var(--luxe-wordmark-4, currentColor)" d="M320 55h10v11h-10z M330 44h40v22h-40z M370 55h10v11h-10z M310 66h20v22h-20z M330 77h10v11h-10z M340 77h10v11h-10z M350 77h10v11h-10z M360 77h10v11h-10z M370 66h20v22h-20z M310 88h20v22h-20z M330 88h10v11h-10z M340 88h10v11h-10z M350 88h10v11h-10z M360 88h10v11h-10z M370 88h10v11h-10z M380 88h10v11h-10z M310 110h10v11h-10z M320 110h20v22h-20z M340 121h10v11h-10z M350 121h10v11h-10z M360 121h10v11h-10z M370 121h10v11h-10z M380 110h10v22h-10z M330 132h10v11h-10z M340 132h10v11h-10z M350 132h10v11h-10z M360 132h10v11h-10z M370 132h10v11h-10z"/>
|
||||
<path fill="var(--luxe-wordmark-5, currentColor)" d="M420 110h20v22h-20z M420 132h10v11h-10z M430 132h10v11h-10z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
147
crates/luxe-remote/app/github-view.js
Normal file
147
crates/luxe-remote/app/github-view.js
Normal file
@@ -0,0 +1,147 @@
|
||||
// @ts-check
|
||||
// The GitHub tab: `/github`'s sections as badges, the shown one's rows as the TUI draws them, and
|
||||
// a tapped row open in the peek, its header over an Overview and a Conversation. The host draws
|
||||
// every row, check and card; the app only says which, and owns the taps.
|
||||
|
||||
import { useEffect } from "preact/hooks";
|
||||
import { githubMention, rowSubject, shownSection } from "./github.js";
|
||||
import { useRendered } from "./render.js";
|
||||
import { html, landedIn } from "./html.js";
|
||||
import { useEscape } from "./dock.js";
|
||||
import { Icon } from "./icons.js";
|
||||
|
||||
/** @import { PanelHooks } from "./panel.js" */
|
||||
/** @import { OpenItem, Reading, Subject } from "./github.js" */
|
||||
|
||||
/** @param {{ hooks: PanelHooks }} props */
|
||||
export function GithubTab({ hooks }) {
|
||||
const { github, send } = hooks;
|
||||
useEffect(() => void github.list(send), []);
|
||||
const listing = github.listing.value;
|
||||
if (listing.state === "lost" && !listing.sections.length) return html`<${Lost} retry=${() => github.list(send)} />`;
|
||||
if (!listing.sections.length) return html`<p class="diff-note">${listing.state === "listed" ? "No sections" : "Loading…"}</p>`;
|
||||
const shown = shownSection(listing.sections, github.section.value);
|
||||
return html`<${Sections} sections=${listing.sections} shown=${shown.name} pick=${github.pick} />
|
||||
<${List} hooks=${hooks} section=${shown} />`;
|
||||
}
|
||||
|
||||
/** @param {{ retry: () => void }} props */
|
||||
function Lost({ retry }) {
|
||||
return html`<p class="diff-note">Connection lost. <button type="button" class="retry" onClick=${retry}>Try again</button></p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The section tabs on one line, as `/github` draws them: the open one a slab, the rest quiet
|
||||
* words, each with how many it holds, scrolling sideways when they don't fit.
|
||||
* @param {{ sections: any[], shown: string, pick: (name: string) => void }} props
|
||||
*/
|
||||
function Sections({ sections, shown, pick }) {
|
||||
return html`<nav class="tabs gh-sections" aria-label="GitHub sections">
|
||||
${sections.map(({ name, items, total }) => html`<button type="button" key=${name} class="tab" aria-pressed=${name === shown}
|
||||
onClick=${() => pick(name)}><span class=${name === shown ? "badge picked" : "gh-tab"}>${name} ${total ?? items.length}</span></button>`)}
|
||||
</nav>`;
|
||||
}
|
||||
|
||||
/** @param {{ hooks: PanelHooks, section: any }} props */
|
||||
function List({ hooks, section }) {
|
||||
const { repository, at } = hooks.github.listing.value;
|
||||
const rendered = useRendered({ kind: "github_list", repository, section, now: at }, false);
|
||||
return html`<div class="gh-view" onClick=${(/** @type {MouseEvent} */ event) => tapGithubRow(event, hooks)}
|
||||
dangerouslySetInnerHTML=${{ __html: rendered ?? "" }}></div>`;
|
||||
}
|
||||
|
||||
/** A tap on a row opens it in the peek, in place of any open file. @param {MouseEvent} event @param {PanelHooks} hooks */
|
||||
export function tapGithubRow(event, { github, files, review, send }) {
|
||||
const row = landedIn(event, "button.gh-row");
|
||||
if (!row) return;
|
||||
files.close();
|
||||
review.close();
|
||||
github.read(rowSubject(row, github.listing.value.repository), send);
|
||||
}
|
||||
|
||||
/**
|
||||
* The open item, in the pane a file opens in. Escape closes it before the panel.
|
||||
* @param {{ hooks: PanelHooks, wide: boolean }} props
|
||||
*/
|
||||
export function GithubPeek({ hooks, wide }) {
|
||||
const { github } = hooks;
|
||||
const item = github.open.value;
|
||||
useEscape(item ? github.close : null);
|
||||
if (!item) return null;
|
||||
const here = github.listing.value.repository;
|
||||
const name = `${item.subject.repository ?? ""}#${item.subject.number}`;
|
||||
return html`<div class="sheet peek" role="dialog" aria-modal=${!wide} aria-label=${name}>
|
||||
<header class="bar">
|
||||
<span class="title">${name}</span>
|
||||
<a class="mention" href=${item.subject.url} target="_blank" rel="noopener noreferrer">GitHub</a>
|
||||
<button type="button" class="mention" onClick=${() => hooks.mention(githubMention(item.subject, here))}>Mention</button>
|
||||
<button type="button" class="close" aria-label="Close" onClick=${github.close}><${Icon} name="close" /></button>
|
||||
</header>
|
||||
<div class="sheet-body gh-view" onClick=${(/** @type {MouseEvent} */ event) => tapDetail(event, hooks)}><${Detail} item=${item} hooks=${hooks} /></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ item: OpenItem, hooks: PanelHooks }} props */
|
||||
function Detail({ item, hooks }) {
|
||||
const retry = () => hooks.github.read(item.subject, hooks.send);
|
||||
const { overview } = item;
|
||||
if (overview.state !== "read") return html`<${Waiting} reading=${overview} retry=${retry} what="overview" />`;
|
||||
const shown = item.tab === "overview" ? overview : item.conversation;
|
||||
return html`<${Piece} piece=${{ kind: "github_header", overview: overview.value, now: overview.at }} />
|
||||
<${DetailTabs} tab=${item.tab} show=${hooks.github.show} said=${overview.value.overview?.conversation_count ?? 0} />
|
||||
${shown.state === "read" ? html`<${Piece} piece=${detailPiece(item)} />` : html`<${Waiting} reading=${shown} retry=${retry} what="conversation" />`}`;
|
||||
}
|
||||
|
||||
/** The shown tab's piece. @param {OpenItem} item */
|
||||
function detailPiece({ tab, overview, conversation }) {
|
||||
if (tab === "overview") return { kind: "github_overview", overview: overview.value, now: overview.at };
|
||||
const opened_by_you = overview.value.overview?.viewer?.author === true;
|
||||
return { kind: "github_conversation", entries: conversation.value, now: conversation.at, opened_by_you };
|
||||
}
|
||||
|
||||
/** @param {{ reading: Reading, retry: () => void, what: string }} props */
|
||||
function Waiting({ reading, retry, what }) {
|
||||
if (reading.state === "lost") return html`<${Lost} retry=${retry} />`;
|
||||
if (reading.state === "failed") return html`<p class="diff-note">${reading.error}</p>`;
|
||||
return html`<p class="diff-note">Reading the ${what}…</p>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The detail's tabs, on the TUI's tab line, Conversation counting what's been said.
|
||||
* @param {{ tab: import("./github.js").DetailTab, show: (tab: import("./github.js").DetailTab) => void, said: number }} props
|
||||
*/
|
||||
function DetailTabs({ tab, show, said }) {
|
||||
/** @type {[import("./github.js").DetailTab, string][]} */
|
||||
const tabs = [["overview", "Overview"], ["conversation", said ? `Conversation ${said}` : "Conversation"]];
|
||||
return html`<nav class="tabs gh-sections" role="tablist" aria-label="Views">
|
||||
${tabs.map(([id, title]) => html`<button type="button" role="tab" key=${id} class="tab" aria-selected=${id === tab}
|
||||
onClick=${() => show(id)}><span class=${id === tab ? "badge picked" : "gh-tab"}>${title}</span></button>`)}
|
||||
</nav>`;
|
||||
}
|
||||
|
||||
/** @param {{ piece: import("./render.js").Piece }} props */
|
||||
function Piece({ piece }) {
|
||||
const rendered = useRendered(piece, false);
|
||||
return html`<div dangerouslySetInnerHTML=${{ __html: rendered ?? "" }}></div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Taps inside the detail: "open #N" opens that pull request, "more lines in Conversation" shows
|
||||
* it, and "Show all" unfolds a long comment. @param {MouseEvent} event @param {PanelHooks} hooks
|
||||
*/
|
||||
export function tapDetail(event, { github, send }) {
|
||||
const item = github.open.value;
|
||||
const open = landedIn(event, "button.gh-open");
|
||||
if (item && open) return github.read(linkedSubject(item.subject, Number(open.dataset.number), github.listing.value.repository), send);
|
||||
if (landedIn(event, "button.gh-more")) return github.show("conversation");
|
||||
landedIn(event, "button.gh-unfold")?.closest(".gh-card")?.classList.remove("folded");
|
||||
}
|
||||
|
||||
/**
|
||||
* The pull request `number` in the same repository as `subject`.
|
||||
* @param {Subject} subject @param {number} number @param {string | null} here @returns {Subject}
|
||||
*/
|
||||
export function linkedSubject(subject, number, here) {
|
||||
const repository = subject.repository ?? here;
|
||||
return { number, pull_request: true, repository: subject.repository, url: `https://github.com/${repository}/pull/${number}` };
|
||||
}
|
||||
250
crates/luxe-remote/app/github.css
Normal file
250
crates/luxe-remote/app/github.css
Normal file
@@ -0,0 +1,250 @@
|
||||
/* The GitHub tab and its peek, as /github draws them: rows on two lines, the second quiet; a
|
||||
detail of facts beside their marks in a label column; and the conversation as cards washed in
|
||||
their tone, the hue mixed 9% into the canvas as the TUI tints a card */
|
||||
|
||||
/* The sections are the picker's tab line: one row, the open tab a slab on the selection surface
|
||||
in the accent, the rest muted words padded to the same footprint */
|
||||
.gh-sections {
|
||||
flex-wrap: nowrap;
|
||||
gap: 0;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.gh-sections::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.gh-sections .tab {
|
||||
flex: none;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.badge.picked {
|
||||
--slab: var(--luxe-selected-bg, #2c2925);
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
.gh-tab {
|
||||
padding: 0 2ch;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.gh-view {
|
||||
padding: 0 1.5ch 1lh;
|
||||
}
|
||||
|
||||
.gh-count,
|
||||
.gh-note {
|
||||
margin: 0.5lh 0;
|
||||
}
|
||||
|
||||
/* A row is the TUI's two lines, the tap target the whole of both */
|
||||
.gh-row {
|
||||
display: block;
|
||||
width: calc(100% + 3ch);
|
||||
min-height: var(--tap);
|
||||
margin: 0 -1.5ch;
|
||||
padding: 0.35lh 1.5ch;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.gh-row:active {
|
||||
background: var(--luxe-tool-bg, #2a2724);
|
||||
}
|
||||
|
||||
.gh-line {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.gh-mark {
|
||||
flex: none;
|
||||
width: 2ch;
|
||||
}
|
||||
|
||||
.gh-title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.gh-right {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
padding-left: 1ch;
|
||||
}
|
||||
|
||||
/* the second line starts under the title, past the mark */
|
||||
.gh-sub {
|
||||
padding-left: 2ch;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.gh-who {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* The detail's header: what it is, then who and where, then its state and labels as chips */
|
||||
.gh-head {
|
||||
margin-bottom: 0.5lh;
|
||||
}
|
||||
|
||||
.gh-heading {
|
||||
margin: 0.5lh 0 0.25lh;
|
||||
font-size: inherit;
|
||||
font-weight: bold;
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
}
|
||||
|
||||
.gh-meta,
|
||||
.gh-chips {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.gh-state,
|
||||
.gh-label-chip {
|
||||
display: inline-block;
|
||||
padding: 0 1ch;
|
||||
border-radius: var(--corner);
|
||||
}
|
||||
|
||||
/* the state chip is cut from its own color, the canvas as ink */
|
||||
.gh-state {
|
||||
color: var(--luxe-background, #12100e);
|
||||
background: currentColor;
|
||||
}
|
||||
|
||||
.gh-state.hue-success { background: var(--luxe-success, #81caa0); }
|
||||
.gh-state.hue-error { background: var(--luxe-error, #e68485); }
|
||||
.gh-state.hue-secondary { background: var(--luxe-accent-secondary, #d2a5cd); }
|
||||
.gh-state.hue-muted { background: var(--luxe-muted, #97938c); }
|
||||
|
||||
.gh-label-chip {
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
}
|
||||
|
||||
.gh-view .gh-sections {
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
.gh-section {
|
||||
display: flex;
|
||||
margin: 1lh 0 0.25lh;
|
||||
font-size: inherit;
|
||||
font-weight: bold;
|
||||
color: var(--luxe-md-heading, #ddc084);
|
||||
}
|
||||
|
||||
/* a fact: its mark, its label in a column, then the evidence wrapping under itself */
|
||||
.gh-check {
|
||||
display: grid;
|
||||
grid-template-columns: 2ch minmax(8ch, 15ch) 1fr;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.gh-evidence {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.gh-open,
|
||||
.gh-more,
|
||||
.gh-unfold {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.gh-more,
|
||||
.gh-unfold {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* The conversation: each entry a card, its frame and wash its tone */
|
||||
/* the column never grows past the pane, so a long unbroken word wraps instead of pushing the
|
||||
cards off the screen */
|
||||
.gh-conversation {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.75lh;
|
||||
padding-top: 0.5lh;
|
||||
}
|
||||
|
||||
.gh-body {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.gh-card {
|
||||
--tone: var(--luxe-muted, #97938c);
|
||||
padding: 0.25lh 1ch;
|
||||
border: 1px solid color-mix(in srgb, var(--tone) 45%, transparent);
|
||||
border-radius: var(--corner);
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
}
|
||||
|
||||
.gh-card.tone-quiet { background: none; }
|
||||
.gh-card.tone-approved { --tone: var(--luxe-success, #81caa0); }
|
||||
.gh-card.tone-changes,
|
||||
.gh-card.tone-unresolved {
|
||||
border-color: var(--tone);
|
||||
background: color-mix(in srgb, var(--tone) 9%, var(--luxe-background, #12100e));
|
||||
}
|
||||
.gh-card.tone-changes { --tone: var(--luxe-error, #e68485); }
|
||||
.gh-card.tone-unresolved { --tone: var(--luxe-info, #85c7d7); }
|
||||
|
||||
.gh-card-title {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.gh-mine {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
/* a long comment shows its first lines until it's unfolded */
|
||||
.gh-card.folded .gh-body {
|
||||
max-height: 6lh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.gh-card:not(.folded) .gh-unfold {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* A thread opens and closes itself, its fold mark the TUI's */
|
||||
.gh-thread summary {
|
||||
list-style: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.gh-thread summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.gh-thread summary::before {
|
||||
content: "\25b8 ";
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.gh-thread[open] summary::before {
|
||||
content: "\25be ";
|
||||
}
|
||||
|
||||
.gh-last {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.gh-thread[open] .gh-last {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.gh-reply {
|
||||
margin: 0.5lh 0 0 4ch;
|
||||
}
|
||||
119
crates/luxe-remote/app/github.js
Normal file
119
crates/luxe-remote/app/github.js
Normal file
@@ -0,0 +1,119 @@
|
||||
// @ts-check
|
||||
// The GitHub tab's state: the sections `list_github` brings, which one is shown, and the one pull
|
||||
// request or issue open, its overview and conversation read side by side. Everything here reads;
|
||||
// a joined session runs with GitHub writes off, so nothing offers one.
|
||||
//
|
||||
// An answer is matched to what was asked by its number and repository, so a late answer for an
|
||||
// item already closed is dropped. Each answer keeps the moment it came, the clock its ages are
|
||||
// drawn from, so a redraw asks the host for the same piece and gets it from the cache.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/**
|
||||
* @typedef {{ number: number, pull_request: boolean, repository: string | null, url: string }} Subject
|
||||
* @typedef {{ state: "asking" | "read" | "failed" | "lost", value?: any, error?: string, at?: number }} Reading
|
||||
* @typedef {{ subject: Subject, tab: DetailTab, overview: Reading, conversation: Reading }} OpenItem
|
||||
* @typedef {"overview" | "conversation"} DetailTab
|
||||
* @typedef {{ state: "idle" | "asking" | "listed" | "lost", repository: string | null, sections: any[], at: number }} GithubListing
|
||||
*/
|
||||
|
||||
/** Nothing listed and nothing open. */
|
||||
export function createGithub() {
|
||||
const listing = signal(/** @type {GithubListing} */ ({ state: "idle", repository: null, sections: [], at: 0 }));
|
||||
const section = signal(/** @type {string | null} */ (null));
|
||||
const open = signal(/** @type {OpenItem | null} */ (null));
|
||||
/** Asks for every section afresh, keeping the last rows up meanwhile. @param {(frame: Frame) => boolean} send */
|
||||
const list = (send) => (listing.value = { ...listing.value, state: send({ kind: "list_github", content: {} }) ? "asking" : "lost" });
|
||||
/** Opens `subject`, asking for its overview and its conversation. @param {Subject} subject @param {(frame: Frame) => boolean} send */
|
||||
const read = (subject, send) => (open.value = opened(subject, send));
|
||||
/** @param {Frame} frame */
|
||||
const apply = (frame) => {
|
||||
listing.value = applyListed(listing.value, frame);
|
||||
open.value = applyItem(open.value, frame);
|
||||
};
|
||||
/** @param {DetailTab} tab */
|
||||
const show = (tab) => open.value && (open.value = { ...open.value, tab });
|
||||
return { listing, section, open, list, read, apply, show, pick: (/** @type {string} */ name) => (section.value = name), close: () => (open.value = null) };
|
||||
}
|
||||
|
||||
/** Seconds since the Unix epoch, the clock the host draws ages from. */
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
|
||||
/** @param {Subject} subject @param {(frame: Frame) => boolean} send @returns {OpenItem} */
|
||||
function opened(subject, send) {
|
||||
const content = { number: subject.number, pull_request: subject.pull_request, repository: subject.repository };
|
||||
const sent = send({ kind: "read_github_overview", content }) && send({ kind: "read_github_conversation", content });
|
||||
/** @type {Reading} */
|
||||
const reading = { state: sent ? "asking" : "lost" };
|
||||
return { subject, tab: "overview", overview: reading, conversation: reading };
|
||||
}
|
||||
|
||||
/**
|
||||
* The listing after `frame`: listed, or lost when the connection began again before it was.
|
||||
* @param {GithubListing} listing @param {Frame} frame @returns {GithubListing}
|
||||
*/
|
||||
export function applyListed(listing, { kind, content }) {
|
||||
if (listing.state !== "asking") return listing;
|
||||
if (kind === "ready") return { ...listing, state: "lost" };
|
||||
if (kind !== "github_listed") return listing;
|
||||
return { state: "listed", repository: content.repository ?? null, sections: content.sections ?? [], at: now() };
|
||||
}
|
||||
|
||||
/**
|
||||
* The open item after `frame`: each half read, failed, or lost when the connection began again.
|
||||
* @param {OpenItem | null} item @param {Frame} frame @returns {OpenItem | null}
|
||||
*/
|
||||
export function applyItem(item, { kind, content }) {
|
||||
if (!item) return item;
|
||||
if (kind === "ready") return { ...item, overview: lost(item.overview), conversation: lost(item.conversation) };
|
||||
if (!answers(item.subject, content)) return item;
|
||||
if (kind === "github_overview_read" && item.overview.state === "asking") {
|
||||
return { ...item, overview: answered(content.overview, content.error) };
|
||||
}
|
||||
if (kind === "github_conversation_read" && item.conversation.state === "asking") {
|
||||
return { ...item, conversation: answered(content.entries, content.error) };
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
/** @param {Reading} reading @returns {Reading} */
|
||||
const lost = (reading) => (reading.state === "asking" ? { state: "lost" } : reading);
|
||||
|
||||
/** @param {any} value @param {string | null | undefined} error @returns {Reading} */
|
||||
const answered = (value, error) => (error ? { state: "failed", error, at: now() } : { state: "read", value, at: now() });
|
||||
|
||||
/** Whether an answer is for `subject`: its number, and its repository when one was named. @param {Subject} subject @param {any} content */
|
||||
function answers(subject, content) {
|
||||
return content?.number === subject.number && (content.repository ?? null) === subject.repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which section the tab shows: the one picked while it's still there, else the first with rows,
|
||||
* as the TUI opens on the first tab with something in it.
|
||||
* @param {any[]} sections @param {string | null} picked
|
||||
*/
|
||||
export function shownSection(sections, picked) {
|
||||
return sections.find((section) => section.name === picked) ?? sections.find((section) => section.items?.length) ?? sections[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* A tapped row's subject, from the data the host drew on it. The checkout's own repository is
|
||||
* left unnamed, as the TUI asks for it. @param {HTMLElement} row @param {string | null} here
|
||||
* @returns {Subject}
|
||||
*/
|
||||
export function rowSubject(row, here) {
|
||||
const repository = row.dataset.repository || null;
|
||||
return {
|
||||
number: Number(row.dataset.number),
|
||||
pull_request: row.dataset.pull === "true",
|
||||
repository: repository === here ? null : repository,
|
||||
url: row.dataset.url ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** What a mention of `subject` adds to the draft: what it is and where, which the agent can read. @param {Subject} subject @param {string | null} here */
|
||||
export function githubMention({ number, pull_request, repository, url }, here) {
|
||||
const noun = pull_request ? "pull request" : "issue";
|
||||
return `${noun} ${repository ?? here ?? ""}#${number} (${url})`;
|
||||
}
|
||||
25
crates/luxe-remote/app/html.js
Normal file
25
crates/luxe-remote/app/html.js
Normal file
@@ -0,0 +1,25 @@
|
||||
// @ts-check
|
||||
// Tagged templates instead of JSX, so the browser runs the files as they are written.
|
||||
import { h } from "preact";
|
||||
import htm from "htm";
|
||||
|
||||
export const html = htm.bind(h);
|
||||
|
||||
/**
|
||||
* The field an event came from. Templates don't type their handlers' events, so the one cast the
|
||||
* app's inputs need lives here.
|
||||
* @param {Event} event @returns {HTMLInputElement}
|
||||
*/
|
||||
export function fieldOf(event) {
|
||||
return /** @type {HTMLInputElement} */ (event.target);
|
||||
}
|
||||
|
||||
/**
|
||||
* The element matching `selector` that `event` landed in, for a tap on HTML the host rendered,
|
||||
* which carries no handlers of its own.
|
||||
* @param {Event} event @param {string} selector @returns {HTMLElement | null}
|
||||
*/
|
||||
export function landedIn(event, selector) {
|
||||
const target = /** @type {Element | null} */ (event.target);
|
||||
return target?.closest?.(selector) ?? null;
|
||||
}
|
||||
27
crates/luxe-remote/app/icons.js
Normal file
27
crates/luxe-remote/app/icons.js
Normal file
@@ -0,0 +1,27 @@
|
||||
// @ts-check
|
||||
// The few drawn icons the app uses, as inline SVG in the text's color. Drawn rather than taken from
|
||||
// a font, so there's no glyph a phone can lack; each button carrying one says its words to a
|
||||
// screen reader.
|
||||
|
||||
import { html } from "./html.js";
|
||||
|
||||
/** @typedef {"send" | "stop" | "attach" | "close" | "dock" | "menu"} IconName */
|
||||
|
||||
const STROKE = { fill: "none", stroke: "currentColor", "stroke-width": "2.2", "stroke-linecap": "round", "stroke-linejoin": "round" };
|
||||
|
||||
/** @type {Record<IconName, () => unknown>} */
|
||||
const DRAWINGS = {
|
||||
send: () => html`<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5" ...${STROKE} />`,
|
||||
stop: () => html`<rect x="7" y="7" width="10" height="10" rx="1.5" fill="currentColor" />`,
|
||||
// a paperclip, tilted as one lies on a desk: attaching reads quicker than a picture of a photo
|
||||
attach: () => html`<path d="M17 8v8a5 5 0 0 1-10 0V6a3.25 3.25 0 0 1 6.5 0v9.5a1.5 1.5 0 0 1-3 0V8"
|
||||
transform="rotate(40 12 12)" ...${STROKE} />`,
|
||||
close: () => html`<path d="M6.5 6.5l11 11M17.5 6.5l-11 11" ...${STROKE} />`,
|
||||
dock: () => html`<rect x="3.5" y="4.5" width="17" height="15" rx="2" ...${STROKE} /><path d="M9.5 4.5v15" ...${STROKE} />`,
|
||||
menu: () => html`<path d="M4.5 7h15M4.5 12h15M4.5 17h15" ...${STROKE} />`,
|
||||
};
|
||||
|
||||
/** One icon, sized to the line it sits in. @param {{ name: IconName }} props */
|
||||
export function Icon({ name }) {
|
||||
return html`<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">${DRAWINGS[name]()}</svg>`;
|
||||
}
|
||||
37
crates/luxe-remote/app/index.html
Normal file
37
crates/luxe-remote/app/index.html
Normal file
@@ -0,0 +1,37 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>Luxe</title>
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
<link rel="apple-touch-icon" href="/icons/180.png">
|
||||
<meta name="apple-mobile-web-app-title" content="Luxe">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
||||
<link rel="stylesheet" href="/theme.css">
|
||||
<link rel="stylesheet" href="/app/style.css">
|
||||
<link rel="stylesheet" href="/app/markdown.css">
|
||||
<link rel="stylesheet" href="/app/controls.css">
|
||||
<link rel="stylesheet" href="/app/dock.css">
|
||||
<link rel="stylesheet" href="/app/panel.css">
|
||||
<link rel="stylesheet" href="/app/github.css">
|
||||
<link rel="stylesheet" href="/app/review.css">
|
||||
<link rel="stylesheet" href="/app/lines.css">
|
||||
<link rel="stylesheet" href="/app/peek.css">
|
||||
<script type="importmap">
|
||||
{
|
||||
"imports": {
|
||||
"preact": "/app/vendor/preact.mjs",
|
||||
"preact/hooks": "/app/vendor/hooks.mjs",
|
||||
"htm": "/app/vendor/htm.mjs",
|
||||
"@preact/signals-core": "/app/vendor/signals-core.mjs",
|
||||
"@preact/signals": "/app/vendor/signals.mjs"
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script type="module" src="/app/main.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
202
crates/luxe-remote/app/items.js
Normal file
202
crates/luxe-remote/app/items.js
Normal file
@@ -0,0 +1,202 @@
|
||||
// @ts-check
|
||||
// The transcript's items, drawn the way the TUI draws them: your messages on a band, replies as
|
||||
// text, reasoning muted, and a line for each tool call that opens to show what it returned.
|
||||
//
|
||||
// Text arrives as the host renders it (`render.js`). Until it does, an item shows its plain text,
|
||||
// so nothing waits on the round trip to be readable.
|
||||
|
||||
import { useLayoutEffect, useRef, useState } from "preact/hooks";
|
||||
import { html, landedIn } from "./html.js";
|
||||
import { useRendered } from "./render.js";
|
||||
|
||||
/** @import { Signal } from "@preact/signals" */
|
||||
/** @import { Card, Item as TranscriptItem, TextItem } from "./transcript.js" */
|
||||
|
||||
/** How long a copy control says it copied. */
|
||||
const COPIED_MS = 1500;
|
||||
|
||||
/**
|
||||
* How many items are drawn at first, and how many more each tap on "Show earlier" adds. WebKit
|
||||
* slows every keystroke as a page passes a few thousand items (a 9,000-item session took 100ms a
|
||||
* key), so a long session's history waits above until it's asked for.
|
||||
*/
|
||||
export const WINDOW = 300;
|
||||
|
||||
/**
|
||||
* The items to draw when the latest `shown` are wanted, and how many earlier ones wait above.
|
||||
* @template T @param {T[]} items @param {number} shown
|
||||
*/
|
||||
export function windowOf(items, shown) {
|
||||
const hidden = Math.max(0, items.length - shown);
|
||||
return { hidden, drawn: hidden ? items.slice(hidden) : items };
|
||||
}
|
||||
|
||||
/** @param {{ items: TranscriptItem[] }} props */
|
||||
export function Transcript({ items }) {
|
||||
const [shown, setShown] = useState(WINDOW);
|
||||
const list = useRef(/** @type {HTMLDivElement | null} */ (null));
|
||||
const keepPlace = useKeptPlace(list);
|
||||
const { hidden, drawn } = windowOf(items, shown);
|
||||
const more = () => keepPlace(() => setShown(shown + WINDOW));
|
||||
const count = html`<span class="dim">${hidden.toLocaleString()} more</span>`;
|
||||
return html`<div class="transcript" ref=${list} onClick=${copyCode}>
|
||||
${hidden ? html`<button type="button" class="earlier" onClick=${more}>Show earlier ${count}</button>` : null}
|
||||
${drawn.map((item) => html`<${Item} key=${item.key} item=${item} />`)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a change that adds items above, then scrolls the item that was first back to where it was.
|
||||
* @param {{ current: HTMLElement | null }} list @returns {(change: () => void) => void}
|
||||
*/
|
||||
function useKeptPlace(list) {
|
||||
const held = useRef(/** @type {{ item: Element, top: number } | null} */ (null));
|
||||
useLayoutEffect(() => {
|
||||
const kept = held.current;
|
||||
held.current = null;
|
||||
if (kept) holdInPlace(kept.item, kept.top);
|
||||
});
|
||||
return (change) => {
|
||||
const item = list.current?.querySelector(".item");
|
||||
if (item) held.current = { item, top: item.getBoundingClientRect().top };
|
||||
change();
|
||||
};
|
||||
}
|
||||
|
||||
/** How many frames an item is held in place while the items drawn above it settle. */
|
||||
const HOLD_FRAMES = 45;
|
||||
|
||||
/**
|
||||
* Keeps `item` at `top` while what was added above settles: items off screen are drawn at a guessed
|
||||
* height until they near it, and WebKit doesn't anchor the scroll as they do. A touch or a wheel
|
||||
* hands the scroll back.
|
||||
* @param {Element} item @param {number} top
|
||||
*/
|
||||
function holdInPlace(item, top) {
|
||||
let frames = HOLD_FRAMES;
|
||||
const release = () => (frames = 0);
|
||||
const kinds = ["touchstart", "wheel"];
|
||||
for (const kind of kinds) addEventListener(kind, release, { once: true, passive: true });
|
||||
const step = () => {
|
||||
if (frames-- <= 0) return kinds.forEach((kind) => removeEventListener(kind, release));
|
||||
scrollBy(0, item.getBoundingClientRect().top - top);
|
||||
requestAnimationFrame(step);
|
||||
};
|
||||
step();
|
||||
}
|
||||
|
||||
/** @param {{ item: TranscriptItem }} props */
|
||||
function Item({ item }) {
|
||||
switch (item.kind) {
|
||||
case "user": return html`<${UserMessage} item=${item} />`;
|
||||
case "assistant": return html`<${Reply} item=${item} />`;
|
||||
case "thinking": return html`<${Thinking} item=${item} />`;
|
||||
case "tool": return html`<${ToolCard} card=${item.card} />`;
|
||||
case "error": return html`<div class="item problem">${item.text}</div>`;
|
||||
default: return html`<div class="item notice">${item.text}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Host HTML when it has come, the plain text until then.
|
||||
* @param {{ className: string, rendered: string | undefined, text: string }} props
|
||||
*/
|
||||
function Rendered({ className, rendered, text }) {
|
||||
if (rendered === undefined) return html`<div class=${`${className} plain`}>${text}</div>`;
|
||||
return html`<div class=${className} dangerouslySetInnerHTML=${{ __html: rendered }} />`;
|
||||
}
|
||||
|
||||
/** @param {{ item: TextItem }} props */
|
||||
function UserMessage({ item }) {
|
||||
const rendered = useRendered({ kind: "user", content: item.content ?? [] }, false);
|
||||
return html`<${Rendered} className="item user-message" rendered=${rendered} text=${item.text.value} />`;
|
||||
}
|
||||
|
||||
/** @param {{ item: TextItem }} props */
|
||||
function Reply({ item }) {
|
||||
const rendered = useRendered({ kind: "answer", text: item.text.value }, !!item.provisional);
|
||||
return html`<${Rendered} className="item reply md" rendered=${rendered} text=${item.text.value} />`;
|
||||
}
|
||||
|
||||
/** @param {{ item: TextItem }} props */
|
||||
function Thinking({ item }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const rendered = useRendered({ kind: "reasoning", text: item.text.value }, !!item.provisional);
|
||||
const toggle = () => setOpen(!open);
|
||||
/** @param {KeyboardEvent} event */
|
||||
const onKey = (event) => (event.key === "Enter" || event.key === " ") && toggle();
|
||||
return html`<div class=${`item thinking ${open ? "open" : ""}`} role="button" tabindex="0"
|
||||
aria-expanded=${open} onClick=${toggle} onKeyDown=${onKey}>
|
||||
<${Rendered} className="md reasoning" rendered=${rendered} text=${item.text.value} />
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ card: Signal<Card> }} props */
|
||||
function ToolCard({ card }) {
|
||||
const call = card.value;
|
||||
const output = call.output_preview;
|
||||
const head = html`<${ToolGlyph} name=${call.name} />
|
||||
<span class="tool-name">${call.name}</span>
|
||||
<span class="tool-label">${call.label}</span>
|
||||
<span class="tool-time">${standing(call)}</span>
|
||||
${body(call)}`;
|
||||
if (!output) return html`<div class=${`item tool ${call.state}`}><div class="tool-head">${head}</div></div>`;
|
||||
return html`<details class=${`item tool ${call.state}`}>
|
||||
<summary class="tool-head">${head}</summary>
|
||||
<pre class="tool-output">${output}</pre>
|
||||
</details>`;
|
||||
}
|
||||
|
||||
/** The mark the TUI's card wears for this tool, which the host knows. @param {{ name: string }} props */
|
||||
function ToolGlyph({ name }) {
|
||||
const glyph = useRendered({ kind: "tool", name }, false);
|
||||
if (!glyph) return null;
|
||||
return html`<span class="tool-glyph" aria-hidden="true" dangerouslySetInnerHTML=${{ __html: glyph }} />`;
|
||||
}
|
||||
|
||||
/** @param {Card} call */
|
||||
function body(call) {
|
||||
const card = call.card_body;
|
||||
if (!card?.text) return null;
|
||||
const lines = card.text.split("\n");
|
||||
const shown = lines.slice(0, Math.max(1, card.collapsed_lines || 3));
|
||||
const more = lines.length - shown.length;
|
||||
return html`<pre class="tool-body">${shown.join("\n")}${more > 0 ? html`<span class="dim">\n… ${more} more lines</span>` : null}</pre>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A fence's copy control, for every rendered block at once; the page's policy allows no handler
|
||||
* in the host's HTML, so the transcript listens for it.
|
||||
* @param {Event} event
|
||||
*/
|
||||
function copyCode(event) {
|
||||
const button = landedIn(event, ".fence .copy");
|
||||
if (!button) return;
|
||||
event.stopPropagation();
|
||||
const code = button.closest(".fence")?.querySelector("code")?.textContent ?? "";
|
||||
navigator.clipboard.writeText(code).then(
|
||||
() => flash(button, "copied"),
|
||||
() => flash(button, "copy-failed"),
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {Element} element @param {string} className */
|
||||
function flash(element, className) {
|
||||
element.classList.add(className);
|
||||
setTimeout(() => element.classList.remove(className), COPIED_MS);
|
||||
}
|
||||
|
||||
/** How the call stands, in words: its time once done, otherwise its state. @param {Card} call */
|
||||
export function standing(call) {
|
||||
if (call.state === "failed") return call.summary || "failed";
|
||||
if (call.state !== "succeeded") return call.state;
|
||||
return call.elapsed_ms == null ? "" : elapsed(call.elapsed_ms);
|
||||
}
|
||||
|
||||
/** A duration the way the TUI writes it. @param {number} ms */
|
||||
export function elapsed(ms) {
|
||||
if (ms < 1) return "<1ms";
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
|
||||
return `${Math.floor(ms / 60000)}m ${Math.round((ms % 60000) / 1000)}s`;
|
||||
}
|
||||
116
crates/luxe-remote/app/layout.js
Normal file
116
crates/luxe-remote/app/layout.js
Normal file
@@ -0,0 +1,116 @@
|
||||
// @ts-check
|
||||
// Whether the dock shows, and on which side: started from your config, which the bridge writes on
|
||||
// the page, as the TUI starts from it. `/dock` and the header's button change them while the app
|
||||
// is open, as `/dock` does in the TUI. On a wide screen the dock is a rail beside the conversation;
|
||||
// on a phone it's the project panel's first tab, behind the header's one button.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
|
||||
/**
|
||||
* @typedef {"auto" | "shown" | "hidden"} DockMode
|
||||
* @typedef {"dock" | "files" | "github" | "review"} Tab
|
||||
*/
|
||||
|
||||
/** The dock, plan and changes both as on the rail, as a tab of the project panel on a phone. */
|
||||
const DOCK_TABS = /** @type {{ id: Tab, title: string }[]} */ ([{ id: "dock", title: "Dock" }]);
|
||||
|
||||
/** The project's views, the panel's tabs on every screen. */
|
||||
const PROJECT_TABS = /** @type {{ id: Tab, title: string }[]} */ ([
|
||||
{ id: "files", title: "Files" }, { id: "github", title: "GitHub" }, { id: "review", title: "Review" },
|
||||
]);
|
||||
|
||||
/**
|
||||
* The project panel's tabs. A phone has one header button for everything, so the dock comes first
|
||||
* there; a wide screen keeps the dock as its own rail.
|
||||
* @param {boolean} wide
|
||||
*/
|
||||
export function panelTabs(wide) {
|
||||
return wide ? PROJECT_TABS : [...DOCK_TABS, ...PROJECT_TABS];
|
||||
}
|
||||
|
||||
/**
|
||||
* The tab the panel shows: `tab` when this screen has it, else the screen's first. `tab` can be
|
||||
* one the screen lacks after an iPad turns or a Duo opens with the panel on the dock.
|
||||
* @param {Tab | null} tab @param {boolean} wide @returns {Tab}
|
||||
*/
|
||||
export function shownTab(tab, wide) {
|
||||
const tabs = panelTabs(wide);
|
||||
return tabs.find(({ id }) => id === tab)?.id ?? tabs[0].id;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a `/dock` verb does on a phone, where the dock is the panel's Dock tab: open the panel on
|
||||
* it, close it, or null for the verbs that set the dock's own mode or side.
|
||||
* @param {string} verb @param {Tab | null} tab The panel's tab, null when it's closed
|
||||
* @returns {"open" | "close" | null}
|
||||
*/
|
||||
export function phoneDock(verb, tab) {
|
||||
if (verb === "hide" || (verb === "toggle" && tab === "dock")) return "close";
|
||||
return verb === "show" || verb === "toggle" ? "open" : null;
|
||||
}
|
||||
|
||||
/** Wide and tall enough for the dock beside the conversation; dock.css's breakpoint. */
|
||||
export const WIDE = "(min-width: 50rem) and (min-height: 30rem)";
|
||||
|
||||
/** The verbs `/dock` takes, as the TUI's does; a bare `/dock` toggles. */
|
||||
export const DOCK_VERBS = ["show", "hide", "auto", "left", "right"];
|
||||
|
||||
/** The mode the page was served with, auto when it says nothing known. @param {DOMStringMap} written @returns {DockMode} */
|
||||
export function startingMode(written) {
|
||||
return written.dockMode === "shown" || written.dockMode === "hidden" ? written.dockMode : "auto";
|
||||
}
|
||||
|
||||
/** Whether the dock shows: always when shown, and on a wide screen when auto. @param {DockMode} mode @param {boolean} wide */
|
||||
export function dockVisible(mode, wide) {
|
||||
return mode === "shown" || (mode === "auto" && wide);
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode after `verb`: "toggle" flips what's on screen, the rest are `/dock`'s. Null for a verb
|
||||
* that doesn't change the mode.
|
||||
* @param {DockMode} mode @param {string} verb @param {boolean} wide @returns {DockMode | null}
|
||||
*/
|
||||
export function dockAfter(mode, verb, wide) {
|
||||
if (verb === "toggle") return dockVisible(mode, wide) ? "hidden" : "shown";
|
||||
if (verb === "show") return "shown";
|
||||
if (verb === "hide") return "hidden";
|
||||
return verb === "auto" ? "auto" : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The dock's mode for the app, and `apply` for a verb. The side lives on the page's own
|
||||
* `data-dock-side`, which the stylesheet reads.
|
||||
* @param {HTMLElement} page @param {() => boolean} wide
|
||||
*/
|
||||
export function createDock(page, wide) {
|
||||
const mode = signal(startingMode(page.dataset));
|
||||
/** @param {string} verb */
|
||||
const apply = (verb) => {
|
||||
if (verb === "left" || verb === "right") return void (page.dataset.dockSide = verb);
|
||||
const next = dockAfter(mode.value, verb, wide());
|
||||
if (next) mode.value = next;
|
||||
};
|
||||
return { mode, apply };
|
||||
}
|
||||
|
||||
/** @type {ReturnType<typeof createDock> | undefined} */
|
||||
let appDock;
|
||||
|
||||
/** The one dock the app's sessions share, made on first use. */
|
||||
export function theDock() {
|
||||
appDock ??= createDock(document.documentElement, () => matchMedia(WIDE).matches);
|
||||
return appDock;
|
||||
}
|
||||
|
||||
/** Whether the screen is wide, following a rotation or a resized window. */
|
||||
export function useWide() {
|
||||
const [wide, setWide] = useState(() => matchMedia(WIDE).matches);
|
||||
useEffect(() => {
|
||||
const query = matchMedia(WIDE);
|
||||
const change = () => setWide(query.matches);
|
||||
query.addEventListener("change", change);
|
||||
return () => query.removeEventListener("change", change);
|
||||
}, []);
|
||||
return wide;
|
||||
}
|
||||
89
crates/luxe-remote/app/lines-view.js
Normal file
89
crates/luxe-remote/app/lines-view.js
Normal file
@@ -0,0 +1,89 @@
|
||||
// @ts-check
|
||||
// A file or a diff whose lines can be picked, with the bar that asks about them. The page is the
|
||||
// host's HTML, so taps are read by delegation and picked rows are marked on the DOM once it's there.
|
||||
|
||||
import { useLayoutEffect, useRef, useState } from "preact/hooks";
|
||||
import { html } from "./html.js";
|
||||
import { askLabel, lineWords, markPicked, selectedLines, tapped } from "./lines.js";
|
||||
import { useRendered } from "./render.js";
|
||||
|
||||
/** @import { LinePick } from "./lines.js" */
|
||||
/** @import { Piece } from "./render.js" */
|
||||
|
||||
/**
|
||||
* How long a selection's lines outlive the selection. Tapping Ask can collapse it in Safari before
|
||||
* the tap lands, and the lines must still be there to send.
|
||||
*/
|
||||
const SELECTION_GRACE_MS = 400;
|
||||
|
||||
/**
|
||||
* What a pickable pane does with lines: ask about them, and, in a review chapter, comment on them
|
||||
* or, with none picked, on the chapter.
|
||||
* @typedef {{ ask: (words: string) => void, comment?: (pick: LinePick | null) => void }} LineActs
|
||||
*/
|
||||
|
||||
/** A piece the host draws, its lines pickable. @param {{ piece: Piece } & LineActs} props */
|
||||
export function PickablePiece({ piece, ask, comment }) {
|
||||
const rendered = useRendered(piece, false);
|
||||
return html`<${Pickable} markup=${rendered ?? ""} ask=${ask} comment=${comment} />`;
|
||||
}
|
||||
|
||||
/** @param {{ markup: string } & LineActs} props */
|
||||
export function Pickable({ markup, ask, comment }) {
|
||||
const root = useRef(/** @type {HTMLDivElement | null} */ (null));
|
||||
const [pick, setPick] = useState(/** @type {LinePick | null} */ (null));
|
||||
const selected = useSelectedLines(root);
|
||||
useLayoutEffect(() => void (root.current && markPicked(root.current, pick)), [pick, markup]);
|
||||
const target = selected.lines ?? pick;
|
||||
/** Lets the pick and the selection go, then hands the lines on. @param {(lines: LinePick | null) => void} then */
|
||||
const done = (then) => () => {
|
||||
document.getSelection()?.removeAllRanges();
|
||||
selected.drop();
|
||||
setPick(null);
|
||||
then(target);
|
||||
};
|
||||
return html`<div ref=${root} onClick=${(/** @type {MouseEvent} */ event) => setPick((it) => tapped(it, /** @type {Element} */ (event.target)))}
|
||||
dangerouslySetInnerHTML=${{ __html: markup }}></div>
|
||||
<${LineBar} target=${target} ask=${done((lines) => lines && ask(lineWords(lines)))} comment=${comment && done(comment)} />`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bar at the foot of the pane: Ask for picked lines, and Comment where comments go, which with
|
||||
* nothing picked is the chapter's. Nothing to offer, no bar.
|
||||
* @param {{ target: LinePick | null, ask: () => void, comment?: () => void }} props
|
||||
*/
|
||||
function LineBar({ target, ask, comment }) {
|
||||
if (!target && !comment) return null;
|
||||
const button = (/** @type {string} */ words, /** @type {() => void} */ act) =>
|
||||
html`<button type="button" class="mention" onClick=${act}>${words}</button>`;
|
||||
return html`<div class="line-ask">
|
||||
${comment ? button(target ? "Comment" : "Comment on the chapter", comment) : null}
|
||||
${target ? button(askLabel(target), ask) : null}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The lines the phone's own selection covers under `root`, kept a moment after it collapses.
|
||||
* @param {{ current: Element | null }} root
|
||||
*/
|
||||
function useSelectedLines(root) {
|
||||
const [lines, setLines] = useState(/** @type {LinePick | null} */ (null));
|
||||
const timer = useRef(/** @type {ReturnType<typeof setTimeout> | undefined} */ (undefined));
|
||||
// armed as the pane reaches the page and read once then: a file drawn from the cache is there at
|
||||
// once, and a selection made before a later listener attached would be missed
|
||||
useLayoutEffect(() => {
|
||||
const read = () => {
|
||||
const now = root.current && selectedLines(document.getSelection(), root.current);
|
||||
clearTimeout(timer.current);
|
||||
if (now) return setLines((was) => (samePick(was, now) ? was : now));
|
||||
timer.current = setTimeout(() => setLines(null), SELECTION_GRACE_MS);
|
||||
};
|
||||
read();
|
||||
document.addEventListener("selectionchange", read);
|
||||
return () => (clearTimeout(timer.current), document.removeEventListener("selectionchange", read));
|
||||
}, []);
|
||||
return { lines, drop: () => (clearTimeout(timer.current), setLines(null)) };
|
||||
}
|
||||
|
||||
/** @param {LinePick | null} a @param {LinePick} b */
|
||||
const samePick = (a, b) => Boolean(a && a.path === b.path && a.first === b.first && a.last === b.last);
|
||||
28
crates/luxe-remote/app/lines.css
Normal file
28
crates/luxe-remote/app/lines.css
Normal file
@@ -0,0 +1,28 @@
|
||||
/* Line picks: a line's number is what a tap picks, and is left out of the phone's own selection
|
||||
so copying code copies only the code. Picked rows wear the selection's surface over their diff
|
||||
tint, as the TUI tints its picked rows, and the Ask bar keeps to the foot of the pane */
|
||||
|
||||
[data-line] > .ln {
|
||||
cursor: pointer;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.dl.picked,
|
||||
.fl.picked {
|
||||
background: var(--luxe-selected-bg, #2c2925);
|
||||
}
|
||||
|
||||
.picked > .ln {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.line-ask {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding: 0.5lh 1.5ch calc(0.5lh + env(safe-area-inset-bottom));
|
||||
background: var(--luxe-background, #12100e);
|
||||
border-top: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
75
crates/luxe-remote/app/lines.js
Normal file
75
crates/luxe-remote/app/lines.js
Normal file
@@ -0,0 +1,75 @@
|
||||
// @ts-check
|
||||
// Line picks in a file, a diff or a review chapter, to ask about those lines as the TUI's File view
|
||||
// does. A tap on a line's number picks it and a tap on another stretches the pick; a tap on the same
|
||||
// line, or anywhere else, lets it go. A selection made the phone's own way, down to part of a line,
|
||||
// offers the same Ask for the lines it covers, and copying it stays the browser's. Ask writes what
|
||||
// the TUI sends for `@[file:path:12-18]`: the path, then the lines.
|
||||
|
||||
/** @typedef {{ path: string, first: number, last: number }} LinePick */
|
||||
|
||||
/**
|
||||
* The pick after a tap on line `line` of `path`: a first tap picks it, a second stretches to it,
|
||||
* and a tap on a lone picked line, or after a stretch, starts over.
|
||||
* @param {LinePick | null} pick @param {string} path @param {number} line @returns {LinePick | null}
|
||||
*/
|
||||
export function tapLine(pick, path, line) {
|
||||
if (!pick || pick.path !== path || pick.first !== pick.last) return { path, first: line, last: line };
|
||||
if (pick.first === line) return null;
|
||||
return { path, first: Math.min(pick.first, line), last: Math.max(pick.first, line) };
|
||||
}
|
||||
|
||||
/** What Ask writes into the message, as the TUI expands its line mention. @param {LinePick} pick */
|
||||
export function lineWords({ path, first, last }) {
|
||||
return `\`${path}\` ${first === last ? `line ${first}` : `lines ${first}–${last}`}`;
|
||||
}
|
||||
|
||||
/** The Ask button's words, as the TUI's action row says them. @param {LinePick} pick */
|
||||
export function askLabel({ first, last }) {
|
||||
return first === last ? `Ask about line ${first}` : `Ask about lines ${first}–${last}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pick a tap makes: the line whose number was tapped, or nothing for a tap anywhere else.
|
||||
* @param {LinePick | null} pick @param {Element | null} target @returns {LinePick | null}
|
||||
*/
|
||||
export function tapped(pick, target) {
|
||||
const row = target?.closest(".ln")?.closest("[data-line]");
|
||||
const path = row?.closest("[data-path]")?.getAttribute("data-path");
|
||||
if (!row || !path) return null;
|
||||
return tapLine(pick, path, Number(row.getAttribute("data-line")));
|
||||
}
|
||||
|
||||
/**
|
||||
* The lines a selection covers when it sits within one file's block: every row it touches, so one
|
||||
* that starts partway through a line counts that line, and deleted lines, which name none, are
|
||||
* passed over. A selection across two files, or outside `root`, offers nothing.
|
||||
* @param {Selection | null} selection @param {Element} root @returns {LinePick | null}
|
||||
*/
|
||||
export function selectedLines(selection, root) {
|
||||
if (!selection || selection.isCollapsed || !selection.rangeCount) return null;
|
||||
const range = selection.getRangeAt(0);
|
||||
const block = blockOf(range.commonAncestorContainer);
|
||||
const path = block?.getAttribute("data-path");
|
||||
if (!block || !path || !root.contains(block)) return null;
|
||||
const rows = [...block.querySelectorAll("[data-line]")].filter((row) => range.intersectsNode(row));
|
||||
const lines = rows.map((row) => Number(row.getAttribute("data-line")));
|
||||
return lines.length ? { path, first: Math.min(...lines), last: Math.max(...lines) } : null;
|
||||
}
|
||||
|
||||
/** The file block a node sits in. @param {Node} node */
|
||||
function blockOf(node) {
|
||||
const element = node.nodeType === 1 ? /** @type {Element} */ (node) : node.parentElement;
|
||||
return element?.closest("[data-path]") ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the picked rows under `root`, and only those, since the page is the host's HTML.
|
||||
* @param {Element} root @param {LinePick | null} pick
|
||||
*/
|
||||
export function markPicked(root, pick) {
|
||||
for (const row of root.querySelectorAll("[data-line]")) {
|
||||
const line = Number(row.getAttribute("data-line"));
|
||||
const path = row.closest("[data-path]")?.getAttribute("data-path");
|
||||
row.classList.toggle("picked", Boolean(pick && path === pick.path && line >= pick.first && line <= pick.last));
|
||||
}
|
||||
}
|
||||
11
crates/luxe-remote/app/main.js
Normal file
11
crates/luxe-remote/app/main.js
Normal file
@@ -0,0 +1,11 @@
|
||||
// @ts-check
|
||||
import { render } from "preact";
|
||||
import { html } from "./html.js";
|
||||
import { App } from "./app.js";
|
||||
import { startWorker } from "./notifications.js";
|
||||
import { holdFieldZoom } from "./viewport.js";
|
||||
|
||||
holdFieldZoom();
|
||||
startWorker();
|
||||
const root = document.getElementById("app");
|
||||
if (root) render(html`<${App} />`, root);
|
||||
233
crates/luxe-remote/app/markdown.css
Normal file
233
crates/luxe-remote/app/markdown.css
Normal file
@@ -0,0 +1,233 @@
|
||||
/* Rendered text: the host's HTML (`luxe_tui::markdown::html`) set the way the terminal sets it.
|
||||
One blank row between blocks, headings in weight and color rather than size, `•` and numbers
|
||||
hanging in the margin, a `>` before each block of a quote, rules of box characters. */
|
||||
|
||||
.md {
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.md :is(p, ul, ol, blockquote, figure, .table, h1, h2, h3, h4, h5, h6, hr) {
|
||||
margin: 0 0 1lh;
|
||||
}
|
||||
|
||||
.md > :last-child,
|
||||
.md li > :last-child,
|
||||
.md blockquote > :last-child {
|
||||
margin-block-end: 0;
|
||||
}
|
||||
|
||||
.md :is(h1, h2, h3, h4, h5, h6) {
|
||||
font-size: inherit;
|
||||
font-weight: bold;
|
||||
color: var(--luxe-md-heading, #ddc084);
|
||||
}
|
||||
|
||||
.md code {
|
||||
color: var(--luxe-md-code, #faaa51);
|
||||
}
|
||||
|
||||
.md :is(h1, h2, h3, h4, h5, h6) code {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.md :is(a, .link) {
|
||||
color: var(--luxe-md-link, #85c7d7);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.md .url {
|
||||
color: var(--luxe-md-link-url, #97938c);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.md :is(ul, ol) {
|
||||
list-style: none;
|
||||
padding-inline-start: 2ch;
|
||||
}
|
||||
|
||||
.md ol {
|
||||
padding-inline-start: 3ch;
|
||||
}
|
||||
|
||||
.md li {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.md li :is(ul, ol) {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.md ul > li::before,
|
||||
.md ol > li::before {
|
||||
position: absolute;
|
||||
right: 100%;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.md ul > li::before {
|
||||
content: "• ";
|
||||
}
|
||||
|
||||
.md ol > li::before {
|
||||
content: counter(list-item) ". ";
|
||||
}
|
||||
|
||||
.md blockquote {
|
||||
padding-inline-start: 2ch;
|
||||
}
|
||||
|
||||
.md blockquote > * {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.md blockquote > :not(.alert-label)::before {
|
||||
content: ">";
|
||||
position: absolute;
|
||||
left: -2ch;
|
||||
color: var(--luxe-md-quote, #97938c);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.md .alert-label {
|
||||
margin: 0;
|
||||
margin-inline-start: -2ch;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.md .alert-label::before {
|
||||
content: "> ";
|
||||
color: var(--luxe-md-quote, #97938c);
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.md .note .alert-label { color: var(--luxe-info, #85c7d7); }
|
||||
.md .tip .alert-label { color: var(--luxe-success, #81caa0); }
|
||||
.md .important .alert-label { color: var(--luxe-accent, #ddc084); }
|
||||
.md .warning .alert-label { color: var(--luxe-warning, #faaa51); }
|
||||
.md .caution .alert-label { color: var(--luxe-error, #e68485); }
|
||||
|
||||
/* Rules are box characters cut to the width, as the terminal fills a row */
|
||||
.md hr,
|
||||
.md .fence::after,
|
||||
.md .fence .fill::before {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.md hr {
|
||||
border: 0;
|
||||
height: 1lh;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.md hr::before {
|
||||
content: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━";
|
||||
}
|
||||
|
||||
.md .fence {
|
||||
margin-inline: 0;
|
||||
color: var(--luxe-border, #201e1a);
|
||||
}
|
||||
|
||||
.md .fence figcaption {
|
||||
display: flex;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.md .fence .fill {
|
||||
flex: 1;
|
||||
min-width: 1ch;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.md .fence .fill::before,
|
||||
.md .fence::after {
|
||||
content: "────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────";
|
||||
}
|
||||
|
||||
.md .fence::after {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.md .fence .lang::before {
|
||||
content: "─ ";
|
||||
color: var(--luxe-border, #201e1a);
|
||||
}
|
||||
|
||||
.md .fence :is(.lang, .copy) {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
padding-inline-end: 1ch;
|
||||
}
|
||||
|
||||
.md .fence .copy {
|
||||
padding-inline: 1ch 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.md .fence .copy::after {
|
||||
content: " ─";
|
||||
color: var(--luxe-border, #201e1a);
|
||||
}
|
||||
|
||||
.md .fence .copy.copied {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
.md .fence .copy.copy-failed {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
.md .fence pre {
|
||||
overflow-x: auto;
|
||||
white-space: pre;
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
}
|
||||
|
||||
.md .fence code {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.md .table {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.md table {
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.md :is(th, td) {
|
||||
padding: 0 1ch;
|
||||
border: 1px solid var(--luxe-border, #201e1a);
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.md :is(th, td).right { text-align: end; }
|
||||
.md :is(th, td).center { text-align: center; }
|
||||
|
||||
/* Reasoning spends weight, not color, and keeps code's hue only inline */
|
||||
.md.reasoning :is(h1, h2, h3, h4, h5, h6, a, .link, .url, .alert-label) {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.md.reasoning .fence pre {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
/* Highlighted code: each role is its theme token, as `luxe_tui::highlight::Role::token` says */
|
||||
.t-text { color: var(--luxe-text, #e4dfd6); }
|
||||
.t-muted { color: var(--luxe-muted, #97938c); }
|
||||
.t-accent { color: var(--luxe-accent, #ddc084); }
|
||||
.t-accent-secondary { color: var(--luxe-accent-secondary, #d2a5cd); }
|
||||
.t-info { color: var(--luxe-info, #85c7d7); }
|
||||
.t-success { color: var(--luxe-success, #81caa0); }
|
||||
.t-warning { color: var(--luxe-warning, #faaa51); }
|
||||
.t-error { color: var(--luxe-error, #e68485); }
|
||||
.t-thinking-ultra { color: var(--luxe-thinking-ultra, #e790b7); }
|
||||
.t-md-heading { color: var(--luxe-md-heading, #ddc084); }
|
||||
.t-md-link { color: var(--luxe-md-link, #85c7d7); }
|
||||
.t-md-link-url { color: var(--luxe-md-link-url, #97938c); }
|
||||
.t-md-quote { color: var(--luxe-md-quote, #97938c); }
|
||||
.t-md-code { color: var(--luxe-md-code, #faaa51); }
|
||||
.b { font-weight: bold; }
|
||||
.i { font-style: italic; }
|
||||
113
crates/luxe-remote/app/mentions.js
Normal file
113
crates/luxe-remote/app/mentions.js
Normal file
@@ -0,0 +1,113 @@
|
||||
// @ts-check
|
||||
// `@` mentions of project files, picked from the project's own folders as `list_directory` gives
|
||||
// them. A picked file goes into the box as its path in backticks, which is what the TUI sends the
|
||||
// model for one, so what you see is what the model reads; a picked folder opens the next level.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/**
|
||||
* @typedef {{ name: string, kind: "directory" | "file" }} Entry
|
||||
* @typedef {{ state: "asking" | "listed" | "failed", entries: Entry[] }} Listing
|
||||
* @typedef {{ start: number, folder: string, name: string }} MentionQuery
|
||||
*/
|
||||
|
||||
/**
|
||||
* The mention being typed just before `caret`: an `@` at the start or after a space, then no
|
||||
* space. `folder` is what's typed up to its last slash, `name` the rest.
|
||||
* @param {string} text @param {number} caret @returns {MentionQuery | null}
|
||||
*/
|
||||
export function mentionAt(text, caret) {
|
||||
const typed = /(?:^|\s)@([^\s@`]*)$/.exec(text.slice(0, caret));
|
||||
if (!typed) return null;
|
||||
const query = typed[1];
|
||||
const cut = query.lastIndexOf("/");
|
||||
return { start: caret - query.length - 1, folder: query.slice(0, Math.max(cut, 0)), name: query.slice(cut + 1) };
|
||||
}
|
||||
|
||||
/** Entries whose name starts with `name`, then those holding it, in the listing's order. @param {Entry[]} entries @param {string} name */
|
||||
export function matchEntries(entries, name) {
|
||||
const needle = name.toLowerCase();
|
||||
const starting = entries.filter((entry) => entry.name.toLowerCase().startsWith(needle));
|
||||
const holding = entries.filter((entry) => !starting.includes(entry) && entry.name.toLowerCase().includes(needle));
|
||||
return [...starting, ...holding];
|
||||
}
|
||||
|
||||
/**
|
||||
* `text` with the mention at `query` replaced by `entry`, and where the caret goes after it.
|
||||
* @param {string} text @param {number} caret @param {MentionQuery} query @param {Entry} entry
|
||||
*/
|
||||
export function pickEntry(text, caret, query, entry) {
|
||||
const path = query.folder ? `${query.folder}/${entry.name}` : entry.name;
|
||||
const inserted = entry.kind === "directory" ? `@${path}/` : `\`${path}\` `;
|
||||
return { text: text.slice(0, query.start) + inserted + text.slice(caret), caret: query.start + inserted.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Each folder's entries, kept while the session is open: the picker asks once, and the Files tab
|
||||
* asks `fresh` each time it opens one, since the agent may have changed it since.
|
||||
*/
|
||||
export function createListings() {
|
||||
const folders = signal(/** @type {Record<string, Listing>} */ ({}));
|
||||
/** @type {Map<string, string>} */
|
||||
const asked = new Map();
|
||||
/** @param {string} folder @param {Listing} listing */
|
||||
const store = (folder, listing) => (folders.value = { ...folders.value, [folder]: listing });
|
||||
/**
|
||||
* Asks for `folder` unless it's on its way, or known and not wanted `fresh`.
|
||||
* @param {string} folder @param {(frame: Frame) => boolean} send @param {{ fresh?: boolean }} [options]
|
||||
*/
|
||||
const ask = (folder, send, { fresh = false } = {}) => askListing({ folders, asked, store }, folder, send, fresh);
|
||||
/** @param {Frame} frame */
|
||||
const apply = (frame) => {
|
||||
if (frame.kind === "ready") folders.value = withoutAsking(folders.value);
|
||||
else applyListing(frame, asked, store);
|
||||
};
|
||||
return { folders, ask, apply };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ folders: { value: Record<string, Listing> }, asked: Map<string, string>,
|
||||
* store: (folder: string, listing: Listing) => void }} listings
|
||||
* @param {string} folder @param {(frame: Frame) => boolean} send @param {boolean} fresh
|
||||
*/
|
||||
function askListing({ folders, asked, store }, folder, send, fresh) {
|
||||
const known = folders.value[folder];
|
||||
if (known && (!fresh || known.state === "asking")) return;
|
||||
const request_id = askFor(folder, send);
|
||||
if (!request_id) return;
|
||||
asked.set(request_id, folder);
|
||||
// what was listed before stays up until the answer replaces it
|
||||
store(folder, { state: "asking", entries: known?.entries ?? [] });
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the question for `folder`, returning its id, or null when it went nowhere.
|
||||
* @param {string} folder @param {(frame: Frame) => boolean} send
|
||||
*/
|
||||
function askFor(folder, send) {
|
||||
// every client hears every answer, so the id has to be ours alone
|
||||
const request_id = `listing:${crypto.randomUUID()}`;
|
||||
return send({ kind: "list_directory", content: { request_id, path: folder } }) ? request_id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `folders` less those still on their way, whose answers a new connection never brings, so the
|
||||
* next look asks again.
|
||||
* @param {Record<string, Listing>} folders
|
||||
*/
|
||||
export function withoutAsking(folders) {
|
||||
return Object.fromEntries(Object.entries(folders).filter(([, listing]) => listing.state !== "asking"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Files the answer to one of `asked`'s questions under its folder.
|
||||
* @param {Frame} frame @param {Map<string, string>} asked
|
||||
* @param {(folder: string, listing: Listing) => void} store
|
||||
*/
|
||||
function applyListing({ kind, content }, asked, store) {
|
||||
const folder = asked.get(content?.request_id);
|
||||
if (folder === undefined) return;
|
||||
if (kind === "directory_listed") store(folder, { state: "listed", entries: content.listing.entries });
|
||||
if (kind === "directory_list_failed") store(folder, { state: "failed", entries: [] });
|
||||
}
|
||||
57
crates/luxe-remote/app/models.js
Normal file
57
crates/luxe-remote/app/models.js
Normal file
@@ -0,0 +1,57 @@
|
||||
// @ts-check
|
||||
// The models a session can switch to, asked for each time the details sheet opens and answered to
|
||||
// this device alone. An older Luxe doesn't know the question and refuses it, so the sheet says so
|
||||
// rather than waiting for an answer that won't come.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/**
|
||||
* One model `list_models` offers, as `models_listed` carries it.
|
||||
* @typedef {{ provider: string, model: string, name: string, thinking_levels: string[] }} ModelChoice
|
||||
* @typedef {"idle" | "asking" | "listed" | "unsupported" | "lost"} ListingState
|
||||
* @typedef {{ state: ListingState, models: ModelChoice[] }} Listing
|
||||
* @typedef {{ provider?: string, model?: string }} CurrentModel
|
||||
*/
|
||||
|
||||
export function createModels() {
|
||||
const listing = signal(/** @type {Listing} */ ({ state: "idle", models: [] }));
|
||||
let asked = "";
|
||||
let count = 0;
|
||||
/** Asks again, keeping the last answer on screen meanwhile. @param {(frame: Frame) => boolean} send */
|
||||
const ask = (send) => {
|
||||
asked = `models-${++count}`;
|
||||
const sent = send({ kind: "list_models", content: { request_id: asked } });
|
||||
listing.value = { ...listing.value, state: sent ? "asking" : "lost" };
|
||||
};
|
||||
/** Takes the answer to the latest question, or a refusal of the question itself. @param {Frame} frame */
|
||||
const apply = ({ kind, content }) => {
|
||||
if (kind === "models_listed" && content.request_id === asked) listing.value = { state: "listed", models: content.models };
|
||||
if (kind === "action_rejected" && content.kind === "list_models") listing.value = { state: "unsupported", models: [] };
|
||||
};
|
||||
return { listing, ask, apply };
|
||||
}
|
||||
|
||||
/** Whether `choice` is the model running now. @param {ModelChoice} choice @param {CurrentModel | undefined} current */
|
||||
export function isCurrent(choice, current) {
|
||||
return choice.provider === current?.provider && choice.model === current?.model;
|
||||
}
|
||||
|
||||
/**
|
||||
* The thinking levels the running model honors; none until it's found in the listing, since a
|
||||
* level it doesn't honor would be clamped without a word.
|
||||
* @param {ModelChoice[]} models @param {CurrentModel | undefined} current
|
||||
*/
|
||||
export function thinkingLevels(models, current) {
|
||||
return models.find((choice) => isCurrent(choice, current))?.thinking_levels ?? [];
|
||||
}
|
||||
|
||||
/** @param {ModelChoice} choice @returns {Frame} */
|
||||
export function selectModelFrame(choice) {
|
||||
return { kind: "select_model", content: { provider: choice.provider, model: choice.model } };
|
||||
}
|
||||
|
||||
/** @param {string} level @returns {Frame} */
|
||||
export function thinkingFrame(level) {
|
||||
return { kind: "set_thinking_level", content: level };
|
||||
}
|
||||
131
crates/luxe-remote/app/notifications.js
Normal file
131
crates/luxe-remote/app/notifications.js
Normal file
@@ -0,0 +1,131 @@
|
||||
// @ts-check
|
||||
// Notifications on this device: the switch, and what it takes to turn them on.
|
||||
//
|
||||
// iOS gives Web Push only to an app on the Home Screen, and asks permission only in answer to a
|
||||
// tap, so the switch subscribes inside its tap handler, and a Safari tab shows the way to the
|
||||
// Home Screen instead. Notifications say what's waiting and where, never what: the app is where
|
||||
// you read and answer.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { html } from "./html.js";
|
||||
|
||||
/**
|
||||
* What the switch can do here.
|
||||
* @typedef {"unsupported" | "home-screen" | "ready"} Support
|
||||
* @typedef {"unsupported" | "home-screen" | "off" | "on" | "blocked" | "busy"} PushState
|
||||
* @typedef {{ worker: boolean, push: boolean, standalone: boolean }} Browser
|
||||
*/
|
||||
|
||||
/** @type {import("@preact/signals").Signal<PushState>} */
|
||||
const state = signal("unsupported");
|
||||
const key = signal("");
|
||||
const problem = signal("");
|
||||
|
||||
/**
|
||||
* Whether this browser can take notifications. Of the browsers people use, only iOS's lack push
|
||||
* in a tab, and they have it once the app is on the Home Screen. @param {Browser} browser
|
||||
* @returns {Support}
|
||||
*/
|
||||
export function support(browser) {
|
||||
if (browser.worker && browser.push) return "ready";
|
||||
return browser.standalone ? "unsupported" : "home-screen";
|
||||
}
|
||||
|
||||
/** @returns {Browser} */
|
||||
function thisBrowser() {
|
||||
const standalone = matchMedia("(display-mode: standalone)").matches;
|
||||
return { worker: "serviceWorker" in navigator, push: "PushManager" in window, standalone };
|
||||
}
|
||||
|
||||
/** The bridge's key as `PushManager.subscribe` takes it. @param {string} base64url */
|
||||
export function keyBytes(base64url) {
|
||||
const base64 = base64url.replaceAll("-", "+").replaceAll("_", "/");
|
||||
return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
|
||||
}
|
||||
|
||||
/** Starts the service worker, which shows what arrives and opens the session one names. */
|
||||
export function startWorker() {
|
||||
if (support(thisBrowser()) !== "ready") return;
|
||||
navigator.serviceWorker.register("/service-worker.js").catch((error) => {
|
||||
console.warn("the service worker didn't start", error);
|
||||
});
|
||||
navigator.serviceWorker.addEventListener("message", (event) => {
|
||||
if (event.data?.kind !== "open_session") return;
|
||||
location.hash = `#/session/${encodeURIComponent(event.data.session)}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** Reads where the switch stands: what the browser allows, and what the bridge has. */
|
||||
export async function refreshNotifications() {
|
||||
const allowed = support(thisBrowser());
|
||||
if (allowed !== "ready") return void (state.value = allowed);
|
||||
if (Notification.permission === "denied") return void (state.value = "blocked");
|
||||
const response = await fetch("/api/push");
|
||||
if (!response.ok) return;
|
||||
const status = await response.json();
|
||||
key.value = status.key;
|
||||
const here = await (await navigator.serviceWorker.ready).pushManager.getSubscription();
|
||||
// the bridge's record alone isn't enough: a reinstalled app has lost its subscription
|
||||
if (state.value !== "busy") state.value = status.subscribed && here ? "on" : "off";
|
||||
}
|
||||
|
||||
/** Asks for permission and subscribes; the switch's tap handler. */
|
||||
async function turnOn() {
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== "granted") return void (state.value = permission === "denied" ? "blocked" : "off");
|
||||
const manager = (await navigator.serviceWorker.ready).pushManager;
|
||||
// one made with a key the bridge no longer has can't be reused, so start fresh
|
||||
await (await manager.getSubscription())?.unsubscribe();
|
||||
const subscription = await manager.subscribe({ userVisibleOnly: true, applicationServerKey: keyBytes(key.value) });
|
||||
await send("PUT", JSON.stringify(subscription));
|
||||
state.value = "on";
|
||||
}
|
||||
|
||||
async function turnOff() {
|
||||
await send("DELETE");
|
||||
const manager = (await navigator.serviceWorker.ready).pushManager;
|
||||
await (await manager.getSubscription())?.unsubscribe();
|
||||
state.value = "off";
|
||||
}
|
||||
|
||||
/** @param {string} method @param {string} [body] */
|
||||
async function send(method, body) {
|
||||
const headers = body ? { "content-type": "application/json" } : undefined;
|
||||
const response = await fetch("/api/push", { method, headers, body });
|
||||
if (!response.ok) throw new Error((await response.text()) || `the bridge said ${response.status}`);
|
||||
}
|
||||
|
||||
/** Runs `change` with the switch busy, putting back what was there if it fails. @param {() => Promise<void>} change */
|
||||
async function flip(change) {
|
||||
const before = state.value;
|
||||
state.value = "busy";
|
||||
problem.value = "";
|
||||
try {
|
||||
await change();
|
||||
} catch (error) {
|
||||
state.value = before;
|
||||
problem.value = `couldn't change notifications: ${/** @type {Error} */ (error).message}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function NotificationSwitch() {
|
||||
return html`<section class="notifications">
|
||||
<h2>Notifications</h2>
|
||||
${problem.value ? html`<p class="problem">${problem.value}</p>` : null}
|
||||
<${Choice} state=${state.value} />
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/** @param {{ state: PushState }} props */
|
||||
function Choice({ state }) {
|
||||
switch (state) {
|
||||
case "unsupported": return html`<p class="dim">Notifications aren't supported in this browser.</p>`;
|
||||
case "home-screen": return html`<p class="dim">Add Luxe to your Home Screen to enable notifications.</p>`;
|
||||
case "blocked": return html`<p class="dim">Allow notifications for Luxe in this device's settings.</p>`;
|
||||
case "on": return html`<p class="dim">Notifications are on for this device.</p>
|
||||
<button type="button" class="quiet" onClick=${() => flip(turnOff)}>Turn off</button>`;
|
||||
default: return html`<p class="dim">Get notified when a session needs an answer or finishes a long turn.</p>
|
||||
<button type="button" disabled=${state === "busy"} onClick=${() => flip(turnOn)}>
|
||||
${state === "busy" ? "Turning on…" : "Turn on"}</button>`;
|
||||
}
|
||||
}
|
||||
37
crates/luxe-remote/app/pairing.js
Normal file
37
crates/luxe-remote/app/pairing.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// @ts-check
|
||||
// Pairing from inside the app. A scanned code opens Safari, and an app kept on the home screen has
|
||||
// cookies of its own, copied from Safari only when it was added, so one that lost its pairing
|
||||
// can't get it back by scanning. Pasting the invitation link here pairs the app itself.
|
||||
|
||||
import { useState } from "preact/hooks";
|
||||
import { fieldOf, html } from "./html.js";
|
||||
|
||||
/**
|
||||
* The invitation in `text`: the link `luxe remote pair` prints, or the part after its `#`.
|
||||
* @param {string} text @returns {string | null}
|
||||
*/
|
||||
export function invitationFrom(text) {
|
||||
const token = text.trim().split("#").pop() ?? "";
|
||||
return /^[A-Za-z0-9_-]+$/.test(token) ? token : null;
|
||||
}
|
||||
|
||||
/** What an unpaired device is told, and a field for the link. */
|
||||
export function PairWithLink() {
|
||||
const [text, setText] = useState("");
|
||||
const token = invitationFrom(text);
|
||||
/** @param {SubmitEvent} event */
|
||||
const submit = (event) => {
|
||||
event.preventDefault();
|
||||
if (token) location.assign(`/pair#${token}`);
|
||||
};
|
||||
return html`<section class="pairing">
|
||||
<p>Run <code>luxe remote pair</code> on your computer, then scan its QR code or paste its link
|
||||
here.</p>
|
||||
<form class="pair-link" onSubmit=${submit}>
|
||||
<input type="text" inputmode="url" placeholder="https://…/pair#…" value=${text} autocapitalize="off"
|
||||
autocorrect="off" spellcheck="false" aria-label="Invitation link"
|
||||
onInput=${(/** @type {Event} */ event) => setText(fieldOf(event).value)} />
|
||||
<button type="submit" disabled=${!token}>Pair</button>
|
||||
</form>
|
||||
</section>`;
|
||||
}
|
||||
158
crates/luxe-remote/app/panel.css
Normal file
158
crates/luxe-remote/app/panel.css
Normal file
@@ -0,0 +1,158 @@
|
||||
/* The project panel: tabs under its bar, then the tab's view. Files is the TUI's dock tree, a
|
||||
finger tall a row, and a file's lines are drawn as a diff's are */
|
||||
|
||||
.panel-button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
align-self: center;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.panel-button .icon {
|
||||
width: 1.1lh;
|
||||
height: 1.1lh;
|
||||
}
|
||||
|
||||
/* everything in the panel starts at the dock's indent */
|
||||
.panel .bar {
|
||||
padding-inline: 1.5ch;
|
||||
}
|
||||
|
||||
/* the project's folder rides the heading's line, so the bar stays one row; plain text, glyph and
|
||||
all, as the TUI's dock heads its tree */
|
||||
.project-name {
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.badge + .project-name {
|
||||
margin-left: 1.5ch;
|
||||
}
|
||||
|
||||
.project-mark {
|
||||
margin-right: 1ch;
|
||||
}
|
||||
|
||||
/* the branch is quieter, as the TUI's section has it; a long one is what the bar cuts */
|
||||
.project-branch {
|
||||
margin-left: 2ch;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
/* The tabs are the TUI's switch: the one showing a lit badge, the others idle ones of the same
|
||||
footprint, so the row never moves as the choice flips */
|
||||
.tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1ch;
|
||||
padding: 0 1.5ch;
|
||||
}
|
||||
|
||||
/* A phone's panel has the dock's tab too: four badges are 45 cells of the 48 a 375-point iPhone
|
||||
has, so they sit fade to slab, the fade being the gap, a cell in from the edges */
|
||||
@media not all and (min-width: 50rem) and (min-height: 30rem) {
|
||||
.tabs {
|
||||
gap: 0;
|
||||
padding: 0 1ch;
|
||||
}
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 0.6lh 0;
|
||||
}
|
||||
|
||||
.panel .sheet-body {
|
||||
padding-top: 0.5lh;
|
||||
}
|
||||
|
||||
/* Rows sit flush, a line each, as the terminal's do */
|
||||
.tree-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
padding: 0 1.5ch;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.tree-row:active {
|
||||
background: var(--luxe-tool-bg, #2a2724);
|
||||
}
|
||||
|
||||
/* a level's guide, chevron and mark are two cells each, the glyph and a space */
|
||||
.guide, .chevron, .mark {
|
||||
flex: none;
|
||||
width: 2ch;
|
||||
}
|
||||
|
||||
/* the guide runs the row's full height, so a column of them reads as one line */
|
||||
.guide {
|
||||
align-self: stretch;
|
||||
background: linear-gradient(var(--luxe-border, #4b463f), var(--luxe-border, #4b463f))
|
||||
0.5ch 0 / 1px 100% no-repeat;
|
||||
}
|
||||
|
||||
.chevron {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.tree-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.tree-name.folder {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.tree-note {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.tree-right {
|
||||
flex: none;
|
||||
padding-left: 1ch;
|
||||
}
|
||||
|
||||
.tree-right.held {
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
}
|
||||
|
||||
.hue-secondary { color: var(--luxe-accent-secondary, #d2a5cd); }
|
||||
.hue-warning { color: var(--luxe-warning, #faaa51); }
|
||||
.hue-info { color: var(--luxe-info, #85c7d7); }
|
||||
.hue-success { color: var(--luxe-success, #81caa0); }
|
||||
.hue-error { color: var(--luxe-error, #e68485); }
|
||||
.hue-thinking-ultra { color: var(--luxe-thinking-ultra, #e790b7); }
|
||||
.hue-text { color: var(--luxe-text, #e4dfd6); }
|
||||
.hue-muted { color: var(--luxe-muted, #97938c); }
|
||||
|
||||
.mention {
|
||||
flex: none;
|
||||
align-self: center;
|
||||
padding: 0.25lh 1ch;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
border-radius: var(--corner);
|
||||
}
|
||||
|
||||
/* A file's lines keep their columns and scroll sideways together, as a diff's do */
|
||||
.file {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.fl {
|
||||
display: flex;
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
margin: 0;
|
||||
white-space: pre;
|
||||
tab-size: 4;
|
||||
}
|
||||
|
||||
.fl code {
|
||||
font: inherit;
|
||||
padding-right: 1ch;
|
||||
}
|
||||
98
crates/luxe-remote/app/panel.js
Normal file
98
crates/luxe-remote/app/panel.js
Normal file
@@ -0,0 +1,98 @@
|
||||
// @ts-check
|
||||
// The project panel: the TUI's views of the project, gathered behind one header button. On a phone
|
||||
// it covers the page and holds the dock's plan and changes too, so one button reaches everything;
|
||||
// on a wide screen it's a rail in the dock's place, as the TUI keeps FILES in its dock, and a file,
|
||||
// a pull request or a review chapter opens in a pane beside it, leaving the conversation up where
|
||||
// there's room. One pane at a time: opening one closes the others.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { DockTab, useEscape } from "./dock.js";
|
||||
import { FilePeek, FilesTab } from "./files-view.js";
|
||||
import { GithubPeek, GithubTab } from "./github-view.js";
|
||||
import { html } from "./html.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { panelTabs, shownTab, useWide } from "./layout.js";
|
||||
import { useRendered } from "./render.js";
|
||||
import { ReviewPeek, ReviewTab } from "./review-view.js";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @import { Listings } from "./picker.js" */
|
||||
/**
|
||||
* @typedef {import("./layout.js").Tab} Tab
|
||||
* @typedef {ReturnType<typeof createPanel>} Panel
|
||||
* @typedef {{ send: (frame: Frame) => boolean, listings: Listings, files: ReturnType<typeof import("./files.js").createFiles>,
|
||||
* github: ReturnType<typeof import("./github.js").createGithub>, review: ReturnType<typeof import("./review.js").createReview>,
|
||||
* mention: (words: string) => void, changes: any, todos: any, openDiff: (path: string) => void, diffOpen: boolean,
|
||||
* project: Project }} PanelHooks
|
||||
* @typedef {{ name: string, branch: string | null, dirty: boolean }} Project
|
||||
*/
|
||||
|
||||
/** @type {Record<Tab, (props: { hooks: PanelHooks }) => any>} */
|
||||
const TAB_VIEWS = { dock: DockTab, files: FilesTab, github: GithubTab, review: ReviewTab };
|
||||
|
||||
/** Closed; `open` shows a tab, the screen's first unless told. */
|
||||
export function createPanel() {
|
||||
const tab = signal(/** @type {Tab | null} */ (null));
|
||||
return { tab, open: (/** @type {Tab | null} */ id = null) => (tab.value = id ?? "dock"), close: () => (tab.value = null) };
|
||||
}
|
||||
|
||||
/** The header's button that opens the panel. @param {{ open: () => void }} props */
|
||||
export function PanelButton({ open }) {
|
||||
const label = useWide() ? "Project" : "Dock and project";
|
||||
return html`<button type="button" class="panel-button" aria-label=${label} onClick=${open}><${Icon} name="menu" /></button>`;
|
||||
}
|
||||
|
||||
/** @param {{ panel: Panel, hooks: PanelHooks }} props */
|
||||
export function ProjectPanel({ panel, hooks }) {
|
||||
const wide = useWide();
|
||||
// an open file, item or diff takes Escape first
|
||||
useEscape(panel.tab.value && !paneOpen(hooks) ? panel.close : null);
|
||||
if (!panel.tab.value) return null;
|
||||
const tab = shownTab(panel.tab.value, wide);
|
||||
/** @param {Tab} next */
|
||||
const pick = (next) => switchTab(panel, hooks, next);
|
||||
return html`<div class="sheet panel" role="dialog" aria-modal=${!wide} aria-label="Project">
|
||||
<header class="bar">
|
||||
<span class="title"><span class="badge">Project</span><${ProjectName} project=${hooks.project} /></span>
|
||||
<button type="button" class="close" aria-label="Close the project panel" onClick=${panel.close}><${Icon} name="close" /></button>
|
||||
</header>
|
||||
<${Tabs} tab=${tab} pick=${pick} wide=${wide} />
|
||||
<div class="sheet-body"><${TAB_VIEWS[tab]} hooks=${hooks} /></div>
|
||||
</div>
|
||||
<${FilePeek} hooks=${hooks} wide=${wide} />
|
||||
<${GithubPeek} hooks=${hooks} wide=${wide} />
|
||||
<${ReviewPeek} hooks=${hooks} wide=${wide} />`;
|
||||
}
|
||||
|
||||
/** Whether a file, an item, a chapter or a diff is open over the panel. @param {PanelHooks} hooks */
|
||||
const paneOpen = ({ files, github, review, diffOpen }) =>
|
||||
Boolean(files.open.value || github.open.value || review.open.value || diffOpen);
|
||||
|
||||
/**
|
||||
* The folder the session works in and its branch, as the TUI's project section has them, in the
|
||||
* session's header and the panel's. The host draws it so the glyphs are the TUI's, at the tree's
|
||||
* tier; the bare name stands in until it does.
|
||||
* @param {{ project: Project }} props
|
||||
*/
|
||||
export function ProjectName({ project }) {
|
||||
const rendered = useRendered({ kind: "project_name", ...project }, true);
|
||||
if (!project.name) return null;
|
||||
if (!rendered) return html`<span class="project-name">${project.name}</span>`;
|
||||
return html`<span class="project-name" dangerouslySetInnerHTML=${{ __html: rendered }}></span>`;
|
||||
}
|
||||
|
||||
/** Shows `next`, closing the pane the last tab opened. @param {Panel} panel @param {PanelHooks} hooks @param {Tab} next */
|
||||
function switchTab(panel, hooks, next) {
|
||||
hooks.files.close();
|
||||
hooks.github.close();
|
||||
hooks.review.close();
|
||||
panel.open(next);
|
||||
}
|
||||
|
||||
/** @param {{ tab: Tab, pick: (tab: Tab) => void, wide: boolean }} props */
|
||||
function Tabs({ tab, pick, wide }) {
|
||||
return html`<nav class="tabs" role="tablist" aria-label="Project views">
|
||||
${panelTabs(wide).map(({ id, title }) => html`<button type="button" role="tab" key=${id} class="tab"
|
||||
aria-selected=${id === tab} onClick=${() => pick(id)}><span class=${id === tab ? "badge raised" : "badge idle"}>${title}</span></button>`)}
|
||||
</nav>`;
|
||||
}
|
||||
86
crates/luxe-remote/app/peek.css
Normal file
86
crates/luxe-remote/app/peek.css
Normal file
@@ -0,0 +1,86 @@
|
||||
/* Where the project panel and the peek (a file or a diff) sit. On a phone each covers the page,
|
||||
a peek over the panel. On a wide screen the panel is a rail in the dock's place, since the TUI
|
||||
keeps FILES in its dock, and a peek opens between the rail and the conversation, as the TUI
|
||||
peeks beside the dock: "click a name, see the file". The conversation keeps its column only
|
||||
where the TUI's own minimums fit, so on an iPad the peek takes the main column until it closes */
|
||||
|
||||
.peek {
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
/* layout.js's WIDE, as in dock.css */
|
||||
@media (min-width: 50rem) and (min-height: 30rem) {
|
||||
:root {
|
||||
--rail: 24rem;
|
||||
}
|
||||
|
||||
.panel {
|
||||
inset: 0 auto 0 0;
|
||||
width: calc(var(--rail) + env(safe-area-inset-left));
|
||||
box-sizing: border-box;
|
||||
padding-right: 0;
|
||||
border-right: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] .panel {
|
||||
inset: 0 0 0 auto;
|
||||
width: calc(var(--rail) + env(safe-area-inset-right));
|
||||
padding-left: 0;
|
||||
border-right: none;
|
||||
border-left: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
/* the panel stands in for the dock's rail while it's open */
|
||||
#app:has(> .panel) > .dock {
|
||||
display: none;
|
||||
}
|
||||
|
||||
#app:has(> .panel) {
|
||||
padding-left: var(--rail);
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] #app:has(> .panel) {
|
||||
padding-left: 0;
|
||||
padding-right: var(--rail);
|
||||
}
|
||||
|
||||
#app:has(> .panel, > .dock.shown) > .peek {
|
||||
inset: 0 0 0 calc(var(--rail) + env(safe-area-inset-left));
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] #app:has(> .panel, > .dock.shown) > .peek {
|
||||
inset: 0 calc(var(--rail) + env(safe-area-inset-right)) 0 0;
|
||||
padding-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Room for the TUI's 56 cells of conversation, a rule and 72 of peek beside the rail: 129 cells
|
||||
of 7.8px, the app's 13px cell, and the rail's 24rem. The peek grows to the TUI's cap for a
|
||||
unified diff, 134 cells, and the conversation takes the rest */
|
||||
@media (min-width: 87rem) and (min-height: 30rem) {
|
||||
:root {
|
||||
--peek: min(100vw - var(--rail) - 57ch, 134ch);
|
||||
}
|
||||
|
||||
#app:has(> .panel, > .dock.shown) > .peek {
|
||||
right: auto;
|
||||
width: var(--peek);
|
||||
border-right: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] #app:has(> .panel, > .dock.shown) > .peek {
|
||||
left: auto;
|
||||
border-right: none;
|
||||
border-left: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
#app:has(> .peek):has(> .panel, > .dock.shown) {
|
||||
padding-left: calc(var(--rail) + var(--peek));
|
||||
}
|
||||
|
||||
:root[data-dock-side="right"] #app:has(> .peek):has(> .panel, > .dock.shown) {
|
||||
padding-left: 0;
|
||||
padding-right: calc(var(--rail) + var(--peek));
|
||||
}
|
||||
}
|
||||
86
crates/luxe-remote/app/pending.js
Normal file
86
crates/luxe-remote/app/pending.js
Normal file
@@ -0,0 +1,86 @@
|
||||
// What's waiting: prompts waiting on you, and steering waiting to reach the agent.
|
||||
//
|
||||
// A pure fold of frames, like the transcript. Prompts come and go by id: `permission_requested`
|
||||
// and `question_asked` add one, `prompt_closed` takes it down whoever answered it. A new
|
||||
// connection starts over, since the session's snapshot sends every prompt still open.
|
||||
//
|
||||
// Steering follows the TUI's tray: a checkpoint delivers everything buffered at once, and a steer
|
||||
// that misses the last one waits for the next turn, so a turn ending leaves it pending. Only a
|
||||
// cancel or a withdrawal empties the buffer.
|
||||
|
||||
import { batch, signal } from "@preact/signals";
|
||||
|
||||
/**
|
||||
* @typedef {{ kind: "permission", id: string, tool: string, summary: string, always_patterns: string[] }} PermissionPrompt
|
||||
* @typedef {{ label: string, description?: string | null, recommended?: boolean }} QuestionOption
|
||||
* @typedef {{ kind: "question", id: string, prompt: string, options: QuestionOption[], multi: boolean }} QuestionPrompt
|
||||
* @typedef {PermissionPrompt | QuestionPrompt} Prompt
|
||||
* @typedef {{ prompts: Signal<Prompt[]>, steering: Signal<number> }} State
|
||||
*/
|
||||
/** @import { Signal } from "@preact/signals" */
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
|
||||
/** Nothing waiting, and the functions that change that. */
|
||||
export function createPending() {
|
||||
/** @type {State} */
|
||||
const state = { prompts: signal([]), steering: signal(0) };
|
||||
return {
|
||||
prompts: state.prompts,
|
||||
steering: state.steering,
|
||||
/** @param {Frame} frame */
|
||||
apply: (frame) => batch(() => apply(state, frame)),
|
||||
/** This device sent a steering message. */
|
||||
steered: () => (state.steering.value += 1),
|
||||
/** This device withdrew or cancelled, which empties the engine's steering buffer. */
|
||||
dropSteering: () => (state.steering.value = 0),
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Frame} frame */
|
||||
function apply(state, { kind, content }) {
|
||||
switch (kind) {
|
||||
case "ready": state.prompts.value = []; state.steering.value = 0; return;
|
||||
case "permission_requested": return open(state, { kind: "permission", ...content });
|
||||
case "question_asked": return open(state, { kind: "question", ...content });
|
||||
case "prompt_closed": return close(state, content.id);
|
||||
case "steering_delivered": state.steering.value = 0; return;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Prompt} prompt */
|
||||
function open(state, prompt) {
|
||||
if (state.prompts.value.some((known) => known.id === prompt.id)) return;
|
||||
state.prompts.value = [...state.prompts.value, prompt];
|
||||
}
|
||||
|
||||
/** @param {State} state @param {string} id */
|
||||
function close(state, id) {
|
||||
state.prompts.value = state.prompts.value.filter((prompt) => prompt.id !== id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reply frame for a permission prompt.
|
||||
* @param {string} id @param {string} reply @returns {Frame}
|
||||
*/
|
||||
export function permissionReply(id, reply) {
|
||||
return { kind: "respond_permission", content: { id, reply } };
|
||||
}
|
||||
|
||||
/**
|
||||
* The reply frame for a question: the chosen answers, or none for a dismissal.
|
||||
* @param {string} id @param {string[] | null} answered @returns {Frame}
|
||||
*/
|
||||
export function questionReply(id, answered) {
|
||||
return { kind: "answer_question", content: { id, reply: answered ? { answered } : "cancelled" } };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the composer sends: steering for the turn running, or a new turn. Steering carries only
|
||||
* words, so a message with images is always a new turn, which waits for a running one to end.
|
||||
* @param {string} text @param {boolean} busy @param {{ data: string, mime: string, name: string | null }[]} images
|
||||
* @returns {Frame}
|
||||
*/
|
||||
export function messageFrame(text, busy, images = []) {
|
||||
if (images.length) return { kind: "submit_user_message", content: { text, images } };
|
||||
return busy ? { kind: "steer_turn", content: { text } } : { kind: "submit_user_message", content: { text } };
|
||||
}
|
||||
80
crates/luxe-remote/app/photos.js
Normal file
80
crates/luxe-remote/app/photos.js
Normal file
@@ -0,0 +1,80 @@
|
||||
// @ts-check
|
||||
// Photos for the composer: from the camera or the library, made small enough to send.
|
||||
//
|
||||
// A phone's photo is 12 megapixels and several megabytes, and the model sees no more than about
|
||||
// 1568 pixels on the longest side (Anthropic's advice; larger is scaled down on arrival), so it
|
||||
// is scaled here, before it crosses the network, and sent as a JPEG.
|
||||
|
||||
import { useState } from "preact/hooks";
|
||||
|
||||
/** The longest side a photo is sent at. */
|
||||
export const LONGEST_EDGE = 1568;
|
||||
|
||||
/** JPEG quality: text in a screenshot stays sharp, and a photo stays a few hundred kilobytes. */
|
||||
const QUALITY = 0.85;
|
||||
|
||||
/**
|
||||
* `width` by `height` scaled to fit within `longest` on its longer side, never scaled up.
|
||||
* @param {number} width @param {number} height @param {number} longest
|
||||
*/
|
||||
export function fitWithin(width, height, longest = LONGEST_EDGE) {
|
||||
const scale = Math.min(1, longest / Math.max(width, height));
|
||||
return { width: Math.round(width * scale), height: Math.round(height * scale) };
|
||||
}
|
||||
|
||||
/**
|
||||
* A photo as the engine takes it, plus a preview to show meanwhile.
|
||||
* @typedef {{ data: string, mime: string, name: string | null, preview: string }} Photo
|
||||
*/
|
||||
|
||||
/**
|
||||
* `file` as an attachment the engine takes, plus a preview to show meanwhile.
|
||||
* @param {File} file @returns {Promise<Photo>}
|
||||
*/
|
||||
export async function attachment(file) {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
const size = fitWithin(bitmap.width, bitmap.height);
|
||||
const canvas = document.createElement("canvas");
|
||||
Object.assign(canvas, size);
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) throw new Error("this browser can't prepare photos");
|
||||
// a JPEG has no transparency, and black is what a transparent screenshot would get otherwise
|
||||
context.fillStyle = "#fff";
|
||||
context.fillRect(0, 0, size.width, size.height);
|
||||
context.drawImage(bitmap, 0, 0, size.width, size.height);
|
||||
bitmap.close();
|
||||
const preview = canvas.toDataURL("image/jpeg", QUALITY);
|
||||
return { data: dataOf(preview), mime: "image/jpeg", name: file.name || null, preview };
|
||||
}
|
||||
|
||||
/** The base64 part of a `data:` URL. @param {string} url */
|
||||
export function dataOf(url) {
|
||||
return url.slice(url.indexOf(",") + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* The attachments as `submit_user_message` takes them, without their previews.
|
||||
* @param {Photo[]} photos
|
||||
*/
|
||||
export function forTheWire(photos) {
|
||||
return photos.map(({ data, mime, name }) => ({ data, mime, name }));
|
||||
}
|
||||
|
||||
/** The photos attached to the message being written. */
|
||||
export function usePhotos() {
|
||||
const [list, setList] = useState(/** @type {Photo[]} */ ([]));
|
||||
const [problem, setProblem] = useState("");
|
||||
/** @param {FileList} files */
|
||||
const add = async (files) => {
|
||||
setProblem("");
|
||||
try {
|
||||
const made = await Promise.all([...files].map(attachment));
|
||||
setList((now) => [...now, ...made]);
|
||||
} catch (error) {
|
||||
setProblem(`couldn't use that photo: ${/** @type {Error} */ (error).message}`);
|
||||
}
|
||||
};
|
||||
/** @param {number} index */
|
||||
const remove = (index) => setList((now) => now.filter((_, at) => at !== index));
|
||||
return { list, problem, add, remove, clear: () => setList([]) };
|
||||
}
|
||||
92
crates/luxe-remote/app/picker.js
Normal file
92
crates/luxe-remote/app/picker.js
Normal file
@@ -0,0 +1,92 @@
|
||||
// @ts-check
|
||||
// What the box offers as you type: the slash commands at the start of a message, and project
|
||||
// files after an `@`. A tap fills in or runs the choice, and the box keeps the keyboard, since a
|
||||
// button that took focus would drop it.
|
||||
|
||||
import { useEffect } from "preact/hooks";
|
||||
import { matchCommands } from "./commands.js";
|
||||
import { html } from "./html.js";
|
||||
import { matchEntries, mentionAt, pickEntry } from "./mentions.js";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @import { Command } from "./commands.js" */
|
||||
/** @import { Entry, Listing } from "./mentions.js" */
|
||||
/**
|
||||
* @typedef {{ key: string, label: string, hint: string, command?: Command, entry?: Entry }} Suggestion
|
||||
* @typedef {{ text: string, caret: number, placed?: boolean }} Draft
|
||||
* @typedef {ReturnType<typeof import("./mentions.js").createListings>} Listings
|
||||
*/
|
||||
|
||||
/** The most entries listed at once; typing narrows the rest. */
|
||||
const MOST = 8;
|
||||
|
||||
/** What to offer for `draft`, from the folders listed so far. @param {Draft} draft @param {Record<string, Listing>} folders */
|
||||
export function suggestions(draft, folders) {
|
||||
const commands = matchCommands(draft.text);
|
||||
if (commands.length) return commands.map(commandSuggestion);
|
||||
const query = mentionAt(draft.text, draft.caret);
|
||||
if (!query) return [];
|
||||
return matchEntries(folders[query.folder]?.entries ?? [], query.name).slice(0, MOST).map(entrySuggestion);
|
||||
}
|
||||
|
||||
/** @param {Command} command @returns {Suggestion} */
|
||||
function commandSuggestion(command) {
|
||||
return { key: command.name, label: `/${command.name}`, hint: command.title, command };
|
||||
}
|
||||
|
||||
/** @param {Entry} entry @returns {Suggestion} */
|
||||
function entrySuggestion(entry) {
|
||||
return { key: entry.name, label: entry.kind === "directory" ? `${entry.name}/` : entry.name, hint: "", entry };
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft after picking `item`: a file or folder replaces the mention, and a command that takes
|
||||
* words goes into the box to finish. Null for a command that runs as it is.
|
||||
* @param {Draft} draft @param {Suggestion} item @returns {Draft | null}
|
||||
*/
|
||||
export function afterPick(draft, item) {
|
||||
const query = mentionAt(draft.text, draft.caret);
|
||||
if (item.entry && query) return { ...pickEntry(draft.text, draft.caret, query, item.entry), placed: true };
|
||||
if (!item.command?.takes) return null;
|
||||
const text = `/${item.command.name} `;
|
||||
return { text, caret: text.length, placed: true };
|
||||
}
|
||||
|
||||
/** What the picker says when it has nothing to list yet. @param {Draft} draft @param {Record<string, Listing>} folders */
|
||||
export function pickerNote(draft, folders) {
|
||||
const query = mentionAt(draft.text, draft.caret);
|
||||
const listing = query ? folders[query.folder] : undefined;
|
||||
const where = query?.folder || "the project";
|
||||
if (listing?.state === "asking") return "Listing files…";
|
||||
if (listing?.state === "failed") return `Couldn't list ${where}`;
|
||||
if (listing?.state === "listed" && !listing.entries.length) return `No files in ${where}`;
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ draft: Draft, listings: Listings, send: (frame: Frame) => boolean,
|
||||
* place: (draft: Draft) => void, run: (text: string) => void }} props
|
||||
*/
|
||||
export function Picker({ draft, listings, send, place, run }) {
|
||||
const folder = mentionAt(draft.text, draft.caret)?.folder;
|
||||
useEffect(() => void (folder !== undefined && listings.ask(folder, send)), [folder]);
|
||||
const folders = listings.folders.value;
|
||||
const items = suggestions(draft, folders);
|
||||
const note = items.length ? "" : pickerNote(draft, folders);
|
||||
if (!items.length && !note) return null;
|
||||
/** @param {Suggestion} item */
|
||||
const choose = (item) => {
|
||||
const next = afterPick(draft, item);
|
||||
if (next) place(next);
|
||||
else run(`/${item.command?.name}`);
|
||||
};
|
||||
return html`<ul class="picker" aria-label="Suggestions">${note ? html`<li class="dim">${note}</li>` : null}
|
||||
${items.map((item) => html`<li key=${item.key}><button type="button" onPointerDown=${keepFocus} onClick=${() => choose(item)}>
|
||||
<span class="name">${item.label}</span>${item.hint ? html` <span class="dim">${item.hint}</span>` : null}</button></li>`)}
|
||||
</ul>`;
|
||||
}
|
||||
|
||||
/** Keeps the box focused, and the keyboard up, through a tap on a suggestion. @param {Event} event */
|
||||
function keepFocus(event) {
|
||||
event.preventDefault();
|
||||
}
|
||||
130
crates/luxe-remote/app/prompt.js
Normal file
130
crates/luxe-remote/app/prompt.js
Normal file
@@ -0,0 +1,130 @@
|
||||
// @ts-check
|
||||
// The prompt waiting on you, above the composer: a permission to grant or a question to answer.
|
||||
//
|
||||
// Like the TUI's card, it holds back every answer but the refusal for a moment after it appears,
|
||||
// since it can slide in under a thumb aimed at Send; a tap that lands then can't grant anything.
|
||||
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { fieldOf, html } from "./html.js";
|
||||
import { permissionReply, questionReply } from "./pending.js";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @import { PermissionPrompt, Prompt, QuestionOption, QuestionPrompt } from "./pending.js" */
|
||||
/** @typedef {(frame: Frame) => boolean} Send */
|
||||
|
||||
/** How long a new prompt ignores everything but a refusal, as the TUI's `GRACE`. */
|
||||
export const GRACE_MS = 400;
|
||||
|
||||
/** @param {{ prompts: Prompt[], send: Send }} props */
|
||||
export function PromptCard({ prompts, send }) {
|
||||
const prompt = prompts[0];
|
||||
const settled = useSettled(prompt?.id);
|
||||
if (!prompt) return null;
|
||||
const count = prompts.length > 1 ? html`<span class="dim"> 1 of ${prompts.length}</span>` : null;
|
||||
const card = prompt.kind === "permission"
|
||||
? html`<${Permission} prompt=${prompt} send=${send} settled=${settled} />`
|
||||
: html`<${Question} key=${prompt.id} prompt=${prompt} send=${send} settled=${settled} />`;
|
||||
return html`<section class="prompt" role="dialog" aria-label=${prompt.kind}>${count}${card}</section>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* False for [`GRACE_MS`] after the prompt `id` appears. Keyed by id rather than a flag reset in an
|
||||
* effect, which would leave the next prompt one render with the last one's grace already spent.
|
||||
* @param {string | undefined} id
|
||||
*/
|
||||
function useSettled(id) {
|
||||
const [settledId, setSettledId] = useState(/** @type {string | undefined} */ (undefined));
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setSettledId(id), GRACE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [id]);
|
||||
return id != null && settledId === id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The TUI's answers, in its order; the two that remember only when the call has a pattern to.
|
||||
* @param {PermissionPrompt} prompt
|
||||
*/
|
||||
export function permissionChoices(prompt) {
|
||||
const patterns = prompt.always_patterns ?? [];
|
||||
const remembered = patterns.join(", ");
|
||||
return [
|
||||
{ reply: "once", label: "Allow once", hint: "run just this call" },
|
||||
...(patterns.length
|
||||
? [
|
||||
{ reply: "always", label: "Allow for this session", hint: `remember ${remembered}` },
|
||||
{ reply: "always_persist", label: "Allow always", hint: `save ${remembered} to your permissions` },
|
||||
]
|
||||
: []),
|
||||
{ reply: "reject", label: "Reject", hint: "deny this call" },
|
||||
];
|
||||
}
|
||||
|
||||
/** @param {{ prompt: PermissionPrompt, send: Send, settled: boolean }} props */
|
||||
function Permission({ prompt, send, settled }) {
|
||||
return html`
|
||||
<p class="prompt-title">${prompt.tool} wants permission</p>
|
||||
<p class="prompt-summary">${prompt.summary}</p>
|
||||
<div class="choices">
|
||||
${permissionChoices(prompt).map((choice) => html`
|
||||
<button type="button" class=${`choice ${choice.reply}`} disabled=${!settled && choice.reply !== "reject"}
|
||||
onClick=${() => send(permissionReply(prompt.id, choice.reply))}>
|
||||
<span class="choice-label">${choice.label}</span>
|
||||
<span class="choice-hint">${choice.hint}</span>
|
||||
</button>`)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ prompt: QuestionPrompt, send: Send, settled: boolean }} props */
|
||||
function Question({ prompt, send, settled }) {
|
||||
const [chosen, setChosen] = useState(/** @type {string[]} */ ([]));
|
||||
/** @param {string[] | null} answered */
|
||||
const answer = (answered) => send(questionReply(prompt.id, answered));
|
||||
/** @param {string} label */
|
||||
const pick = (label) => (prompt.multi ? setChosen(toggled(chosen, label)) : answer([label]));
|
||||
return html`
|
||||
<p class="prompt-title">${prompt.prompt}</p>
|
||||
<div class="choices">
|
||||
${prompt.options.map((option) => html`<${QuestionChoice} option=${option} settled=${settled}
|
||||
picked=${chosen.includes(option.label)} multi=${prompt.multi} onPick=${() => pick(option.label)} />`)}
|
||||
</div>
|
||||
<${OwnAnswer} chosen=${chosen} settled=${settled} answer=${answer} />
|
||||
<button type="button" class="dismiss" onClick=${() => answer(null)}>Dismiss</button>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Words of your own, sent with whatever options are ticked.
|
||||
* @param {{ chosen: string[], settled: boolean, answer: (answered: string[]) => void }} props
|
||||
*/
|
||||
function OwnAnswer({ chosen, settled, answer }) {
|
||||
const [own, setOwn] = useState("");
|
||||
const typed = own.trim();
|
||||
const ready = settled && (chosen.length > 0 || typed !== "");
|
||||
/** @param {SubmitEvent} event */
|
||||
const submit = (event) => {
|
||||
event.preventDefault();
|
||||
if (ready) answer([...chosen, ...(typed ? [typed] : [])]);
|
||||
};
|
||||
return html`<form class="own-answer" onSubmit=${submit}>
|
||||
<input type="text" placeholder="Type your own answer" value=${own} onInput=${(/** @type {Event} */ event) => setOwn(fieldOf(event).value)} />
|
||||
<button type="submit" disabled=${!ready}>Send</button>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ option: QuestionOption, settled: boolean, picked: boolean, multi: boolean,
|
||||
* onPick: () => void }} props
|
||||
*/
|
||||
function QuestionChoice({ option, settled, picked, multi, onPick }) {
|
||||
const mark = multi ? html`<span class="check" aria-hidden="true">${picked ? "[x] " : "[ ] "}</span>` : null;
|
||||
return html`<button type="button" class=${`choice ${picked ? "picked" : ""}`} disabled=${!settled}
|
||||
aria-pressed=${multi ? picked : undefined} onClick=${onPick}>
|
||||
<span class="choice-label">${mark}${option.label}${option.recommended ? html`<span class="recommended"> recommended</span>` : null}</span>
|
||||
${option.description ? html`<span class="choice-hint">${option.description}</span>` : null}
|
||||
</button>`;
|
||||
}
|
||||
|
||||
/** `list` with `label` added, or taken out if it was there. @param {string[]} list @param {string} label */
|
||||
export function toggled(list, label) {
|
||||
return list.includes(label) ? list.filter((item) => item !== label) : [...list, label];
|
||||
}
|
||||
143
crates/luxe-remote/app/render.js
Normal file
143
crates/luxe-remote/app/render.js
Normal file
@@ -0,0 +1,143 @@
|
||||
// @ts-check
|
||||
// Text as the host renders it, through `/api/render`: the app parses no markdown itself.
|
||||
//
|
||||
// Everything asked for in the same moment goes in one request, so a transcript loading a hundred
|
||||
// messages costs one round trip, not a hundred. A finished piece is kept, so scrolling and
|
||||
// reconnecting don't ask again; a growing reply isn't, since each version is seen once.
|
||||
|
||||
import { useEffect, useRef, useState } from "preact/hooks";
|
||||
|
||||
/**
|
||||
* @typedef {{ kind: "answer" | "reasoning", text: string }
|
||||
* | { kind: "user", content: { type: string, content?: string }[] }
|
||||
* | { kind: "tool", name: string }
|
||||
* | { kind: "status", [fact: string]: any }
|
||||
* | { kind: "plan", todos: any } | { kind: "changes", changes: any }
|
||||
* | { kind: "diff", diff: any } | { kind: "diff_failed", error: any }
|
||||
* | { kind: "file", file: any } | { kind: "file_failed", error: any }
|
||||
* | { kind: "tree", rows: import("./files.js").TreeRow[], changes: any }
|
||||
* | { kind: "github_list", repository: string | null, section: any, now: number }
|
||||
* | { kind: "github_header" | "github_overview", overview: any, now: number | undefined }
|
||||
* | { kind: "github_conversation", entries: any, now: number | undefined, opened_by_you: boolean }
|
||||
* | { kind: "project_name", name: string, branch: string | null, dirty: boolean }
|
||||
* | { kind: "mode_name", mode: string }
|
||||
* | { kind: "review_guide", review: any, reading: any[], walked: string[] }
|
||||
* | { kind: "review_chapter", chapter: any, files: any[], place: { number: number, total: number, walked: boolean }, reading: any,
|
||||
* findings: any[] }} Piece
|
||||
* @typedef {(pieces: Piece[]) => Promise<string[]>} Post
|
||||
* @typedef {{
|
||||
* piece: Piece, key: string, keep: boolean,
|
||||
* resolve: (html: string) => void, reject: (error: unknown) => void,
|
||||
* }} Asked
|
||||
* @typedef {{ post: Post, kept: Map<string, string>, queue: Asked[] }} State
|
||||
*/
|
||||
|
||||
/** The most finished pieces kept; the oldest goes first. */
|
||||
const KEPT = 2000;
|
||||
|
||||
/** How long a growing reply waits between renders, at least. */
|
||||
const GROWING_PAUSE_MS = 150;
|
||||
|
||||
/** A renderer that sends its batches with `post`. */
|
||||
export function createRenderer(post = postPieces) {
|
||||
/** @type {State} */
|
||||
const state = { post, kept: new Map(), queue: [] };
|
||||
return {
|
||||
/** The HTML for `piece` if it's been kept. @param {Piece} piece */
|
||||
peek: (piece) => state.kept.get(keyOf(piece)),
|
||||
/** @param {Piece} piece @param {{ keep: boolean }} options @returns {Promise<string>} */
|
||||
render: (piece, { keep }) => ask(state, piece, keep),
|
||||
};
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Piece} piece @param {boolean} keep @returns {Promise<string>} */
|
||||
function ask(state, piece, keep) {
|
||||
const key = keyOf(piece);
|
||||
const known = state.kept.get(key);
|
||||
if (known !== undefined) return Promise.resolve(known);
|
||||
if (!state.queue.length) queueMicrotask(() => flush(state));
|
||||
return new Promise((resolve, reject) => state.queue.push({ piece, key, keep, resolve, reject }));
|
||||
}
|
||||
|
||||
/** @param {State} state */
|
||||
function flush(state) {
|
||||
const batch = state.queue;
|
||||
state.queue = [];
|
||||
sendBatch(state.post, batch, state.kept);
|
||||
}
|
||||
|
||||
/** @param {Post} post @param {Asked[]} batch @param {Map<string, string>} kept */
|
||||
function sendBatch(post, batch, kept) {
|
||||
post(batch.map((asked) => asked.piece)).then(
|
||||
(html) => batch.forEach((asked, index) => {
|
||||
if (asked.keep) keep(kept, asked.key, html[index]);
|
||||
asked.resolve(html[index]);
|
||||
}),
|
||||
(error) => batch.forEach((asked) => asked.reject(error)),
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {Map<string, string>} kept @param {string} key @param {string} html */
|
||||
function keep(kept, key, html) {
|
||||
kept.set(key, html);
|
||||
const oldest = kept.keys().next().value;
|
||||
if (kept.size > KEPT && oldest !== undefined) kept.delete(oldest);
|
||||
}
|
||||
|
||||
/** @param {Piece} piece */
|
||||
export function keyOf(piece) {
|
||||
return JSON.stringify(piece);
|
||||
}
|
||||
|
||||
/** @type {Post} */
|
||||
async function postPieces(pieces) {
|
||||
const response = await fetch("/api/render", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ pieces }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`rendering failed: ${response.status}`);
|
||||
return (await response.json()).html;
|
||||
}
|
||||
|
||||
/** The app's one renderer, so everything on screen batches together. */
|
||||
export const renderer = createRenderer();
|
||||
|
||||
/**
|
||||
* `piece` as HTML, or undefined until the host answers. While `growing`, a newer version waits
|
||||
* for the one in flight, so a streaming reply is rendered as fast as the round trip allows and
|
||||
* no faster; the last HTML stays up meanwhile.
|
||||
* @param {Piece} piece @param {boolean} growing
|
||||
*/
|
||||
export function useRendered(piece, growing) {
|
||||
const [shown, setShown] = useState(() => renderer.peek(piece));
|
||||
const wanted = useRef(piece);
|
||||
const asking = useRef(false);
|
||||
wanted.current = piece;
|
||||
const key = keyOf(piece);
|
||||
useEffect(() => {
|
||||
if (asking.current) return;
|
||||
asking.current = true;
|
||||
keepUp(wanted, growing, setShown).finally(() => (asking.current = false));
|
||||
}, [key]);
|
||||
return shown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the wanted piece until what was rendered is still what's wanted.
|
||||
* @param {{ current: Piece }} wanted @param {boolean} growing @param {(html: string) => void} setShown
|
||||
*/
|
||||
async function keepUp(wanted, growing, setShown) {
|
||||
for (;;) {
|
||||
const piece = wanted.current;
|
||||
try {
|
||||
setShown(await renderer.render(piece, { keep: !growing }));
|
||||
} catch (error) {
|
||||
console.warn(error);
|
||||
return;
|
||||
}
|
||||
// by key: a parent drawing again hands over an equal piece that is a new object
|
||||
if (keyOf(wanted.current) === keyOf(piece)) return;
|
||||
await new Promise((resolve) => setTimeout(resolve, GROWING_PAUSE_MS));
|
||||
}
|
||||
}
|
||||
92
crates/luxe-remote/app/review-view.js
Normal file
92
crates/luxe-remote/app/review-view.js
Normal file
@@ -0,0 +1,92 @@
|
||||
// @ts-check
|
||||
// The Review tab: the open review's guide, which the host draws as the TUI's guide pane, and a
|
||||
// tapped chapter open in the peek with its notes, diffs and comments. Reviewed marks the chapter
|
||||
// walked, as reading to its end does in the TUI, Next opens the one after, and Comment writes on
|
||||
// the picked lines or the chapter.
|
||||
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { chapterPiece, guidePiece, nextChapter, targetName } from "./review.js";
|
||||
import { useRendered } from "./render.js";
|
||||
import { html, landedIn } from "./html.js";
|
||||
import { useEscape } from "./dock.js";
|
||||
import { Icon } from "./icons.js";
|
||||
import { PickablePiece } from "./lines-view.js";
|
||||
import { CommentSheet, Unsent, composeAt, composedEdit, tapCard } from "./comments-view.js";
|
||||
|
||||
/** @import { PanelHooks } from "./panel.js" */
|
||||
/** @import { ReviewShown } from "./review.js" */
|
||||
/** @import { Composing } from "./comments-view.js" */
|
||||
|
||||
/** @param {{ hooks: PanelHooks }} props */
|
||||
export function ReviewTab({ hooks }) {
|
||||
const { review, send } = hooks;
|
||||
useEffect(() => void review.ask(send), []);
|
||||
const shown = review.shown.value;
|
||||
if (!shown.review) return html`<${Empty} shown=${shown} hooks=${hooks} />`;
|
||||
return html`<p class="rv-target">${targetName(shown.review.target)}</p><${Unsent} shown=${shown} hooks=${hooks} />
|
||||
<${Guide} shown=${shown} hooks=${hooks} />`;
|
||||
}
|
||||
|
||||
/** @param {{ shown: ReviewShown, hooks: PanelHooks }} props */
|
||||
function Guide({ shown, hooks }) {
|
||||
const rendered = useRendered(guidePiece(shown), false);
|
||||
return html`<div class="rv-view" onClick=${(/** @type {MouseEvent} */ event) => tapChapter(event, hooks)}
|
||||
dangerouslySetInnerHTML=${{ __html: rendered ?? "" }}></div>`;
|
||||
}
|
||||
|
||||
/** What the tab says with no review to show, and the way to get one. @param {{ shown: ReviewShown, hooks: PanelHooks }} props */
|
||||
function Empty({ shown, hooks }) {
|
||||
const { review, send } = hooks;
|
||||
const again = (/** @type {string} */ words, /** @type {() => void} */ act) =>
|
||||
html`<button type="button" class="retry" onClick=${act}>${words}</button>`;
|
||||
switch (shown.state) {
|
||||
case "lost": return html`<p class="diff-note">Connection lost. ${again("Try again", () => review.ask(send))}</p>`;
|
||||
case "failed": return html`<p class="diff-note">${shown.error} ${again("Try again", () => review.load(send))}</p>`;
|
||||
case "loading": return html`<p class="diff-note">Reading the changes…</p>`;
|
||||
case "shown": return html`<p class="diff-note">No review is open. ${again("Review changes", () => review.load(send))}</p>`;
|
||||
default: return html`<p class="diff-note">Loading…</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A tap on a chapter opens it in the peek, in place of any other pane. @param {MouseEvent} event @param {PanelHooks} hooks */
|
||||
export function tapChapter(event, { review, files, github }) {
|
||||
const chapter = /** @type {HTMLElement | null} */ (landedIn(event, "[data-chapter]"));
|
||||
if (!chapter?.dataset.chapter) return;
|
||||
files.close();
|
||||
github.close();
|
||||
review.pick(chapter.dataset.chapter);
|
||||
}
|
||||
|
||||
/**
|
||||
* The open chapter, in the pane a file opens in. Escape closes it before the panel.
|
||||
* @param {{ hooks: PanelHooks, wide: boolean }} props
|
||||
*/
|
||||
export function ReviewPeek({ hooks, wide }) {
|
||||
const { review, send } = hooks;
|
||||
const id = review.open.value;
|
||||
const [composing, compose] = useState(/** @type {Composing | null} */ (null));
|
||||
useEffect(() => compose(null), [id]);
|
||||
useEscape(composing ? () => compose(null) : id ? review.close : null);
|
||||
const shown = review.shown.value;
|
||||
if (!id || !shown.review) return null;
|
||||
const piece = chapterPiece(shown, id);
|
||||
const submit = (/** @type {string} */ body, /** @type {boolean} */ question, /** @type {boolean} */ now) =>
|
||||
composing && (review.edit(send, composedEdit(composing, body, question, now)), compose(null));
|
||||
return html`<div class="sheet peek" role="dialog" aria-modal=${!wide} aria-label=${`Chapter ${piece.place.number} of ${piece.place.total}`}>
|
||||
<${ChapterBar} hooks=${hooks} id=${id} place=${piece.place} next=${nextChapter(shown.review, id)} />
|
||||
${shown.problem ? html`<p class="diff-note">${shown.problem}</p>` : null}
|
||||
<div class="sheet-body rv-view" key=${id} onClick=${(/** @type {MouseEvent} */ event) => tapCard(event, hooks, compose)}>
|
||||
<${PickablePiece} piece=${piece} ask=${hooks.mention} comment=${(/** @type {any} */ pick) => compose(composeAt(shown.review, id, pick))} /></div>
|
||||
${composing ? html`<${CommentSheet} key=${composing.heading} composing=${composing} submit=${submit} cancel=${() => compose(null)} />` : null}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** @param {{ hooks: PanelHooks, id: string, place: { number: number, total: number, walked: boolean }, next: string | null }} props */
|
||||
function ChapterBar({ hooks: { review, send }, id, place, next }) {
|
||||
return html`<header class="bar">
|
||||
<span class="title">Chapter ${place.number} of ${place.total}</span>
|
||||
<button type="button" class="mention" aria-pressed=${place.walked} onClick=${() => review.walk(id, send)}>Reviewed</button>
|
||||
${next ? html`<button type="button" class="mention" onClick=${() => review.pick(next)}>Next</button>` : null}
|
||||
<button type="button" class="close" aria-label="Close" onClick=${review.close}><${Icon} name="close" /></button>
|
||||
</header>`;
|
||||
}
|
||||
262
crates/luxe-remote/app/review.css
Normal file
262
crates/luxe-remote/app/review.css
Normal file
@@ -0,0 +1,262 @@
|
||||
/* The Review tab and its peek, as the TUI's guide pane draws a review: each chapter's place and
|
||||
kind dim over its title in the accent, its rationale as prose, its files leaning in under it, and
|
||||
a chapter that needs nothing receding to a muted title and one dim line */
|
||||
|
||||
.rv-target {
|
||||
margin: 0.5lh 1.5ch 0;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.rv-view {
|
||||
padding: 0 1.5ch 1lh;
|
||||
}
|
||||
|
||||
.rv-brief {
|
||||
margin: 0.5lh 0 1lh;
|
||||
}
|
||||
|
||||
.rv-chapter {
|
||||
margin: 0 0 1lh;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.rv-meta {
|
||||
display: flex;
|
||||
gap: 3ch;
|
||||
margin: 0;
|
||||
color: var(--luxe-dim, #4d4a45);
|
||||
}
|
||||
|
||||
.rv-walked {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
.rv-title {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
font: inherit;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
.rv-title.quiet {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.rv-chapter-view .rv-title {
|
||||
font-weight: bold;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* the TUI leans prose in 4 cells under its title; a phone has half the columns, so 2 */
|
||||
.rv-reason {
|
||||
margin: 0;
|
||||
padding-left: 2ch;
|
||||
color: var(--luxe-dim, #4d4a45);
|
||||
}
|
||||
|
||||
.rv-prose {
|
||||
padding-left: 2ch;
|
||||
}
|
||||
|
||||
.rv-prose.md p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.rv-impact p::before {
|
||||
content: "\2192 ";
|
||||
}
|
||||
|
||||
.rv-files {
|
||||
margin: 0.5lh 0 0;
|
||||
padding: 0 0 0 2ch;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* a long path wraps under itself, past the status letter, with its figures following it */
|
||||
.rv-files li {
|
||||
padding-left: 2ch;
|
||||
text-indent: -2ch;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.rv-status {
|
||||
margin-right: 1ch;
|
||||
}
|
||||
|
||||
.rv-added,
|
||||
.rv-deleted,
|
||||
.rv-files .rv-dim {
|
||||
margin-left: 1ch;
|
||||
}
|
||||
|
||||
.rv-added,
|
||||
.rv-deleted {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.rv-added {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
.rv-deleted {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
.rv-dim,
|
||||
.rv-more {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.rv-status.tone-added {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
.rv-status.tone-modified {
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
}
|
||||
|
||||
.rv-status.tone-deleted {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
.rv-status.tone-moved {
|
||||
color: var(--luxe-info, #85c7d7);
|
||||
}
|
||||
|
||||
.rv-head {
|
||||
margin: 0.5lh 0 1lh;
|
||||
}
|
||||
|
||||
.rv-file {
|
||||
margin: 1lh 0 0.5lh;
|
||||
color: var(--luxe-info, #85c7d7);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.rv-symbol {
|
||||
margin: 0.5lh 0 0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.rv-note {
|
||||
margin: 0.25lh 0 0.5lh;
|
||||
}
|
||||
|
||||
.sheet .bar .mention[aria-pressed="true"] {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
/* A comment is a card washed in its state's hue, as the TUI tints its cards (9% into the
|
||||
background), under the hunk it's about */
|
||||
.rv-finding {
|
||||
--tone: var(--luxe-muted, #97938c);
|
||||
margin: 0.5lh 0 1lh;
|
||||
padding: 0.25lh 1ch;
|
||||
border: 1px solid color-mix(in srgb, var(--tone) 45%, transparent);
|
||||
border-radius: var(--corner);
|
||||
background: color-mix(in srgb, var(--tone) 9%, var(--luxe-background, #12100e));
|
||||
}
|
||||
|
||||
/* rv- prefixed: the status line's plain tone-* classes color text, and a card only tints */
|
||||
.rv-finding.rv-tone-warning { --tone: var(--luxe-warning, #faaa51); }
|
||||
.rv-finding.rv-tone-success { --tone: var(--luxe-success, #81caa0); }
|
||||
.rv-finding.rv-tone-info { --tone: var(--luxe-info, #85c7d7); }
|
||||
.rv-finding.rv-tone-dim { --tone: var(--luxe-dim, #4d4a45); }
|
||||
|
||||
.rv-finding-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0 2ch;
|
||||
margin: 0;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.rv-label {
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.rv-state {
|
||||
color: var(--tone);
|
||||
}
|
||||
|
||||
.rv-finding-body,
|
||||
.rv-said .md {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.rv-said {
|
||||
padding-left: 2ch;
|
||||
}
|
||||
|
||||
.rv-who {
|
||||
margin: 0.5lh 0 0;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.rv-finding-acts,
|
||||
.rv-compose-acts,
|
||||
.rv-kinds {
|
||||
display: flex;
|
||||
gap: 1ch;
|
||||
margin: 0.5lh 0 0;
|
||||
}
|
||||
|
||||
.rv-compose-acts {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.rv-unsent {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2ch;
|
||||
margin: 0.5lh 1.5ch 0;
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
}
|
||||
|
||||
/* The composer holds the foot of the chapter while it's open, above the keyboard */
|
||||
.rv-compose {
|
||||
padding: 0 1.5ch calc(0.5lh + env(safe-area-inset-bottom));
|
||||
border-top: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
background: var(--luxe-background, #12100e);
|
||||
}
|
||||
|
||||
.rv-compose .bar {
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
/* the composer takes over from the line bar while it's open */
|
||||
.peek:has(.rv-compose) .line-ask {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.rv-compose textarea:focus-visible {
|
||||
outline: 1px solid var(--luxe-accent, #ddc084);
|
||||
outline-offset: 0;
|
||||
}
|
||||
|
||||
.rv-compose textarea {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
margin-top: 0.5lh;
|
||||
padding: 0.25lh 1ch;
|
||||
resize: vertical;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: var(--luxe-surface, #1a1816);
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
border-radius: var(--corner);
|
||||
}
|
||||
|
||||
.mention[aria-pressed="true"] {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
border-color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.mention:disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
169
crates/luxe-remote/app/review.js
Normal file
169
crates/luxe-remote/app/review.js
Normal file
@@ -0,0 +1,169 @@
|
||||
// @ts-check
|
||||
// The Review tab's state: the review open in the session, joined rather than replaced, and the one
|
||||
// chapter open in the peek.
|
||||
//
|
||||
// A session holds one review, and loading one makes a new one with no comments or progress, so the
|
||||
// tab asks for whatever is open (`show_open_review`) and offers to review the working changes only
|
||||
// when nothing is. A review loaded or re-guided afterwards, by any client, is the open one now, so
|
||||
// the tab asks again. The guide goes to the host without its hunks' lines, which it doesn't draw;
|
||||
// what needs reading comes with the answer, since it's decided from those lines. Comments change
|
||||
// through `edit_review`, and every change, whoever made it, comes back as the whole session.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/**
|
||||
* @typedef {"idle" | "asking" | "loading" | "shown" | "failed" | "lost"} ReviewState
|
||||
* @typedef {{ state: ReviewState, review: any | null, guide: any | null, reading: any[], walked: string[],
|
||||
* session?: any, error?: string, problem?: string }} ReviewShown
|
||||
* @typedef {(frame: Frame) => boolean} Send
|
||||
*/
|
||||
|
||||
/** @type {ReviewShown} */
|
||||
const NOTHING = { state: "idle", review: null, guide: null, reading: [], walked: [] };
|
||||
|
||||
/** Nothing asked and no chapter open. */
|
||||
export function createReview() {
|
||||
const shown = signal(NOTHING);
|
||||
const open = signal(/** @type {string | null} */ (null));
|
||||
/** @type {Asked} */
|
||||
const asked = { id: "", load: "", send: null, edits: new Set() };
|
||||
/** @param {Send} send */
|
||||
const ask = (send) => (shown.value = { ...shown.value, state: askOpen(asked, send) ? "asking" : "lost" });
|
||||
/** @param {Send} send */
|
||||
const load = (send) => (shown.value = { ...shown.value, state: loadChanges(asked, send) ? "loading" : "lost", error: undefined });
|
||||
/** @param {Frame} frame */
|
||||
const apply = (frame) => {
|
||||
const { next, again } = applyReview(shown.value, frame, asked);
|
||||
shown.value = next;
|
||||
if (!next.review?.chapters?.some((/** @type {any} */ it) => it.id === open.value)) open.value = null;
|
||||
if (again && asked.send) ask(asked.send);
|
||||
};
|
||||
const walk = (/** @type {string} */ chapter, /** @type {Send} */ send) => (shown.value = walked(shown.value, chapter, send));
|
||||
const edit = (/** @type {Send} */ send, /** @type {object | null} */ change) => (shown.value = edited(shown.value, asked, send, change));
|
||||
return { shown, open, ask, load, apply, walk, edit, pick: (/** @type {string} */ id) => (open.value = id), close: () => (open.value = null) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends `change` to the open review, remembering the request so a refusal of it is said. The
|
||||
* session the desk answers with arrives through `apply`, as everyone's changes do.
|
||||
* @param {ReviewShown} shown @param {Asked} asked @param {Send} send @param {object | null} change @returns {ReviewShown}
|
||||
*/
|
||||
function edited(shown, asked, send, change) {
|
||||
if (!shown.review || !change) return shown;
|
||||
const request_id = requestId("edit");
|
||||
asked.edits.add(request_id);
|
||||
const sent = send({ kind: "edit_review", content: { request_id, review_id: shown.review.id, ...change } });
|
||||
return { ...shown, problem: sent ? undefined : "Connection lost. Try again once it's back." };
|
||||
}
|
||||
|
||||
/**
|
||||
* The requests the next answers must carry, and the send to ask again with when the open review
|
||||
* changes. @typedef {{ id: string, load: string, send: Send | null, edits: Set<string> }} Asked
|
||||
*/
|
||||
|
||||
/** Asks for the open review. @param {Asked} asked @param {Send} send */
|
||||
function askOpen(asked, send) {
|
||||
Object.assign(asked, { id: requestId("show"), send });
|
||||
return send({ kind: "show_open_review", content: { request_id: asked.id } });
|
||||
}
|
||||
|
||||
/** Loads a review of the working changes, which becomes the open one. @param {Asked} asked @param {Send} send */
|
||||
function loadChanges(asked, send) {
|
||||
Object.assign(asked, { load: requestId("load"), send });
|
||||
return send({ kind: "load_guided_review", content: { request_id: asked.load, target: { kind: "working_tree" } } });
|
||||
}
|
||||
|
||||
/** An id no other phone will send, so each answers only its asker. @param {string} what */
|
||||
function requestId(what) {
|
||||
return `phone-review:${what}:${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What `frame` does to the tab, and whether to ask for the open review again because it changed.
|
||||
* @param {ReviewShown} shown @param {Frame} frame @param {{ id: string, load: string, edits?: Set<string> }} asked
|
||||
* @returns {{ next: ReviewShown, again: boolean }}
|
||||
*/
|
||||
export function applyReview(shown, { kind, content }, asked) {
|
||||
const waiting = shown.state === "asking" || shown.state === "loading";
|
||||
if (kind === "ready") return { next: waiting ? { ...shown, state: "lost" } : shown, again: false };
|
||||
if (kind === "open_review_shown" && content?.request_id === asked.id) return { next: answered(content), again: false };
|
||||
if (kind === "review_session_saved" && shown.review && content?.session?.id === shown.review.id) {
|
||||
return { next: withSession(shown, content.session), again: false };
|
||||
}
|
||||
if (kind === "review_session_save_failed" && asked.edits?.has(content?.request_id)) {
|
||||
return { next: { ...shown, problem: content.message }, again: false };
|
||||
}
|
||||
if (kind === "guided_review_failed" && content?.request_id === asked.load) {
|
||||
return { next: { ...shown, state: "failed", error: content.error?.message ?? "The review couldn't be loaded." }, again: false };
|
||||
}
|
||||
return { next: shown, again: kind === "guided_review_loaded" || kind === "guided_review_guide_updated" };
|
||||
}
|
||||
|
||||
/** The tab after an answer: the review, its guide without lines, and the reading it came with. @param {any} content @returns {ReviewShown} */
|
||||
function answered({ review, session, reading }) {
|
||||
if (!review) return { ...NOTHING, state: "shown" };
|
||||
return withSession({ state: "shown", review, guide: withoutLines(review), reading: reading ?? [], walked: [] }, session);
|
||||
}
|
||||
|
||||
/** The tab holding `session`, its comments and the chapters walked in it. @param {ReviewShown} shown @param {any} session @returns {ReviewShown} */
|
||||
function withSession(shown, session) {
|
||||
return { ...shown, session, walked: session?.progress?.walked_chapter_ids ?? shown.walked };
|
||||
}
|
||||
|
||||
/** `review` with every hunk's lines left out, which is all the guide's piece needs. @param {any} review */
|
||||
export function withoutLines(review) {
|
||||
const files = review.files.map((/** @type {any} */ file) => ({ ...file, hunks: file.hunks.map((/** @type {any} */ hunk) => ({ ...hunk, lines: [] })) }));
|
||||
return { ...review, files };
|
||||
}
|
||||
|
||||
/**
|
||||
* `chapter` marked walked, or unmarked if it was, with the session told every chapter walked now.
|
||||
* @param {ReviewShown} shown @param {string} chapter @param {Send} send @returns {ReviewShown}
|
||||
*/
|
||||
function walked(shown, chapter, send) {
|
||||
if (!shown.review) return shown;
|
||||
const was = shown.walked.includes(chapter);
|
||||
const walked = was ? shown.walked.filter((id) => id !== chapter) : [...shown.walked, chapter];
|
||||
send({ kind: "record_review_progress", content: { review_id: shown.review.id, walked_chapter_ids: walked } });
|
||||
return { ...shown, walked };
|
||||
}
|
||||
|
||||
/** The guide's piece. @param {ReviewShown} shown */
|
||||
export function guidePiece({ guide, reading, walked }) {
|
||||
return { kind: /** @type {const} */ ("review_guide"), review: guide, reading, walked };
|
||||
}
|
||||
|
||||
/**
|
||||
* Chapter `id`'s piece: the chapter, and only the files it names holding only its hunks, so the
|
||||
* request stays the size of the chapter rather than the review. @param {ReviewShown} shown @param {string} id
|
||||
*/
|
||||
export function chapterPiece({ review, reading, walked, session }, id) {
|
||||
const index = review.chapters.findIndex((/** @type {any} */ chapter) => chapter.id === id);
|
||||
const chapter = review.chapters[index];
|
||||
const named = new Set(chapter.items.map((/** @type {any} */ item) => item.id));
|
||||
const files = review.files
|
||||
.map((/** @type {any} */ file) => ({ ...file, hunks: file.hunks.filter((/** @type {any} */ hunk) => named.has(hunk.id)) }))
|
||||
.filter((/** @type {any} */ file) => named.has(file.id) || file.hunks.length);
|
||||
const place = { number: index + 1, total: review.chapters.length, walked: walked.includes(id) };
|
||||
const read = reading.find((/** @type {any} */ it) => it.chapter_id === id) ?? null;
|
||||
const findings = session?.findings ?? [];
|
||||
return { kind: /** @type {const} */ ("review_chapter"), chapter, files, place, reading: read, findings };
|
||||
}
|
||||
|
||||
/** The chapter after `id`, if there is one. @param {any} review @param {string} id @returns {string | null} */
|
||||
export function nextChapter(review, id) {
|
||||
const index = review.chapters.findIndex((/** @type {any} */ chapter) => chapter.id === id);
|
||||
return review.chapters[index + 1]?.id ?? null;
|
||||
}
|
||||
|
||||
/** What the review is of, in a few words. @param {any} target */
|
||||
export function targetName(target) {
|
||||
switch (target?.kind) {
|
||||
case "working_tree": return "Working changes";
|
||||
case "pull_request": return `Pull request #${target.number}`;
|
||||
case "commit": return `Commit ${String(target.oid).slice(0, 8)}`;
|
||||
case "base": return `Changes since ${target.reference}`;
|
||||
default: return "Review";
|
||||
}
|
||||
}
|
||||
252
crates/luxe-remote/app/session.js
Normal file
252
crates/luxe-remote/app/session.js
Normal file
@@ -0,0 +1,252 @@
|
||||
// @ts-check
|
||||
// One session: its transcript, live over the socket, and how the connection stands.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { useEffect, useMemo, useRef } from "preact/hooks";
|
||||
import { commandAction, runCommand } from "./commands.js";
|
||||
import { connect } from "./connection.js";
|
||||
import { html } from "./html.js";
|
||||
import { Composer } from "./composer.js";
|
||||
import { DetailsSheet } from "./details.js";
|
||||
import { DiffSheet, Dock, DockToggle } from "./dock.js";
|
||||
import { createFiles } from "./files.js";
|
||||
import { createGithub } from "./github.js";
|
||||
import { createReview } from "./review.js";
|
||||
import { Transcript } from "./items.js";
|
||||
import { WIDE, dockVisible, phoneDock, theDock, useWide } from "./layout.js";
|
||||
import { createListings } from "./mentions.js";
|
||||
import { createModels } from "./models.js";
|
||||
import { createPending } from "./pending.js";
|
||||
import { PairWithLink } from "./pairing.js";
|
||||
import { PanelButton, ProjectName, ProjectPanel, createPanel } from "./panel.js";
|
||||
import { PromptCard } from "./prompt.js";
|
||||
import { folderName } from "./sessions.js";
|
||||
import { StatusLine, createStatus } from "./status.js";
|
||||
import { createTranscript } from "./transcript.js";
|
||||
import { createWorkspace, diffRequest } from "./workspace.js";
|
||||
|
||||
const PROTOCOL_VERSION = 2;
|
||||
|
||||
/** @import { Frame, Status } from "./connection.js" */
|
||||
/** @typedef {ReturnType<typeof createView>} View */
|
||||
|
||||
/** @param {{ sessionId: string }} props */
|
||||
export function SessionView({ sessionId }) {
|
||||
const view = useMemo(createView, [sessionId]);
|
||||
const transcriptRef = useRef(/** @type {HTMLElement | null} */ (null));
|
||||
useLink(sessionId, view);
|
||||
usePinnedScroll(transcriptRef);
|
||||
return html`
|
||||
<${Header} view=${view} sessionId=${sessionId} />
|
||||
<main ref=${transcriptRef}>
|
||||
<${Transcript} items=${view.transcript.items.value} />
|
||||
<${Ending} status=${view.status.value} problem=${view.problem.value} />
|
||||
</main>
|
||||
<${Footer} view=${view} />
|
||||
<${WorkspaceViews} view=${view} />
|
||||
`;
|
||||
}
|
||||
|
||||
/** @param {{ view: View, sessionId: string }} props */
|
||||
function Header({ view, sessionId }) {
|
||||
const dock = theDock();
|
||||
const wide = useWide();
|
||||
return html`<header class="bar">
|
||||
<a class="back" href="#/" aria-label="All sessions">‹</a>
|
||||
<span class="title">${view.title.value ? html`<${ProjectName} project=${projectOf(view)} />` : sessionId.slice(0, 8)}</span>
|
||||
${wide ? html`<${DockToggle} shown=${dockVisible(dock.mode.value, wide)} toggle=${() => dock.apply("toggle")} />` : null}
|
||||
<${PanelButton} open=${() => view.panel.open()} />
|
||||
<${Connection} status=${view.status.value} />
|
||||
</header>`;
|
||||
}
|
||||
|
||||
/** The dock, the diff a tap in it opens, the project panel and the status line's details. @param {{ view: View }} props */
|
||||
function WorkspaceViews({ view }) {
|
||||
const { workspace } = view;
|
||||
const open = openDiff(view);
|
||||
const wide = useWide();
|
||||
return html`
|
||||
<${Dock} todos=${workspace.todos.value} changes=${workspace.changes.value} shown=${wide && dockVisible(theDock().mode.value, wide)} open=${open} />
|
||||
<${DiffSheet} open=${workspace.diff.value} close=${workspace.close} retry=${() => workspace.diff.value && open(workspace.diff.value.path)}
|
||||
ask=${(/** @type {string} */ words) => mentionIn(view, words)} />
|
||||
<${ProjectPanel} panel=${view.panel} hooks=${panelHooks(view)} />
|
||||
${view.detailsShown.value ? html`<${DetailsSheet} facts=${view.statusLine.facts.value} mode=${view.statusLine.mode.value}
|
||||
listing=${view.models.listing.value} send=${(/** @type {Frame} */ frame) => view.send(frame)} close=${() => (view.detailsShown.value = false)} />` : null}
|
||||
`;
|
||||
}
|
||||
|
||||
/** Asks for a changed file's diff, which opens over the page. @param {View} view */
|
||||
function openDiff(view) {
|
||||
return (/** @type {string} */ path) => {
|
||||
const request = diffRequest(path);
|
||||
view.workspace.opened(request);
|
||||
if (!view.send(request)) view.workspace.lost();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `/dock`'s verb: on a phone, where the dock is the panel's Dock tab, it opens or closes the
|
||||
* panel; the side and mode, and every verb on a wide screen, go to the dock.
|
||||
* @param {View} view @param {string} verb
|
||||
*/
|
||||
function workDock(view, verb) {
|
||||
const onPhone = matchMedia(WIDE).matches ? null : phoneDock(verb, view.panel.tab.value);
|
||||
if (onPhone === "open") return view.panel.open("dock");
|
||||
if (onPhone === "close") return view.panel.close();
|
||||
theDock().apply(verb);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts `words` in the draft and clears every sheet over the composer, where the question about
|
||||
* them is typed next. @param {View} view @param {string} words
|
||||
*/
|
||||
function mentionIn(view, words) {
|
||||
view.mentioned.value = words;
|
||||
view.files.close();
|
||||
view.github.close();
|
||||
view.review.close();
|
||||
view.panel.close();
|
||||
view.workspace.close();
|
||||
}
|
||||
|
||||
/** What the project panel works the session with. @param {View} view @returns {import("./panel.js").PanelHooks} */
|
||||
function panelHooks(view) {
|
||||
/** @param {string} words */
|
||||
const mention = (words) => mentionIn(view, words);
|
||||
const { listings, files, github, review, workspace } = view;
|
||||
const project = projectOf(view);
|
||||
const dock = { changes: workspace.changes.value, todos: workspace.todos.value, openDiff: openDiff(view), diffOpen: Boolean(workspace.diff.value) };
|
||||
return { send: (frame) => view.send(frame), listings, files, github, review, mention, ...dock, project };
|
||||
}
|
||||
|
||||
/** The session's folder, its branch and whether the tree has changes. @param {View} view @returns {import("./panel.js").Project} */
|
||||
function projectOf(view) {
|
||||
const identity = view.workspace.project.value;
|
||||
return { name: view.title.value, branch: identity?.git_branch ?? null, dirty: Boolean(identity?.git_dirty) };
|
||||
}
|
||||
|
||||
/** Opens the status line's details, asking for the models afresh. @param {View} view */
|
||||
function openDetails(view) {
|
||||
view.models.ask(view.send);
|
||||
view.detailsShown.value = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The socket for as long as the view shows this session; `view.send` writes to it.
|
||||
* @param {string} sessionId @param {View} view
|
||||
*/
|
||||
function useLink(sessionId, view) {
|
||||
useEffect(() => {
|
||||
const link = connect(sessionId, { onFrame: view.apply, onStatus: (status) => (view.status.value = status) });
|
||||
view.send = link.send;
|
||||
return () => link.close();
|
||||
}, [sessionId]);
|
||||
}
|
||||
|
||||
/** What the project panel's tabs keep: the files, GitHub and the review, each with its open pane. */
|
||||
function panes() {
|
||||
return { files: createFiles(), github: createGithub(), review: createReview() };
|
||||
}
|
||||
|
||||
function createView() {
|
||||
const view = {
|
||||
transcript: createTranscript(),
|
||||
pending: createPending(),
|
||||
statusLine: createStatus(),
|
||||
models: createModels(),
|
||||
listings: createListings(),
|
||||
workspace: createWorkspace(),
|
||||
...panes(),
|
||||
panel: createPanel(),
|
||||
mentioned: signal(/** @type {string | null} */ (null)),
|
||||
detailsShown: signal(false),
|
||||
title: signal(""),
|
||||
status: signal(/** @type {Status} */ ("connecting")),
|
||||
problem: signal(""),
|
||||
/** @type {(frame: Frame) => boolean} */ send: () => false,
|
||||
};
|
||||
return Object.assign(view, { apply: (/** @type {Frame} */ frame) => applyFrame(view, frame) });
|
||||
}
|
||||
|
||||
/** What you answer and write with, kept at the foot of the screen. @param {{ view: View }} props */
|
||||
function Footer({ view }) {
|
||||
const { pending } = view;
|
||||
/** @param {Frame} frame */
|
||||
const send = (frame) => view.send(frame);
|
||||
const hooks = { send, details: () => openDetails(view), dock: (/** @type {string} */ verb) => workDock(view, verb) };
|
||||
/** @param {string} text */
|
||||
const run = (text) => runCommand(commandAction(text, view.statusLine.mode.value), hooks);
|
||||
if (view.status.value === "ended" || view.status.value === "unpaired") return null;
|
||||
return html`<footer class="controls">
|
||||
<${PromptCard} prompts=${pending.prompts.value} send=${send} />
|
||||
<${Composer} busy=${view.transcript.busy.value} live=${view.status.value === "live"} steering=${pending.steering.value}
|
||||
listings=${view.listings} send=${send} run=${run} onSteered=${pending.steered} onDropped=${pending.dropSteering}
|
||||
mention=${view.mentioned.value} taken=${() => (view.mentioned.value = null)} />
|
||||
<${StatusLine} facts=${view.statusLine.facts.value} mode=${view.statusLine.mode.value} send=${send}
|
||||
details=${() => openDetails(view)} />
|
||||
</footer>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Omit<View, "apply">} view The view being made, which `apply` is added to
|
||||
* @param {Frame} frame
|
||||
*/
|
||||
function applyFrame(view, frame) {
|
||||
view.pending.apply(frame);
|
||||
view.statusLine.apply(frame);
|
||||
view.models.apply(frame);
|
||||
view.listings.apply(frame);
|
||||
view.workspace.apply(frame);
|
||||
view.files.apply(frame);
|
||||
view.github.apply(frame);
|
||||
view.review.apply(frame);
|
||||
if (frame.kind !== "ready") return view.transcript.apply(frame);
|
||||
view.title.value = folderName(frame.content.cwd);
|
||||
if (frame.content.protocol_version !== PROTOCOL_VERSION) {
|
||||
view.problem.value = `Protocol mismatch: Luxe uses ${frame.content.protocol_version}, this app ${PROTOCOL_VERSION}.`;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {{ status: string }} props */
|
||||
function Connection({ status }) {
|
||||
/** @type {Record<string, string>} */
|
||||
const words = { connecting: "connecting", live: "live", reconnecting: "reconnecting", ended: "ended", unpaired: "unpaired" };
|
||||
return html`<span class=${`connection ${status}`}>${words[status] ?? status}</span>`;
|
||||
}
|
||||
|
||||
/** @param {{ status: string, problem: string }} props */
|
||||
function Ending({ status, problem }) {
|
||||
if (problem) return html`<p class="problem">${problem}</p>`;
|
||||
if (status === "ended") return html`<p class="notice">Session ended.</p>`;
|
||||
if (status !== "unpaired") return null;
|
||||
return html`<p class="problem">Device unpaired.</p><${PairWithLink} />`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow new output while the reader is at the bottom; leave them be once they scroll up. Only
|
||||
* scrolling up lets go: items drawn late grow the page under a scroll to the bottom, which would
|
||||
* otherwise read as the reader having left it.
|
||||
* @param {{ current: HTMLElement | null }} ref
|
||||
*/
|
||||
function usePinnedScroll(ref) {
|
||||
useEffect(() => (ref.current ? followGrowth(ref.current) : undefined), []);
|
||||
}
|
||||
|
||||
/** Keeps the page at the bottom as `transcript` grows, until stopped. @param {HTMLElement} transcript */
|
||||
function followGrowth(transcript) {
|
||||
let pinned = true;
|
||||
let lastY = scrollY;
|
||||
const page = document.documentElement;
|
||||
const onScroll = () => {
|
||||
if (innerHeight + scrollY >= page.scrollHeight - 48) pinned = true;
|
||||
else if (scrollY < lastY) pinned = false;
|
||||
lastY = scrollY;
|
||||
};
|
||||
const follow = new ResizeObserver(() => pinned && scrollTo(0, page.scrollHeight));
|
||||
addEventListener("scroll", onScroll, { passive: true });
|
||||
follow.observe(transcript);
|
||||
return () => {
|
||||
removeEventListener("scroll", onScroll);
|
||||
follow.disconnect();
|
||||
};
|
||||
}
|
||||
98
crates/luxe-remote/app/sessions.js
Normal file
98
crates/luxe-remote/app/sessions.js
Normal file
@@ -0,0 +1,98 @@
|
||||
// @ts-check
|
||||
// The sessions running on your computer, kept current while the list is on screen.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { useEffect } from "preact/hooks";
|
||||
import { offered, refreshFolders } from "./folders.js";
|
||||
import { html } from "./html.js";
|
||||
import { NotificationSwitch, refreshNotifications } from "./notifications.js";
|
||||
import { PairWithLink } from "./pairing.js";
|
||||
import { loadWordmark, Wordmark } from "./wordmark.js";
|
||||
|
||||
/**
|
||||
* A running session, as `GET /api/sessions` lists it.
|
||||
* @typedef {{ session_id: string, cwd: string, pid: number, luxe_version: string }} Session
|
||||
*/
|
||||
|
||||
const REFRESH_MS = 5000;
|
||||
|
||||
/** @type {import("@preact/signals").Signal<Session[] | null>} */
|
||||
const sessions = signal(null);
|
||||
const problem = signal("");
|
||||
// 401 is the bridge's answer to a device it doesn't know; the tailnet login itself is never
|
||||
// missing behind Serve, so the way in to offer is pairing
|
||||
const unpaired = signal(false);
|
||||
|
||||
async function refresh() {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
try {
|
||||
const response = await fetch("/api/sessions");
|
||||
unpaired.value = response.status === 401;
|
||||
if (!response.ok) {
|
||||
problem.value = await response.text();
|
||||
return;
|
||||
}
|
||||
problem.value = "";
|
||||
sessions.value = await response.json();
|
||||
await refreshFolders();
|
||||
} catch (error) {
|
||||
problem.value = `couldn't reach your computer: ${error}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The computer this app reaches, as the bridge names the page for it, or nothing when it couldn't
|
||||
* ask Tailscale. One phone can have an app for each of several computers.
|
||||
* @param {Pick<Document, "querySelector">} page @returns {string}
|
||||
*/
|
||||
export function machineName(page) {
|
||||
return page.querySelector('meta[name="luxe-machine"]')?.getAttribute("content") ?? "";
|
||||
}
|
||||
|
||||
/** @param {{ name: string }} props */
|
||||
function Machine({ name }) {
|
||||
return name ? html`<span class="machine">${name}</span>` : null;
|
||||
}
|
||||
|
||||
export function SessionList() {
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
refreshNotifications().catch((error) => console.warn("couldn't read the notifications", error));
|
||||
loadWordmark().catch((error) => console.warn("couldn't draw the wordmark", error));
|
||||
const timer = setInterval(refresh, REFRESH_MS);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
return html`
|
||||
<header class="bar"><${Wordmark} /><${Machine} name=${machineName(document)} />${offered.value && !unpaired.value ? html`<a class="new" href="#/new">+ New</a>` : null}</header>
|
||||
<main>
|
||||
${problem.value ? html`<p class="problem">${problem.value}</p>` : null}
|
||||
${unpaired.value ? html`<${PairWithLink} />` : html`
|
||||
<h2>Running</h2>
|
||||
<${Rows} sessions=${sessions.value} />
|
||||
<${NotificationSwitch} />`}
|
||||
</main>
|
||||
`;
|
||||
}
|
||||
|
||||
/** @param {{ sessions: Session[] | null }} props */
|
||||
function Rows({ sessions }) {
|
||||
if (!sessions) return html`<p class="dim">Loading sessions…</p>`;
|
||||
if (!sessions.length) return html`<p class="dim">No sessions running.</p>`;
|
||||
return html`<ul class="sessions">
|
||||
${sessions.map((session) => html`<li key=${session.session_id}><${Row} session=${session} /></li>`)}
|
||||
</ul>`;
|
||||
}
|
||||
|
||||
/** @param {{ session: Session }} props */
|
||||
function Row({ session }) {
|
||||
return html`<a class="session" href=${`#/session/${encodeURIComponent(session.session_id)}`}>
|
||||
<span class="name">${folderName(session.cwd)}</span>
|
||||
<span class="dim path">${session.cwd}</span>
|
||||
<span class="dim">${session.session_id.slice(0, 8)} · Luxe ${session.luxe_version}</span>
|
||||
</a>`;
|
||||
}
|
||||
|
||||
/** The last part of a path, from either kind of separator. @param {string} path */
|
||||
export function folderName(path) {
|
||||
return path.split(/[\\/]/).filter(Boolean).pop() ?? path;
|
||||
}
|
||||
71
crates/luxe-remote/app/status.js
Normal file
71
crates/luxe-remote/app/status.js
Normal file
@@ -0,0 +1,71 @@
|
||||
// @ts-check
|
||||
// The status line under the composer: the mode, which a tap switches, then the bar's right-hand
|
||||
// facts (context, cost, thinking, model) as the host words them, so they read as the TUI's do. A
|
||||
// phone keeps it to one row and leaves the cost to the details sheet a tap on the facts opens.
|
||||
|
||||
import { batch, signal } from "@preact/signals";
|
||||
import { MODES } from "./details.js";
|
||||
import { html } from "./html.js";
|
||||
import { useRendered } from "./render.js";
|
||||
|
||||
/** @import { Signal } from "@preact/signals" */
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/** @typedef {{ facts: Signal<Record<string, any>>, mode: Signal<string> }} State */
|
||||
|
||||
/** Nothing reported yet, and the function that folds frames into what is. */
|
||||
export function createStatus() {
|
||||
/** @type {State} */
|
||||
const state = { facts: signal({}), mode: signal("") };
|
||||
/** @param {Frame} frame */
|
||||
const fold = (frame) => batch(() => apply(state, frame));
|
||||
return { facts: state.facts, mode: state.mode, apply: fold };
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Frame} frame */
|
||||
function apply(state, { kind, content }) {
|
||||
switch (kind) {
|
||||
case "state_changed":
|
||||
state.mode.value = content.mode ?? "";
|
||||
return update(state, { model: content.model, thinking: content.thinking });
|
||||
case "context_usage": return update(state, { context: content });
|
||||
case "plan_usage": return update(state, { plan: content });
|
||||
// the total is all the line shows; the breakdown would only make every request longer
|
||||
case "session_usage": return update(state, { session: { total: content.total } });
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Record<string, any>} changed */
|
||||
function update(state, changed) {
|
||||
state.facts.value = { ...state.facts.value, ...changed };
|
||||
}
|
||||
|
||||
/** The frame that switches from `mode` to the next one. @param {string} mode @returns {Frame} */
|
||||
export function nextModeFrame(mode) {
|
||||
const next = MODES[(MODES.indexOf(mode) + 1) % MODES.length];
|
||||
return { kind: "set_mode", content: next };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ facts: Record<string, any>, mode: string, send: (frame: Frame) => boolean,
|
||||
* details: () => void }} props
|
||||
*/
|
||||
export function StatusLine({ facts, mode, send, details }) {
|
||||
const rendered = useRendered({ kind: "status", ...facts }, true);
|
||||
return html`<div class="status-line">
|
||||
${mode ? html`<${ModeButton} mode=${mode} send=${send} />` : null}
|
||||
<button type="button" class="segments" aria-label="Session details" onClick=${details}
|
||||
dangerouslySetInnerHTML=${{ __html: rendered ?? "" }}></button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode behind the mark the TUI's composer title gives it, drawn by the host; the bare name
|
||||
* until it is. A tap switches to the next mode.
|
||||
* @param {{ mode: string, send: (frame: Frame) => boolean }} props
|
||||
*/
|
||||
function ModeButton({ mode, send }) {
|
||||
const rendered = useRendered({ kind: "mode_name", mode }, true);
|
||||
const label = rendered ? { dangerouslySetInnerHTML: { __html: rendered } } : { children: mode };
|
||||
return html`<button type="button" class=${`mode mode-${mode}`} aria-label=${`Mode: ${mode}, tap to switch`}
|
||||
onClick=${() => send(nextModeFrame(mode))} ...${label} />`;
|
||||
}
|
||||
479
crates/luxe-remote/app/style.css
Normal file
479
crates/luxe-remote/app/style.css
Normal file
@@ -0,0 +1,479 @@
|
||||
/* The app is set like the terminal: one monospace face, one line height, widths in `ch`. Colors
|
||||
come from `/theme.css`, the active theme; each fallback is Luxe's own, for a theme whose token
|
||||
is the terminal's default color, which a page can't know. Rendered text is `markdown.css`. */
|
||||
|
||||
@font-face {
|
||||
font-family: "Luxe Mono";
|
||||
src: url("fonts/jetbrains-mono-regular.woff2") format("woff2");
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Luxe Mono";
|
||||
src: url("fonts/jetbrains-mono-bold.woff2") format("woff2");
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Luxe Mono";
|
||||
src: url("fonts/jetbrains-mono-italic.woff2") format("woff2");
|
||||
font-style: italic;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
/* A separate family, so the browser takes from it only what the first face lacks */
|
||||
@font-face {
|
||||
font-family: "Luxe Mono Marks";
|
||||
src: url("fonts/adwaita-mono-regular.woff2") format("woff2");
|
||||
font-weight: 400;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Luxe Mono Marks";
|
||||
src: url("fonts/adwaita-mono-bold.woff2") format("woff2");
|
||||
font-weight: 700;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
:root {
|
||||
--cell: 1.4;
|
||||
/* the terminal's rounded box corner, an arc half a cell wide (luxe-tui's PANEL_BORDER_TYPE) */
|
||||
--corner: 0.5ch;
|
||||
/* the least a finger is given to hit, Apple's 44 points */
|
||||
--tap: 2.4lh;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0 env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
|
||||
background: var(--luxe-background, #12100e);
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
font: 13px / var(--cell) "Luxe Mono", "Luxe Mono Marks", ui-monospace, monospace;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: none;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
text-align: start;
|
||||
}
|
||||
|
||||
/* Buttons keep Luxe's square shape: no browser's rounded tap blob or focus ring, which hug a lone
|
||||
icon into a circle. A press or a keyboard's focus marks the button's own box instead */
|
||||
button,
|
||||
a {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
:is(button, a):focus-visible {
|
||||
outline: 1px solid var(--luxe-accent, #ddc084);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
|
||||
/* An icon on its own is a square a finger can hit, drawn into the bar without making it taller.
|
||||
A press fills a smaller square inside it, so the fill stays within the bar */
|
||||
:is(.close, .panel-button, .dock-toggle) {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
box-sizing: border-box;
|
||||
inline-size: var(--tap);
|
||||
block-size: var(--tap);
|
||||
margin-block: calc((1lh - var(--tap)) / 2);
|
||||
padding: 0.35lh;
|
||||
background-clip: content-box;
|
||||
border-radius: var(--corner);
|
||||
}
|
||||
|
||||
:is(.close, .panel-button, .dock-toggle):active {
|
||||
background-color: var(--luxe-selected-bg, #2c2925);
|
||||
}
|
||||
|
||||
pre,
|
||||
code {
|
||||
font: inherit;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* At least a screen tall, so the composer sits at the foot of a session with nothing in it yet */
|
||||
#app {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: calc(100dvh - env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
main {
|
||||
flex: 1;
|
||||
padding: 1lh 1ch;
|
||||
}
|
||||
|
||||
.bar {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
/* over the phone's dock page, whose button it holds */
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
gap: 1ch;
|
||||
align-items: baseline;
|
||||
padding: calc(env(safe-area-inset-top) + 0.5lh) 1ch 0.5lh;
|
||||
background: var(--luxe-background, #12100e);
|
||||
border-bottom: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
}
|
||||
|
||||
.bar .title {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* which computer this app reaches, beside the wordmark: one phone can have an app for each */
|
||||
.bar .wordmark:has(+ .machine) {
|
||||
margin-inline-end: 0;
|
||||
}
|
||||
|
||||
.bar .machine {
|
||||
align-self: center;
|
||||
margin-inline: 1ch auto;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.back {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
padding-inline-end: 1ch;
|
||||
}
|
||||
|
||||
.bar .new {
|
||||
align-self: center;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
padding: 0.25lh 1ch;
|
||||
border: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
border-radius: var(--corner);
|
||||
}
|
||||
|
||||
/* The logotype, lit like the terminal's: each letter swings between the accent and the accent cut
|
||||
back toward the canvas by the depth the generated file carries */
|
||||
.wordmark {
|
||||
--wordmark-lit: var(--luxe-accent, #ddc084);
|
||||
--wordmark-dim: color-mix(
|
||||
in srgb,
|
||||
var(--luxe-background, #12100e) calc(var(--drift-depth) * 100%),
|
||||
var(--wordmark-lit)
|
||||
);
|
||||
align-self: center;
|
||||
height: 2lh;
|
||||
margin-inline-end: auto;
|
||||
}
|
||||
|
||||
/* The terminal's `DRIFT_TICKS` of its 33ms tick. Each letter's `--phase` is a negative share of
|
||||
it, so every letter is mid-swing on the first frame rather than the whole mark pulsing once */
|
||||
.wordmark path {
|
||||
fill: var(--wordmark-lit);
|
||||
animation: wordmark-drift 6.996s linear infinite;
|
||||
animation-delay: calc(var(--phase, 0) * 6.996s);
|
||||
}
|
||||
|
||||
/* Held where it would be, each letter at its own point of the swing */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.wordmark path {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
}
|
||||
|
||||
/* The terminal's raised cosine, sampled every eighth of a turn as the website does: an easing curve
|
||||
reads as letters taking turns fading rather than one light moving over metal */
|
||||
@keyframes wordmark-drift {
|
||||
0%,
|
||||
100% {
|
||||
fill: var(--wordmark-lit);
|
||||
}
|
||||
12.5%,
|
||||
87.5% {
|
||||
fill: color-mix(in oklab, var(--wordmark-dim) 15%, var(--wordmark-lit));
|
||||
}
|
||||
25%,
|
||||
75% {
|
||||
fill: color-mix(in oklab, var(--wordmark-dim) 50%, var(--wordmark-lit));
|
||||
}
|
||||
37.5%,
|
||||
62.5% {
|
||||
fill: color-mix(in oklab, var(--wordmark-dim) 85%, var(--wordmark-lit));
|
||||
}
|
||||
50% {
|
||||
fill: var(--wordmark-dim);
|
||||
}
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.dim {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
/* The TUI's heading badge: the word cut into a slab two cells in and one after, then three cells
|
||||
stepping a quarter of the way each into the canvas. The depth is the section's own, by the TUI's
|
||||
stops: PROJECT and MODEL the accent itself with the canvas as ink, the work in flight (PLAN,
|
||||
FILES) receded 40% into the canvas and SESSION 70%, both inked in body text. An idle badge is
|
||||
a switch's face that isn't showing. A flat statusline style draws bold accent words, as the
|
||||
TUI's rail does */
|
||||
.badge {
|
||||
--canvas: var(--luxe-background, #12100e);
|
||||
--slab: var(--luxe-accent, #ddc084);
|
||||
display: inline-block;
|
||||
padding: 0 4ch 0 2ch;
|
||||
font-weight: bold;
|
||||
text-transform: uppercase;
|
||||
color: var(--canvas);
|
||||
background: linear-gradient(to right,
|
||||
var(--slab) calc(100% - 3ch),
|
||||
color-mix(in srgb, var(--canvas) 25%, var(--slab)) calc(100% - 3ch) calc(100% - 2ch),
|
||||
color-mix(in srgb, var(--canvas) 50%, var(--slab)) calc(100% - 2ch) calc(100% - 1ch),
|
||||
color-mix(in srgb, var(--canvas) 75%, var(--slab)) calc(100% - 1ch));
|
||||
}
|
||||
|
||||
.badge.raised,
|
||||
.badge.recessed {
|
||||
color: var(--luxe-text, #e4dfd6);
|
||||
}
|
||||
|
||||
.badge.raised {
|
||||
--slab: color-mix(in srgb, var(--luxe-accent, #ddc084) 60%, var(--canvas));
|
||||
}
|
||||
|
||||
.badge.recessed {
|
||||
--slab: color-mix(in srgb, var(--luxe-accent, #ddc084) 30%, var(--canvas));
|
||||
}
|
||||
|
||||
.badge.idle {
|
||||
--slab: color-mix(in srgb, var(--luxe-muted, #97938c) 22%, var(--canvas));
|
||||
font-weight: normal;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
:root[data-headings="flat"] .badge {
|
||||
padding: 0;
|
||||
background: none;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
:root[data-headings="flat"] .badge.idle {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.problem {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
.notice {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
/* The session list */
|
||||
|
||||
.sessions {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.session {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0.5lh 1ch;
|
||||
margin-block-end: 1lh;
|
||||
background: var(--luxe-tool-call-bg, #201e1a);
|
||||
}
|
||||
|
||||
.session .name {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.session .path {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.folder {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.folder:disabled {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 1lh 0 0.5lh;
|
||||
font-size: inherit;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
/* How the connection stands; the word says it, the color only helps */
|
||||
|
||||
.connection {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.connection::before {
|
||||
content: "● ";
|
||||
}
|
||||
|
||||
.connection.live {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
.connection.reconnecting {
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
}
|
||||
|
||||
.connection.unpaired {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
/* The transcript: one blank row between items, as in the terminal */
|
||||
|
||||
.item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin-block-end: 1lh;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 3lh;
|
||||
}
|
||||
|
||||
/* A long session's history waits above the latest items until it's asked for */
|
||||
.earlier {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: var(--tap);
|
||||
margin-block-end: 1lh;
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
padding-inline: 1ch;
|
||||
}
|
||||
|
||||
/* Your words on a band; a brief Luxe wrote to the agent, as one muted line */
|
||||
.user-message .words,
|
||||
.user-message.plain {
|
||||
display: block;
|
||||
margin: 0;
|
||||
padding: 1lh 1ch;
|
||||
background: var(--luxe-user-msg-bg, #201e1a);
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.user-message .words + .words {
|
||||
margin-block-start: 1lh;
|
||||
}
|
||||
|
||||
.user-message .brief,
|
||||
.user-message .attached {
|
||||
margin: 0;
|
||||
padding-inline: 1ch;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.user-message .chip {
|
||||
color: var(--luxe-info, #85c7d7);
|
||||
}
|
||||
|
||||
.reply {
|
||||
padding-inline: 1ch;
|
||||
}
|
||||
|
||||
/* Reasoning stays three rows until it's tapped open */
|
||||
.thinking {
|
||||
padding-inline: 1ch;
|
||||
font-style: italic;
|
||||
color: var(--luxe-thinking-text, #97938c);
|
||||
max-height: 3lh;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.thinking.open {
|
||||
max-height: none;
|
||||
}
|
||||
|
||||
.tool {
|
||||
padding: 0.5lh 1ch;
|
||||
background: var(--luxe-tool-call-bg, #201e1a);
|
||||
}
|
||||
|
||||
.tool-head {
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.tool-head::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* The glyph and the name are one label in the TUI, in the call's color */
|
||||
.tool-glyph,
|
||||
.tool-name {
|
||||
font-weight: bold;
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.tool-glyph {
|
||||
margin-inline-end: 1ch;
|
||||
}
|
||||
|
||||
.tool-label {
|
||||
margin-inline: 1ch;
|
||||
}
|
||||
|
||||
.tool-time {
|
||||
color: var(--luxe-muted, #97938c);
|
||||
}
|
||||
|
||||
.tool-body {
|
||||
display: block;
|
||||
padding-inline-start: 3ch;
|
||||
color: var(--luxe-tool-output, #e4dfd6);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.tool-output {
|
||||
margin-block-start: 0.5lh;
|
||||
padding-block-start: 0.5lh;
|
||||
border-top: 1px solid var(--luxe-border-muted, #2e2b27);
|
||||
color: var(--luxe-tool-output, #e4dfd6);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.running :is(.tool-glyph, .tool-name) {
|
||||
color: var(--luxe-accent, #ddc084);
|
||||
}
|
||||
|
||||
.succeeded :is(.tool-glyph, .tool-name) {
|
||||
color: var(--luxe-success, #81caa0);
|
||||
}
|
||||
|
||||
.failed :is(.tool-glyph, .tool-name, .tool-time) {
|
||||
color: var(--luxe-error, #e68485);
|
||||
}
|
||||
|
||||
.interrupted :is(.tool-glyph, .tool-name),
|
||||
.cancelled :is(.tool-glyph, .tool-name) {
|
||||
color: var(--luxe-warning, #faaa51);
|
||||
}
|
||||
279
crates/luxe-remote/app/transcript.js
Normal file
279
crates/luxe-remote/app/transcript.js
Normal file
@@ -0,0 +1,279 @@
|
||||
// The transcript as the phone shows it, folded from a session's frames.
|
||||
//
|
||||
// Each item carries its own signals, so a reply streaming in re-renders one text node rather
|
||||
// than the list. The fold mirrors the TUI's: deltas grow provisional items, `message_committed`
|
||||
// replaces them with what was saved, tool cards follow `tool_activity_updated` by call id, and
|
||||
// `session_loaded` starts over from the saved history.
|
||||
|
||||
import { batch, signal } from "@preact/signals";
|
||||
|
||||
/** @import { Signal } from "@preact/signals" */
|
||||
/** @import { Frame } from "./connection.js" */
|
||||
/**
|
||||
* @typedef {{ type: string, content: any }} Block
|
||||
* @typedef {{ role: string, content: Block[] }} Message
|
||||
* @typedef {"user" | "assistant" | "thinking" | "notice" | "error"} TextKind
|
||||
* @typedef {{
|
||||
* key: string,
|
||||
* kind: TextKind,
|
||||
* text: Signal<string>,
|
||||
* content?: { type: string, content?: string }[],
|
||||
* provisional?: boolean,
|
||||
* }} TextItem
|
||||
* @typedef {{ key: string, kind: "tool", card: Signal<Card> }} ToolItem
|
||||
* @typedef {TextItem | ToolItem} Item
|
||||
* @typedef {{
|
||||
* items: Signal<Item[]>, busy: Signal<boolean>,
|
||||
* cards: Map<string, ToolItem>, live: Map<string, TextItem>, serial: number,
|
||||
* compacting?: TextItem | null,
|
||||
* }} State
|
||||
* @typedef {{
|
||||
* call_id: string, name: string, label: string, state: string, revision: number,
|
||||
* elapsed_ms?: number | null, summary?: string | null, output_preview?: string | null,
|
||||
* card_body?: { text: string, total_lines: number, collapsed_lines: number } | null,
|
||||
* }} Card
|
||||
*/
|
||||
|
||||
/** An empty transcript, and the one function that changes it. */
|
||||
export function createTranscript() {
|
||||
/** @type {State} */
|
||||
const state = { items: signal([]), busy: signal(false), cards: new Map(), live: new Map(), serial: 0 };
|
||||
/** @param {Frame} frame */
|
||||
const fold = (frame) => batch(() => apply(state, frame));
|
||||
return { items: state.items, busy: state.busy, apply: fold };
|
||||
}
|
||||
|
||||
// The engine says a turn started with turn_started; the message that opened it, or anything it
|
||||
// streams, stands in for that from a session whose Luxe predates the event
|
||||
const TURN_SIGNS = new Set(["turn_started", "token_delta", "thinking_delta", "tool_call_composing"]);
|
||||
|
||||
/** @param {State} state @param {Frame} frame */
|
||||
function apply(state, { kind, content }) {
|
||||
if (TURN_SIGNS.has(kind) || (kind === "message_committed" && content.message.role === "user")) {
|
||||
state.busy.value = true;
|
||||
}
|
||||
switch (kind) {
|
||||
case "session_loaded": return load(state, content.messages);
|
||||
case "token_delta": return grow(state, "assistant", content.block, content.delta);
|
||||
case "thinking_delta": return grow(state, "thinking", content.block, content.delta);
|
||||
case "message_committed": return commit(state, content.message);
|
||||
case "tool_activity_updated": return showCard(state, content);
|
||||
case "state_changed": state.busy.value = content.streaming; return;
|
||||
case "turn_ended": return endTurn(state);
|
||||
case "notice": return push(state, textItem(state, "notice", content));
|
||||
case "error": push(state, textItem(state, "error", content)); return endTurn(state);
|
||||
case "action_rejected": return push(state, textItem(state, "error", `Refused: ${content.reason}`));
|
||||
case "compaction_started": return startCompaction(state, content.tokens_before);
|
||||
case "compaction_done": return settleCompaction(state, compacted(content));
|
||||
case "compaction_stopped": return settleCompaction(state, "Compaction stopped.");
|
||||
}
|
||||
}
|
||||
|
||||
// A summary takes a minute and nothing else streams meanwhile, so it's said as it starts, and the
|
||||
// same line becomes how it ended
|
||||
/** @param {State} state @param {number} tokens */
|
||||
function startCompaction(state, tokens) {
|
||||
state.compacting = textItem(state, "notice", `Compacting the conversation — ${formatTokens(tokens)} of context…`);
|
||||
push(state, state.compacting);
|
||||
}
|
||||
|
||||
/** @param {State} state @param {string} text */
|
||||
function settleCompaction(state, text) {
|
||||
const line = state.compacting;
|
||||
state.compacting = null;
|
||||
if (line && state.items.value.includes(line)) line.text.value = text;
|
||||
else push(state, textItem(state, "notice", text));
|
||||
}
|
||||
|
||||
/** @param {{ tokens_before: number, tokens_after: number }} content */
|
||||
function compacted({ tokens_before, tokens_after }) {
|
||||
return `Compacted the conversation — ${formatTokens(tokens_before)} → ${formatTokens(tokens_after)} of context.`;
|
||||
}
|
||||
|
||||
/** A token count as the TUI writes it: `812`, `579.4k`, `1.2M`. @param {number} count */
|
||||
export function formatTokens(count) {
|
||||
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
|
||||
if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
|
||||
return String(count);
|
||||
}
|
||||
|
||||
/** @param {State} state @param {{ message: Message }[]} messages */
|
||||
function load(state, messages) {
|
||||
state.items.value = [];
|
||||
state.cards.clear();
|
||||
state.live.clear();
|
||||
for (const { message } of messages) replay(state, message);
|
||||
for (const item of state.cards.values()) settleUnfinished(item, "interrupted");
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Message} message */
|
||||
function replay(state, message) {
|
||||
if (message.role === "assistant") {
|
||||
for (const item of assistantItems(state, message.content)) push(state, item);
|
||||
for (const block of message.content) if (block.type === "tool_call") cardFromCall(state, block.content);
|
||||
return;
|
||||
}
|
||||
if (message.role === "tool") return settleResults(state, message.content);
|
||||
commit(state, message);
|
||||
}
|
||||
|
||||
/** @param {State} state @param {TextKind} kind @param {number} block @param {string} delta */
|
||||
function grow(state, kind, block, delta) {
|
||||
const slot = `${kind}:${block}`;
|
||||
let item = state.live.get(slot);
|
||||
if (!item) {
|
||||
item = { ...textItem(state, kind, ""), provisional: true };
|
||||
state.live.set(slot, item);
|
||||
push(state, item);
|
||||
}
|
||||
item.text.value += delta;
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Message} message */
|
||||
function commit(state, message) {
|
||||
if (message.role === "user") {
|
||||
// a photo sent on its own is still a message, shown by its "attached" line
|
||||
const words = message.content.find((block) => block.type === "text");
|
||||
const shown = words || message.content.some((block) => block.type === "image");
|
||||
if (shown) push(state, { ...textItem(state, "user", words?.content ?? ""), content: wordsOnly(message.content) });
|
||||
return;
|
||||
}
|
||||
if (message.role === "assistant") return commitAssistant(state, message.content);
|
||||
if (message.role === "tool") return settleResults(state, message.content);
|
||||
if (message.role === "system") for (const block of message.content) {
|
||||
if (block.type === "text") push(state, textItem(state, "notice", block.content));
|
||||
}
|
||||
}
|
||||
|
||||
// Line the saved blocks up with the streamed ones in place; if they don't match, swap them out
|
||||
/** @param {State} state @param {Block[]} content */
|
||||
function commitAssistant(state, content) {
|
||||
const saved = assistantItems(state, content);
|
||||
const streamed = state.items.value.filter(isProvisional);
|
||||
state.live.clear();
|
||||
const linesUp = saved.length === streamed.length
|
||||
&& saved.every((item, index) => item.kind === streamed[index].kind);
|
||||
if (linesUp) {
|
||||
streamed.forEach((item, index) => settleText(item, saved[index].text.value));
|
||||
return;
|
||||
}
|
||||
replaceStreamed(state, streamed, saved);
|
||||
}
|
||||
|
||||
/** @param {Item} item @returns {item is TextItem} */
|
||||
function isProvisional(item) {
|
||||
return item.kind !== "tool" && item.provisional === true;
|
||||
}
|
||||
|
||||
/** @param {State} state @param {TextItem[]} streamed @param {TextItem[]} saved */
|
||||
function replaceStreamed(state, streamed, saved) {
|
||||
const items = state.items.value;
|
||||
const at = streamed.length ? items.indexOf(streamed[0]) : items.length;
|
||||
/** @type {Item[]} */
|
||||
const kept = items.filter((item) => !isProvisional(item));
|
||||
kept.splice(Math.min(at, kept.length), 0, ...saved);
|
||||
state.items.value = kept;
|
||||
}
|
||||
|
||||
/** @param {TextItem} item @param {string} text */
|
||||
function settleText(item, text) {
|
||||
item.text.value = text;
|
||||
item.provisional = false;
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Block[]} content */
|
||||
function assistantItems(state, content) {
|
||||
/** @type {TextItem[]} */
|
||||
const items = [];
|
||||
for (const block of content) {
|
||||
// Saved reasoning often ends in blank lines, which would draw as a gap
|
||||
const thinking = block.type === "thinking" ? block.content.text.trimEnd() : "";
|
||||
const text = block.type === "text" ? block.content.trimEnd() : "";
|
||||
if (thinking) items.push(textItem(state, "thinking", thinking));
|
||||
if (text) items.push(textItem(state, "assistant", text));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Card} activity */
|
||||
function showCard(state, activity) {
|
||||
const known = state.cards.get(activity.call_id);
|
||||
if (!known) {
|
||||
/** @type {ToolItem} */
|
||||
const item = { key: `tool:${activity.call_id}`, kind: "tool", card: signal(activity) };
|
||||
state.cards.set(activity.call_id, item);
|
||||
return push(state, item);
|
||||
}
|
||||
if (activity.revision >= known.card.value.revision) known.card.value = activity;
|
||||
}
|
||||
|
||||
/** @param {State} state @param {{ id: string, name: string, arguments: any }} call */
|
||||
function cardFromCall(state, { id, name, arguments: args }) {
|
||||
const label = describeCall(args);
|
||||
// A described command shows the command under it, as a live card does
|
||||
const command = typeof args?.command === "string" && args.command !== label ? args.command : "";
|
||||
const card_body = command ? { text: command, total_lines: 1, collapsed_lines: 3 } : null;
|
||||
showCard(state, { call_id: id, name, label, card_body, state: "running", revision: 0 });
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Block[]} content */
|
||||
function settleResults(state, content) {
|
||||
for (const block of content) {
|
||||
if (block.type !== "tool_result") continue;
|
||||
const { call_id, content: output, is_error } = block.content;
|
||||
const item = state.cards.get(call_id);
|
||||
if (!item) continue;
|
||||
/** @type {Block[]} */
|
||||
const parts = output;
|
||||
const text = parts.filter((part) => part.type === "text").map((part) => part.content).join("\n");
|
||||
const card = item.card.value;
|
||||
item.card.value = {
|
||||
...card,
|
||||
state: is_error ? "failed" : "succeeded",
|
||||
output_preview: card.output_preview ?? text,
|
||||
revision: card.revision + 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {State} state */
|
||||
function endTurn(state) {
|
||||
state.live.clear();
|
||||
for (const item of state.items.value) if (item.kind !== "tool") item.provisional = false;
|
||||
state.busy.value = false;
|
||||
}
|
||||
|
||||
/** @param {ToolItem} item @param {string} final */
|
||||
function settleUnfinished(item, final) {
|
||||
const card = item.card.value;
|
||||
if (card.state === "running" || card.state === "queued" || card.state === "composing") {
|
||||
item.card.value = { ...card, state: final, revision: card.revision + 1 };
|
||||
}
|
||||
}
|
||||
|
||||
/** What a call from history was about, from its arguments: the label live cards are sent with. */
|
||||
/** @param {any} args @returns {string} */
|
||||
export function describeCall(args) {
|
||||
for (const field of ["description", "command", "path", "pattern", "query", "url"]) {
|
||||
if (typeof args?.[field] === "string") return args[field];
|
||||
}
|
||||
if (Array.isArray(args?.paths)) return args.paths.join(", ");
|
||||
return "";
|
||||
}
|
||||
|
||||
// The blocks as the host needs them to say what a message shows: text, and the place of the rest,
|
||||
// so a photo's bytes aren't sent back to be rendered
|
||||
/** @param {Block[]} content */
|
||||
function wordsOnly(content) {
|
||||
return content.map((block) => (block.type === "text" ? block : { type: block.type }));
|
||||
}
|
||||
|
||||
/** @param {State} state @param {TextKind} kind @param {string} text @returns {TextItem} */
|
||||
function textItem(state, kind, text) {
|
||||
return { key: `${kind}:${state.serial++}`, kind, text: signal(text) };
|
||||
}
|
||||
|
||||
/** @param {State} state @param {Item} item */
|
||||
function push(state, item) {
|
||||
state.items.value = [...state.items.value, item];
|
||||
}
|
||||
2
crates/luxe-remote/app/vendor/hooks.mjs
vendored
Normal file
2
crates/luxe-remote/app/vendor/hooks.mjs
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
import{options as n}from"preact";var t,r,u,i,o=Object.is,f=0,c=[],e=[],a=n,v=a.__b,l=a.__r,m=a.diffed,s=a.__c,h=a.unmount,p=a.__;function y(n,t){a.__h&&a.__h(r,n,f||t),f=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return f=1,_(G,n)}function _(n,u,i){var f=y(t++,2);if(f.t=n,!f.__c&&(f.__=[i?i(u):G(void 0,u),function(n){var t=f.__N?f.__N[0]:f.__[0],r=f.t(t,n);o(t,r)||(f.__N=[r,f.__[1]],f.__c.setState({}))}],f.__c=r,!r.__f)){r.__f=!0;var c=r.shouldComponentUpdate;r.shouldComponentUpdate=function(n,t,r){var u=this.__H;if(!u)return!0;var i=!1,f=this.props!=n;if(u.__.some(function(n){n.__N&&(i=!0,o(n.__[0],n.__N[0])||(f=!0))}),c){var e=c.call(this,n,t,r);return i?e||f:e}return!i||f}}return f.__}function A(n,u){var i=y(t++,3);!a.__s&&E(i.__H,u)&&(i.__P=!0,i.__=n,i.u=u,r.__H.__h.push(i))}function F(n,u){var i=y(t++,4);!a.__s&&E(i.__H,u)&&(i.__P=!1,i.__=n,i.u=u,r.__h.push(i))}function T(n){return f=5,b(function(){return{current:n}},[])}function q(n,t,r){f=6,F(function(){if("function"==typeof n){var r=n(t());return function(){n(null),r&&"function"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function b(n,r){var u=y(t++,7);return E(u.__H,r)&&(u.__=n(),u.__H=r),u.__}function j(n,t){return f=8,b(function(){return n},t)}function w(n){var u=r.context[n.__c],i=y(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function x(n,t){a.useDebugValue&&a.useDebugValue(t?t(n):n)}function O(n){var u=y(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function P(){var n=y(t++,11);if(!n.__){for(var u=r.__v;!u.__m&&u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__}function g(){var n;do{for(;n=e.shift();)try{C(n)}catch(t){a.__e(t,{__:(n=n.__P)&&n.__v})}for(;n=c.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(C),t.__h.some(D),t.__h=[]}catch(r){t.__h=[],a.__e(r,n.__v)}}}while(e.length)}a.__b=function(n){r=null,v&&v(n)},a.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},a.__r=function(n){l&&l(n),t=0;var i=(r=n.__c).__H;i&&(u==r?r.__h=[]:(i.__h.some(C),i.__h.some(D),t=0),i.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})),u=r},a.diffed=function(n){m&&m(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&B(c.push(t)),t.__H.__.some(function(n){n.u&&(n.__H=n.u)})),u=r=null},a.__c=function(n,t){t.some(function(n){try{n.__h.some(C),n.__h=n.__h.filter(function(n){return!n.__||D(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],a.__e(r,n.__v)}}),s&&s(n,t)},a.unmount=function(n){h&&h(n);var t,r,u=n.__c;u&&u.__H&&(u.__H.__.some(function(u){try{if(u.__P&&u.__c){if(void 0===r){for(r=n.__;r&&(!r.__c||!r.__c.__P);)r=r.__;r=r&&r.__c}u.__P=r,B(e.push(u))}else C(u)}catch(n){t=n}}),u.__H=void 0,t&&a.__e(t,u.__v))};var k="function"==typeof requestAnimationFrame;function z(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function B(n){1!=n&&i==a.requestAnimationFrame||((i=a.requestAnimationFrame)||z)(g)}function C(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function D(n){var t=r;n.__c=n.__(),r=t}function E(n,t){return!n||n.length!=t.length||t.some(function(t,r){return!o(t,n[r])})}function G(n,t){return"function"==typeof t?t(n):t}export{j as useCallback,w as useContext,x as useDebugValue,A as useEffect,O as useErrorBoundary,P as useId,q as useImperativeHandle,F as useLayoutEffect,b as useMemo,_ as useReducer,T as useRef,d as useState};
|
||||
//# sourceMappingURL=hooks.mjs.map
|
||||
1
crates/luxe-remote/app/vendor/htm.mjs
vendored
Normal file
1
crates/luxe-remote/app/vendor/htm.mjs
vendored
Normal file
@@ -0,0 +1 @@
|
||||
var n=function(t,s,r,e){var u;s[0]=0;for(var h=1;h<s.length;h++){var p=s[h++],a=s[h]?(s[0]|=p?1:2,r[s[h++]]):s[++h];3===p?e[0]=a:4===p?e[1]=Object.assign(e[1]||{},a):5===p?(e[1]=e[1]||{})[s[++h]]=a:6===p?e[1][s[++h]]+=a+"":p?(u=t.apply(a,n(t,a,r,["",null])),e.push(u),a[0]?s[0]|=2:(s[h-2]=0,s[h]=u)):e.push(a)}return e},t=new Map;export default function(s){var r=t.get(this);return r||(r=new Map,t.set(this,r)),(r=n(this,r.get(s)||(r.set(s,r=function(n){for(var t,s,r=1,e="",u="",h=[0],p=function(n){1===r&&(n||(e=e.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?h.push(0,n,e):3===r&&(n||e)?(h.push(3,n,e),r=2):2===r&&"..."===e&&n?h.push(4,n,0):2===r&&e&&!n?h.push(5,0,!0,e):r>=5&&((e||!n&&5===r)&&(h.push(r,0,e,s),r=6),n&&(h.push(r,n,0,s),r=6)),e=""},a=0;a<n.length;a++){a&&(1===r&&p(),p(a));for(var l=0;l<n[a].length;l++)t=n[a][l],1===r?"<"===t?(p(),h=[h],r=3):e+=t:4===r?"--"===e&&">"===t?(r=1,e=""):e=t+e[0]:u?t===u?u="":e+=t:'"'===t||"'"===t?u=t:">"===t?(p(),r=1):r&&("="===t?(r=5,s=e,e=""):"/"===t&&(r<5||">"===n[a][l+1])?(p(),3===r&&(h=h[0]),r=h,(h=h[0]).push(2,0,r),r=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(p(),r=2):e+=t),3===r&&"!--"===e&&(r=4,h=h[0])}return p(),h}(s)),r),arguments,[])).length>1?r:r[0]}
|
||||
202
crates/luxe-remote/app/vendor/licenses/htm.txt
vendored
Normal file
202
crates/luxe-remote/app/vendor/licenses/htm.txt
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2018 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
21
crates/luxe-remote/app/vendor/licenses/preact-signals-core.txt
vendored
Normal file
21
crates/luxe-remote/app/vendor/licenses/preact-signals-core.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022-present Preact Team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
21
crates/luxe-remote/app/vendor/licenses/preact-signals.txt
vendored
Normal file
21
crates/luxe-remote/app/vendor/licenses/preact-signals.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022-present Preact Team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
21
crates/luxe-remote/app/vendor/licenses/preact.txt
vendored
Normal file
21
crates/luxe-remote/app/vendor/licenses/preact.txt
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present Jason Miller
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
7
crates/luxe-remote/app/vendor/manifest.json
vendored
Normal file
7
crates/luxe-remote/app/vendor/manifest.json
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
[
|
||||
{"file": "preact.mjs", "package": "preact", "version": "11.0.1", "from": "dist/preact.mjs", "license": "MIT", "sha256": "3a3201e9ccef7d30ef1273427f1b17ef8323e464b2c8d73b4fd5636af730433e"},
|
||||
{"file": "hooks.mjs", "package": "preact", "version": "11.0.1", "from": "hooks/dist/hooks.mjs", "license": "MIT", "sha256": "6cb79fe9959ad185b8b86134aff47c12fd20216b24837597b19be59a133d9947"},
|
||||
{"file": "htm.mjs", "package": "htm", "version": "3.1.1", "from": "dist/htm.mjs", "license": "Apache-2.0", "sha256": "ab33dd3f38059b9be4d5f5350128eefb2356639c4e0bbe9d9e8b3ba75847e9e4"},
|
||||
{"file": "signals-core.mjs", "package": "@preact/signals-core", "version": "1.14.4", "from": "dist/signals-core.mjs", "license": "MIT", "sha256": "0676238240715faeb4eb8b0a329837dc06ef7f37e7103601e13af3ed309c042c"},
|
||||
{"file": "signals.mjs", "package": "@preact/signals", "version": "2.11.3", "from": "dist/signals.mjs", "license": "MIT", "sha256": "19c5ca080f54f3b36d1b687555dc82c0c8ce29eaedc0ca42b237012892861841"}
|
||||
]
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user