All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
Share a whole machine by link (#33)
Adib Hannaa8d4c7ddc691
diff --git a/README.md b/README.mdindex a59753d..f7e5a0f 100644--- a/README.md+++ b/README.md@@ -403,16 +403,17 @@ muxin session stop beelink/claude-3f9aBuild the agent for every platform with `scripts/build-agents.sh` (needs `cargo-zigbuild` and Zig for the Linux builds); `scripts/bundle-macos.sh` runs it and ships the builds inside the app.-## Sharing a session+## Sharing a session or a machine-Show someone a session, or let them type in it, straight from your computer. They join from Muxin or from any browser; nothing to install.+Show someone a session, or a whole machine, straight from your computer. They join from Muxin or from any browser; nothing to install.- **Share.** On a session's page, click **Share**: the link is made and copied, ready to paste anywhere (`https://muxin.dev/s#1.…`). By default you let each person in, they can only watch, and it lasts an hour; change any of that in the same window, while it runs: let them type, let anyone with the link watch without asking, or make it last longer.-- **Let people in.** When someone opens it, a card over the terminal shows their name and a 6-digit code; they see the same code. Ask them to read it out, then **Let in**. A link that leaked shows a code nobody reads to you.-- **While you share.** The header says who's there (**Shared · Sam watching**). Click it to let someone type or stop them, remove them, copy the link, add an hour, or stop sharing. A shared session has an eye in the sidebar; a dot means someone is waiting.-- **Joining.** The link opens a page that asks for their name, then joins right there in the browser (or in Muxin, if they have it). In Muxin, ⇧⌘P › **Join a shared session…** takes a link too. Shared sessions are listed under **Shared with you**, shown at the size the sharer's terminal is.+- **Share a machine.** On a machine's page, **Share** does the same for all of its sessions: guests see the sessions running there (and ones started later) and open any of them. In the same window, share its desktop (**View**, or **Control** for people you let in) and pick which of its servers they can open (**Servers**: what's listening there, web servers first). Everything else stays off: no files, no shell, no other ports.+- **Let people in.** When someone opens it, a card over the page shows their name and a 6-digit code; they see the same code. Ask them to read it out, then **Let in**. A link that leaked shows a code nobody reads to you.+- **While you share.** The header says who's there (**Shared · Sam watching**). Click it to let someone type or stop them, let them use the desktop or stop them, remove them, copy the link, add an hour, or stop sharing. A shared session has an eye in the sidebar; a dot means someone is waiting.+- **Joining.** The link opens a page that asks for their name, then joins right there in the browser (or in Muxin, if they have it). In Muxin, ⇧⌘P › **Join a share…** takes a link too. Shares are listed under **Shared with you**, sessions shown at the size the sharer's terminal is. A shared machine's page lists its sessions, its screen and its servers; **Open** puts a server at `localhost` on the guest's computer (in Muxin; a browser can't open ports).- **Peer to peer.** The two computers connect directly (WebRTC): over your network or Tailscale when they share one, across the internet otherwise, and through an encrypted relay only when nothing direct works. muxin.dev only introduces them, with two short messages: the part of the link after `#` (the share's secret) never reaches it, and the guest checks that it reached the sharing computer's own certificate, so the site can't listen in or join.-- **What a guest can do.** Watch the one session shared, and type in it only while you let them. Muxin enforces it on your computer, and the agent on the machine attaches a watcher that can't type or resize. Guests never reach the machine, its other sessions, files or a shell.+- **What a guest can do.** Only what's shared, and type, use the desktop or open servers only while you let them. Muxin enforces it on your computer, and the agent on the machine attaches a watcher that can't type or resize. Guests never reach the machine itself, its files or a shell.- **It ends** when its time runs out, when you **Stop sharing**, or when you quit Muxin. The link stops working then, for good.To introduce them through a server of your own instead (`share-server/` in this repository), set `[settings.share] server = "https://share.example.com"` in `config.toml`.diff --git a/share-server/web/index.html b/share-server/web/index.htmlindex 740387c..ef16677 100644--- a/share-server/web/index.html+++ b/share-server/web/index.html@@ -27,7 +27,7 @@<main><section id="start" class="center" hidden><form id="join-form" class="card stack">- <h1>Join a shared session</h1>+ <h1>Join a share</h1><p class="muted">Right here in your browser. Nothing to install.</p><label for="name">Your name</label><input id="name" name="name" maxlength="40" autocomplete="name" placeholder="Sam" required>@@ -41,11 +41,7 @@<div class="card stack"><h2 id="wait-title">Connecting…</h2><p id="wait-sub" class="muted"></p>- <ul id="facts" class="facts" hidden>- <li id="fact-can"></li>- <li id="fact-ends"></li>- <li id="fact-name"></li>- </ul>+ <ul id="facts" class="facts" hidden></ul><div id="code-box" class="code-box" hidden><span class="muted small">Your code</span><span id="code" class="code"></span>@@ -59,9 +55,25 @@</section><section id="watch" class="watch" hidden>+ <nav id="tabs" class="tabs" aria-label="What's shared" hidden></nav><div id="term" class="term"></div>+ <div id="screen" class="screen" hidden>+ <canvas id="canvas" tabindex="0" aria-label="Their screen"></canvas>+ <p id="screen-wait" class="muted">Starting their screen…</p>+ </div>+ <p id="empty" class="empty muted" hidden></p><div class="term-bar"><span id="term-note">You're watching.</span>+ <button type="button" id="kbd" class="secondary small-btn" hidden>Keyboard</button>+ <input id="kbd-input" class="kbd-input" aria-label="Type on their screen" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false">+ <label id="quality-wrap" class="quality" hidden>Quality+ <select id="quality">+ <option value="low">Low</option>+ <option value="medium" selected>Medium</option>+ <option value="high">High</option>+ <option value="max">Max</option>+ </select>+ </label><span class="muted" id="term-path">Peer to peer · encrypted</span></div></section>diff --git a/share-server/web/join.css b/share-server/web/join.cssindex 45d0784..d2247d3 100644--- a/share-server/web/join.css+++ b/share-server/web/join.css@@ -115,3 +115,67 @@ button:disabled { opacity: 0.6; cursor: default; }padding: 10px 14px; border-radius: 10px; background: var(--surface); font-size: 13px;}.term-bar > :first-child { flex: 1 1 220px; }++.tabs {+ width: 100%; max-width: 1200px; display: flex; flex-wrap: wrap; gap: 6px; align-items: center;+}+.tab {+ min-height: 34px; padding: 6px 12px; border-radius: 8px; border: 1px solid var(--border-soft);+ background: var(--surface); font-size: 13px; display: inline-flex; align-items: center; gap: 8px; max-width: 260px;+}+.tab span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.tab[aria-pressed="true"] { border-color: var(--accent); background: var(--accent-soft); }+.tab.exited { color: var(--muted); }+.tab .busy { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); flex: none; }+.tabs .gap { flex: 1; }+.tabs .hint { font-size: 12px; color: var(--muted); }++.screen {+ width: 100%; max-width: 1600px; flex: 1; min-height: 320px; display: flex; align-items: center; justify-content: center;+ border: 1px solid var(--border-soft); border-radius: 10px; background: #000; overflow: hidden; position: relative;+}+.screen canvas { max-width: 100%; max-height: 100%; display: block; outline: none; cursor: default; }+.screen canvas.control { cursor: crosshair; }+.screen canvas:focus-visible { outline: 2px solid var(--accent); }+.screen p { position: absolute; margin: 0; }+.empty { flex: 1; display: flex; align-items: center; justify-content: center; margin: 0; }+.quality { display: inline-flex; align-items: center; gap: 8px; color: var(--muted); font-size: 13px; }+.quality select {+ font: inherit; color: var(--text); background: var(--canvas); border: 1px solid var(--border);+ border-radius: 7px; padding: 4px 8px;+}++/* The shared screen: touch drives it while you're let control it. */+.screen canvas.control { touch-action: none; }+.small-btn { min-height: 34px; padding: 5px 14px; font-size: 13px; }+.kbd-input { position: fixed; left: 0; bottom: 0; width: 1px; height: 1px; opacity: 0; border: 0; padding: 0; }++/* Phones: one compact header row, the rest of the screen for what's shared. */+@media (max-width: 640px) {+ .bar { padding: 10px 14px; gap: 8px 10px; flex-wrap: nowrap; }+ .brand { gap: 0; font-size: 0; }+ .logo { width: 22px; height: 22px; }+ .session { flex: 1 1 0; padding-left: 10px; }+ .session-title { font-size: 15px; }+ .session-sub { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .session-actions { gap: 8px; flex-wrap: nowrap; }+ #time-left { display: none; }+ .pill { padding: 3px 10px; font-size: 13px; }+ #leave { min-height: 34px; padding: 5px 12px; font-size: 13px; }+ .watch { padding: 10px 8px; gap: 8px; }+ .tabs { flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; }+ .tab { flex: none; }+ .tabs .gap, .tabs .hint { display: none; }+ .term { padding: 8px; min-height: 260px; }+ .screen { min-height: 200px; }+ .term-bar { padding: 8px 12px; font-size: 12.5px; }+ .card { padding: 20px; }+ h1 { font-size: 26px; }+ .code { font-size: 30px; }+}++/* Portrait phones and tablets: the box is the screen's own shape, not a tall black frame around it. */+@media (orientation: portrait) and (max-width: 1024px) {+ .screen { flex: none; min-height: 0; }+ .screen canvas { width: 100%; height: auto; max-height: none; }+}diff --git a/share-server/web/join.js b/share-server/web/join.jsindex ed6352e..2627715 100644--- a/share-server/web/join.js+++ b/share-server/web/join.js@@ -1,12 +1,15 @@// Joins a Muxin share from the browser: the link's ticket (after the #)// names the share, its secret and its certificate. This page connects to// the sharing computer over WebRTC, refuses any other certificate, proves-// it has the link, then shows the session. See src/share in Muxin.+// it has the link, then shows what's shared: a session, or a machine's+// sessions and screen. See src/share in Muxin."use strict";(() => {- const JSON_KIND = 10, DATA = 0, EXIT = 2, SIZE = 3, CLOSE = 11;- const SESSION = 1;+ // MORE: part of a frame too big for one message; the rest follows on its channel.+ const JSON_KIND = 10, DATA = 0, EXIT = 2, SIZE = 3, CLOSE = 11, MORE = 12;+ // The screen's frames: whole ones, input back, what changed (agent/src/desktop.rs).+ const FRAME = 20, INPUT = 21, TILES = 23;const $ = (id) => document.getElementById(id);const enc = new TextEncoder();const dec = new TextDecoder();@@ -77,7 +80,13 @@show("done");}- const state = { over: false, pc: null, dc: null, term: null, canType: false, info: null, clock: 0, name: "" };+ const state = {+ over: false, pc: null, dc: null, term: null, canType: false, canControl: false, info: null, clock: 0, name: "",+ // Channels open (number → {kind: "session" | "desktop", name}), and the next one.+ channels: new Map(), next: 1,+ // A shared machine's sessions; what's showing ({kind, name}).+ sessions: [], showing: null, session: 0, desktop: 0,+ };function minutesLeft(endsAt) {const s = endsAt - Date.now() / 1000;@@ -92,14 +101,24 @@function showInfo(info) {state.info = info;const what = agents[info.agent] || "A session";- $("session-title").textContent = info.title || what;- $("session-sub").textContent = `${what} on ${info.machine} · shared by ${info.by}`;+ const title = info.machine_share ? info.title : info.title || what;+ const sub = info.machine_share ? `A machine · shared by ${info.by}` : `${what} on ${info.machine} · shared by ${info.by}`;+ $("session-title").textContent = title;+ $("session-sub").textContent = sub;$("session").hidden = false;- $("wait-title").textContent = `Join ${info.title || what}`;- $("wait-sub").textContent = `${what} on ${info.machine} · shared by ${info.by}`;- $("fact-can").textContent = info.can_type ? "You can watch and type" : "You can watch";- $("fact-ends").textContent = `Ends in ${minutesLeft(info.ends_at).replace(" left", "")}`;- $("fact-name").textContent = `Joining as ${state.name}`;+ $("wait-title").textContent = `Join ${title}`;+ $("wait-sub").textContent = sub;+ const facts = [];+ if (info.machine_share) {+ facts.push(info.can_type ? "Its sessions: you can watch and type" : "Its sessions: you can watch");+ if (info.desktop === "view") facts.push("Its screen: you can watch");+ if (info.desktop === "control") facts.push(info.can_control ? "Its screen: you can watch and use it" : "Its screen: you can watch, and use it when they let you");+ if (info.ports.length) facts.push(`${info.ports.length} server${info.ports.length === 1 ? "" : "s"}: open them in the Muxin app`);+ } else {+ facts.push(info.can_type ? "You can watch and type" : "You can watch");+ }+ facts.push(`Ends in ${minutesLeft(info.ends_at).replace(" left", "")}`, `Joining as ${state.name}`);+ $("facts").replaceChildren(...facts.map((f) => Object.assign(document.createElement("li"), { textContent: f })));$("facts").hidden = false;$("code-help").textContent = `Read it to ${info.by} so they know it's you.`;clearInterval(state.clock);@@ -107,73 +126,522 @@$("time-left").textContent = minutesLeft(info.ends_at);}- function setTyping(allowed) {- state.canType = allowed;- $("mode-pill").textContent = allowed ? "Typing" : "Watching";+ // The bar under what's showing, and the pill: what you can do there.+ function updateNote() {const by = state.info ? state.info.by : "they";- $("term-note").textContent = allowed ? "You can type. Keys go to their session." : `You're watching. Only ${by} can type.`;- if (state.term) state.term.options.disableStdin = !allowed;+ const desktop = state.showing && state.showing.kind === "desktop";+ $("mode-pill").textContent = desktop ? (state.canControl ? "In control" : "Watching") : state.canType ? "Typing" : "Watching";+ $("term-note").textContent = desktop+ ? state.canControl ? `Your mouse and keys work on ${state.info.title}.` : `You're watching. Only ${by} can use it.`+ : state.canType ? "You can type. Keys go to their session." : `You're watching. Only ${by} can type.`;+ if (state.term) state.term.options.disableStdin = !state.canType;+ $("canvas").classList.toggle("control", state.canControl);+ $("kbd").hidden = !(desktop && state.canControl);}- function openTerminal() {- show("watch");- $("session-actions").hidden = false;+ function makeTerminal() {const term = new window.Terminal({cols: 80, rows: 24, scrollback: 5000, convertEol: false, cursorBlink: true, disableStdin: true,fontFamily: 'ui-monospace, "SF Mono", Menlo, Consolas, monospace', fontSize: 13,theme: { background: "#1a1e3c", foreground: "#eeecfb", cursor: "#eeecfb", selectionBackground: "#3d3a7a" },});term.open($("term"));- term.onData((data) => {- if (state.canType && state.dc && state.dc.readyState === "open") state.dc.send(frame(SESSION, DATA, enc.encode(data)));- });- term.onBinary((data) => {- if (!state.canType || !state.dc || state.dc.readyState !== "open") return;- state.dc.send(frame(SESSION, DATA, Uint8Array.from(data, (c) => c.charCodeAt(0) & 255)));- });+ const keys = (bytes) => {+ if (state.canType && state.session && state.dc && state.dc.readyState === "open") state.dc.send(frame(state.session, DATA, bytes));+ };+ term.onData((data) => keys(enc.encode(data)));+ term.onBinary((data) => keys(Uint8Array.from(data, (c) => c.charCodeAt(0) & 255)));state.term = term;- setTyping(state.canType);+ if (window.ResizeObserver) new ResizeObserver(fitText).observe($("term"));+ }++ // The session keeps the sharer's size: its text is sized to fit the width+ // here (13px at most; on a phone, 9px at least, and it scrolls sideways).+ function fitText() {+ const term = state.term;+ if (!term) return;+ const box = $("term");+ const width = box.clientWidth - 24;+ if (width <= 0) return;+ const size = Math.max(9, Math.min(13, Math.floor((width / (term.cols * 0.6)) * 2) / 2));+ if (term.options.fontSize !== size) term.options.fontSize = size;}function send(obj) {if (state.dc && state.dc.readyState === "open") state.dc.send(frame(0, JSON_KIND, enc.encode(JSON.stringify(obj))));}+ function openChannel(op, extra, kind, name) {+ const channel = state.next++;+ state.channels.set(channel, { kind, name });+ send(Object.assign({ op, channel }, extra));+ return channel;+ }++ function closeChannel(channel) {+ if (!channel || !state.channels.has(channel)) return;+ state.channels.delete(channel);+ if (state.dc && state.dc.readyState === "open") state.dc.send(frame(channel, CLOSE, new Uint8Array(0)));+ }++ // What the page shows: a session (in the one terminal) or the screen.+ function showSession(name) {+ if (state.showing && state.showing.kind === "session" && state.showing.name === name && state.session) return;+ closeChannel(state.session);+ state.showing = { kind: "session", name };+ state.term.reset();+ state.session = openChannel("watch", { session: name }, "session", name);+ closeScreen();+ $("quality-wrap").hidden = true;+ $("kbd").hidden = true;+ $("term").hidden = false;+ $("screen").hidden = true;+ $("empty").hidden = true;+ renderTabs();+ updateNote();+ state.term.focus();+ }++ function showDesktop() {+ state.showing = { kind: "desktop" };+ if (!state.desktop) {+ $("screen-wait").textContent = "Starting their screen…";+ $("screen-wait").hidden = false;+ state.desktop = openChannel("desktop", { quality: $("quality").value }, "desktop", "");+ }+ $("quality-wrap").hidden = false;+ $("term").hidden = true;+ $("screen").hidden = false;+ $("empty").hidden = true;+ renderTabs();+ updateNote();+ $("canvas").focus();+ }++ // The screen isn't showing: its stream stops (it starts again when shown).+ function closeScreen() {+ letGo();+ closeChannel(state.desktop);+ state.desktop = 0;+ }++ function showEmpty(text) {+ state.showing = null;+ closeScreen();+ $("quality-wrap").hidden = true;+ $("kbd").hidden = true;+ $("term").hidden = true;+ $("screen").hidden = true;+ $("empty").textContent = text;+ $("empty").hidden = false;+ renderTabs();+ }++ function tab(label, pressed, onClick, extra) {+ const b = document.createElement("button");+ b.type = "button";+ b.className = "tab" + (extra && extra.exited ? " exited" : "");+ b.setAttribute("aria-pressed", pressed ? "true" : "false");+ if (extra && extra.busy) b.append(Object.assign(document.createElement("i"), { className: "busy" }));+ b.append(Object.assign(document.createElement("span"), { textContent: label }));+ b.addEventListener("click", onClick);+ return b;+ }++ function renderTabs() {+ const info = state.info;+ if (!info || !info.machine_share) return;+ const items = state.sessions.map((s) => {+ const label = s.title || agents[s.agent] || s.name;+ const on = state.showing && state.showing.kind === "session" && state.showing.name === s.name;+ return tab(label, on, () => showSession(s.name), { busy: s.busy, exited: s.status === "exited" });+ });+ if (info.desktop !== "none") items.push(tab("Screen", state.showing && state.showing.kind === "desktop", showDesktop));+ if (info.ports.length) {+ items.push(Object.assign(document.createElement("span"), { className: "gap" }));+ items.push(Object.assign(document.createElement("span"), { className: "hint", textContent: `${info.ports.length} server${info.ports.length === 1 ? "" : "s"} shared: open them in the Muxin app` }));+ }+ $("tabs").replaceChildren(...items);+ $("tabs").hidden = false;+ }++ function admitted() {+ show("watch");+ $("session-actions").hidden = false;+ makeTerminal();+ if (state.info && state.info.machine_share) {+ showEmpty(`Looking at ${state.info.title}'s sessions…`);+ } else {+ showSession("");+ }+ updateNote();+ }++ // ---- The screen: patches painted as they come, in order; input back.++ const canvas = () => $("canvas");+ // What arrived and isn't painted yet. While a paint runs, newer screens+ // wait here; the next paint takes them all at once and skips the parts a+ // later one covers, so a slow device shows the newest screen, never one+ // that falls further and further behind.+ let waiting = [];+ let painting = false;++ function paint(kind, body) {+ waiting.push([kind, body.slice()]);+ if (!painting) paintWaiting();+ }++ // The patches of a TILES message: [x, y, w, h, jpeg].+ function patchesOf(copy) {+ const v = new DataView(copy.buffer);+ const n = v.getUint16(4), patches = [];+ let o = 6;+ for (let i = 0; i < n && o + 12 <= copy.length; i++) {+ const len = v.getUint32(o + 8);+ patches.push([v.getUint16(o), v.getUint16(o + 2), v.getUint16(o + 4), v.getUint16(o + 6), copy.subarray(o + 12, o + 12 + len)]);+ o += 12 + len;+ }+ return { w: v.getUint16(0), h: v.getUint16(2), patches };+ }++ async function paintWaiting() {+ painting = true;+ while (waiting.length) {+ const batch = waiting;+ waiting = [];+ const c = canvas(), ctx = c.getContext("2d");+ // A whole frame replaces everything before it.+ const lastFrame = batch.map(([k]) => k).lastIndexOf(FRAME);+ if (lastFrame >= 0) {+ const copy = batch[lastFrame][1];+ const img = copy.length > 4 ? await createImageBitmap(new Blob([copy.subarray(4)], { type: "image/jpeg" })).catch(() => null) : null;+ if (img) {+ if (c.width !== img.width || c.height !== img.height) { c.width = img.width; c.height = img.height; }+ ctx.drawImage(img, 0, 0);+ img.close();+ }+ }+ // Then the patches after it, in order, without those a later one covers.+ let size = null, patches = [];+ for (const [k, copy] of batch.slice(lastFrame + 1)) {+ if (k !== TILES) continue;+ const t = patchesOf(copy);+ if (!size || size.w !== t.w || size.h !== t.h) { size = t; patches = []; }+ const covers = (a, b) => a[0] <= b[0] && a[1] <= b[1] && a[0] + a[2] >= b[0] + b[2] && a[1] + a[3] >= b[1] + b[3];+ patches = patches.filter((old) => !t.patches.some((p) => covers(p, old)));+ patches.push(...t.patches);+ }+ if (size) {+ if (c.width !== size.w || c.height !== size.h) { c.width = size.w; c.height = size.h; }+ const images = await Promise.all(patches.map((p) => createImageBitmap(new Blob([p[4]], { type: "image/jpeg" })).catch(() => null)));+ images.forEach((img, i) => { if (img) { ctx.drawImage(img, patches[i][0], patches[i][1]); img.close(); } });+ }+ $("screen-wait").hidden = true;+ }+ painting = false;+ }++ function input(event) {+ if (!state.canControl || !state.desktop || !state.dc || state.dc.readyState !== "open") return;+ state.dc.send(frame(state.desktop, INPUT, enc.encode(JSON.stringify(event))));+ }++ // Where the pointer is, in the screen's own pixels.+ function at(e) {+ const c = canvas(), r = c.getBoundingClientRect();+ if (!r.width || !r.height) return null;+ const x = ((e.clientX - r.left) / r.width) * c.width, y = ((e.clientY - r.top) / r.height) * c.height;+ return x < 0 || y < 0 || x >= c.width || y >= c.height ? null : { x, y };+ }++ // X keysyms: the key's place for letters, digits and signs (Shift goes+ // separately), its name for the rest.+ const codes = { Minus: "-", Equal: "=", BracketLeft: "[", BracketRight: "]", Backslash: "\\", Semicolon: ";", Quote: "'", Comma: ",", Period: ".", Slash: "/", Backquote: "`", Space: " " };+ const named = {+ Enter: 0xff0d, Backspace: 0xff08, Tab: 0xff09, Escape: 0xff1b, Delete: 0xffff, Insert: 0xff63, Home: 0xff50, End: 0xff57,+ PageUp: 0xff55, PageDown: 0xff56, ArrowLeft: 0xff51, ArrowUp: 0xff52, ArrowRight: 0xff53, ArrowDown: 0xff54,+ Shift: 0xffe1, Control: 0xffe3, Alt: 0xffe9, CapsLock: 0xffe5,+ };+ function keysym(e) {+ if (/^Key[A-Z]$/.test(e.code)) return e.code.charCodeAt(3) + 32;+ if (/^Digit[0-9]$/.test(e.code)) return e.code.charCodeAt(5);+ if (codes[e.code]) return codes[e.code].charCodeAt(0);+ // ⌘ is ⌘ on a Mac; elsewhere it works as Ctrl (copy, paste, ... as on a Mac).+ if (e.key === "Meta") return state.info && state.info.mac ? 0xffeb : 0xffe3;+ if (/^F([1-9]|1[0-2])$/.test(e.key)) return 0xffbe + Number(e.key.slice(1)) - 1;+ if (named[e.key]) return named[e.key];+ return e.key.length === 1 && e.key.charCodeAt(0) <= 0xff ? e.key.charCodeAt(0) : null;+ }++ const held = { keys: new Set(), buttons: new Set() };+ function letGo() {+ for (const k of held.keys) input({ t: "key", keysym: k, down: false });+ for (const b of held.buttons) input({ t: "button", b, down: false, x: 0, y: 0 });+ held.keys.clear();+ held.buttons.clear();+ }++ function wireScreen() {+ // How it looks: smoother and sharper takes more of the connection. The+ // choice is kept for next time; a new stream starts at it.+ try { const q = localStorage.getItem("muxin-quality"); if (q && [...$("quality").options].some((o) => o.value === q)) $("quality").value = q; } catch (_) {}+ $("quality").addEventListener("change", () => {+ try { localStorage.setItem("muxin-quality", $("quality").value); } catch (_) {}+ if (!state.desktop) return;+ closeChannel(state.desktop);+ state.desktop = 0;+ showDesktop();+ });+ const c = canvas();+ let lastMove = 0, rest = 0;+ c.addEventListener("mousemove", (e) => {+ const p = at(e);+ if (!p || performance.now() - lastMove < 8) return;+ lastMove = performance.now();+ input({ t: "move", x: p.x, y: p.y });+ });+ const button = (e, down) => {+ const b = { 0: 1, 1: 2, 2: 3 }[e.button];+ if (!b || !state.canControl) return;+ e.preventDefault();+ if (down) c.focus();+ const p = at(e) || { x: 0, y: 0 };+ if (down) held.buttons.add(b); else held.buttons.delete(b);+ input({ t: "button", b, down, x: p.x, y: p.y });+ };+ c.addEventListener("mousedown", (e) => button(e, true));+ window.addEventListener("mouseup", (e) => { if (held.buttons.size) button(e, false); });+ c.addEventListener("contextmenu", (e) => { if (state.canControl) e.preventDefault(); });+ c.addEventListener("wheel", (e) => {+ const p = at(e);+ if (!p || !state.canControl) return;+ e.preventDefault();+ rest += e.deltaMode === 1 ? e.deltaY : e.deltaY / 40;+ const notches = Math.trunc(rest);+ if (notches) { rest -= notches; input({ t: "scroll", dy: notches, dx: 0, x: p.x, y: p.y }); }+ }, { passive: false });+ const key = (e, down) => {+ if (!state.canControl) return;+ const sym = keysym(e);+ if (sym == null) return;+ e.preventDefault();+ if (down) held.keys.add(sym); else held.keys.delete(sym);+ input({ t: "key", keysym: sym, down });+ };+ c.addEventListener("keydown", (e) => key(e, true));+ c.addEventListener("keyup", (e) => key(e, false));+ c.addEventListener("blur", letGo);+ window.addEventListener("blur", letGo);+ wireTouch(c);+ }++ // Phones and tablets: a tap clicks, a long press right-clicks, one finger+ // drags (the mouse held down), two fingers scroll. While watching only,+ // touch scrolls and zooms the page as usual.+ function wireTouch(c) {+ let start = null, dragging = false, long = 0, twoY = null, rest = 0;+ const point = (t) => at({ clientX: t.clientX, clientY: t.clientY });+ const clickAt = (p, b) => {+ input({ t: "move", x: p.x, y: p.y });+ input({ t: "button", b, down: true, x: p.x, y: p.y });+ input({ t: "button", b, down: false, x: p.x, y: p.y });+ };+ c.addEventListener("touchstart", (e) => {+ if (!state.canControl) return;+ e.preventDefault();+ clearTimeout(long);+ if (e.touches.length === 2) {+ start = null;+ twoY = (e.touches[0].clientY + e.touches[1].clientY) / 2;+ return;+ }+ const t = e.touches[0], p = point(t);+ if (!p) return;+ start = { x: t.clientX, y: t.clientY, p, done: false };+ dragging = false;+ long = setTimeout(() => {+ if (start && !dragging) { clickAt(start.p, 3); start.done = true; }+ }, 550);+ }, { passive: false });+ c.addEventListener("touchmove", (e) => {+ if (!state.canControl) return;+ e.preventDefault();+ if (e.touches.length === 2 && twoY != null) {+ const y = (e.touches[0].clientY + e.touches[1].clientY) / 2;+ const p = point(e.touches[0]) || { x: 0, y: 0 };+ rest += (twoY - y) / 24;+ twoY = y;+ const notches = Math.trunc(rest);+ if (notches) { rest -= notches; input({ t: "scroll", dy: notches, dx: 0, x: p.x, y: p.y }); }+ return;+ }+ if (!start || start.done) return;+ const t = e.touches[0], p = point(t);+ if (!p) return;+ if (!dragging && Math.hypot(t.clientX - start.x, t.clientY - start.y) > 10) {+ dragging = true;+ clearTimeout(long);+ input({ t: "move", x: start.p.x, y: start.p.y });+ input({ t: "button", b: 1, down: true, x: start.p.x, y: start.p.y });+ held.buttons.add(1);+ }+ if (dragging) input({ t: "move", x: p.x, y: p.y });+ }, { passive: false });+ const end = (e) => {+ if (!state.canControl) return;+ clearTimeout(long);+ if (e.touches.length) return;+ twoY = null;+ if (!start) return;+ const t = e.changedTouches[0], p = point(t) || start.p;+ if (dragging) {+ input({ t: "button", b: 1, down: false, x: p.x, y: p.y });+ held.buttons.delete(1);+ } else if (!start.done) {+ clickAt(start.p, 1);+ }+ start = null;+ dragging = false;+ };+ c.addEventListener("touchend", end);+ c.addEventListener("touchcancel", end);++ // A keyboard for touch screens: what's typed goes to the shared screen.+ const field = $("kbd-input");+ $("kbd").addEventListener("click", () => field.focus());+ field.addEventListener("input", (e) => {+ const text = e.data || field.value;+ if (text && state.canControl) input({ t: "text", s: text });+ field.value = "";+ });+ field.addEventListener("keydown", (e) => {+ const sym = { Enter: 0xff0d, Backspace: 0xff08, Tab: 0xff09, Escape: 0xff1b, ArrowLeft: 0xff51, ArrowUp: 0xff52, ArrowRight: 0xff53, ArrowDown: 0xff54 }[e.key];+ if (!sym || !state.canControl) return;+ e.preventDefault();+ input({ t: "key", keysym: sym, down: true });+ input({ t: "key", keysym: sym, down: false });+ });+ }++ function onChannel(channel, kind, body) {+ const ch = state.channels.get(channel);+ if (!ch) return;+ if (ch.kind === "desktop") {+ if (kind === TILES || kind === FRAME) paint(kind, body);+ else if (kind === CLOSE) {+ state.channels.delete(channel);+ state.desktop = 0;+ $("screen-wait").textContent = "Their screen stopped.";+ $("screen-wait").hidden = false;+ }+ return;+ }+ if (channel !== state.session) return;+ const machine = state.info && state.info.machine_share;+ if (kind === DATA) state.term.write(body);+ else if (kind === SIZE && body.length === 4) {+ const v = new DataView(body.buffer, body.byteOffset);+ state.term.resize(Math.max(10, v.getUint16(0)), Math.max(4, v.getUint16(2)));+ fitText();+ } else if (kind === EXIT || kind === CLOSE) {+ if (kind === CLOSE) { state.channels.delete(channel); state.session = 0; }+ if (!machine) return finish("The session ended", "");+ state.term.write("\r\n\x1b[2m[The session ended]\x1b[0m\r\n");+ }+ }++ // Frames that came in parts, per channel, until their last part.+ const pieces = new Map();+function onFrame(buf) {const bytes = new Uint8Array(buf);if (bytes.length < 5) return;const channel = new DataView(bytes.buffer, bytes.byteOffset).getUint32(0);const kind = bytes[4];- const body = bytes.subarray(5);- if (channel === SESSION) {- if (!state.term) return;- if (kind === DATA) state.term.write(body);- else if (kind === SIZE && body.length === 4) {- const v = new DataView(body.buffer, body.byteOffset);- state.term.resize(Math.max(10, v.getUint16(0)), Math.max(4, v.getUint16(2)));- } else if (kind === EXIT) finish("The session ended", "");- else if (kind === CLOSE) finish("The session ended", "");+ let body = bytes.subarray(5);+ if (kind === MORE) {+ const parts = pieces.get(channel) || [];+ parts.push(body);+ pieces.set(channel, parts);return;}- if (channel !== 0 || kind !== JSON_KIND) return;+ const parts = pieces.get(channel);+ if (parts) {+ pieces.delete(channel);+ parts.push(body);+ const whole = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let at = 0;+ for (const p of parts) { whole.set(p, at); at += p.length; }+ body = whole;+ }+ if (channel !== 0) return onChannel(channel, kind, body);+ if (kind !== JSON_KIND) return;let m;try { m = JSON.parse(dec.decode(body)); } catch (_) { return; }const clean = (s, n) => String(s || "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "").slice(0, n);+ const ports = (list) => (Array.isArray(list) ? list.slice(0, 32) : []).map((p) => ({ port: Number(p.port) || 0, name: clean(p.name, 60) })).filter((p) => p.port > 0);+ const desktop = (d) => (d === "view" || d === "control" ? d : "none");switch (m.event) {case "share":- showInfo({ title: clean(m.title, 120), agent: clean(m.agent, 40), machine: clean(m.machine, 80), by: clean(m.by, 80), can_type: !!m.can_type, ends_at: Number(m.ends_at) || 0 });+ showInfo({+ machine_share: m.kind === "machine", title: clean(m.title, 120), agent: clean(m.agent, 40), machine: clean(m.machine, 80), by: clean(m.by, 80),+ can_type: !!m.can_type, desktop: desktop(m.desktop), can_control: !!m.can_control, mac: !!m.mac, ports: ports(m.ports), ends_at: Number(m.ends_at) || 0,+ });break;case "waiting":$("wait-status").textContent = `Waiting for ${state.info ? state.info.by : "them"} to let you in…`;break;case "admitted":state.canType = !!m.can_type;- openTerminal();- send({ op: "watch", channel: SESSION });+ state.canControl = !!m.can_control;+ admitted();+ break;+ case "sessions":+ state.sessions = (Array.isArray(m.sessions) ? m.sessions.slice(0, 200) : []).map((s) => ({+ name: clean(s.name, 120), title: clean(s.title, 120), agent: clean(s.agent, 40), status: clean(s.status, 20), busy: !!s.busy,+ }));+ if (!state.showing) {+ const first = state.sessions.find((s) => s.status !== "exited");+ if (first) showSession(first.name);+ else if (state.info.desktop !== "none") showDesktop();+ else showEmpty(`No sessions are running on ${state.info.title}.`);+ }+ renderTabs();break;case "typing":- setTyping(!!m.allowed);+ state.canType = !!m.allowed;+ updateNote();+ break;+ case "control":+ state.canControl = !!m.allowed;+ if (!state.canControl) letGo();+ updateNote();break;+ case "access":+ state.info.desktop = desktop(m.desktop);+ state.info.ports = ports(m.ports);+ state.canControl = !!m.can_control;+ if (state.info.desktop === "none" && state.showing && state.showing.kind === "desktop") {+ const first = state.sessions.find((s) => s.status !== "exited");+ if (first) showSession(first.name); else showEmpty("They stopped sharing the screen.");+ }+ renderTabs();+ updateNote();+ break;+ case "refused": {+ const ch = state.channels.get(Number(m.channel));+ state.channels.delete(Number(m.channel));+ if (ch && ch.kind === "desktop") {+ state.desktop = 0;+ $("screen-wait").textContent = clean(m.error, 200);+ $("screen-wait").hidden = false;+ } else if (ch && Number(m.channel) === state.session) {+ state.session = 0;+ state.term.write(`\r\n\x1b[2m${clean(m.error, 200)}\x1b[0m\r\n`);+ }+ break;+ }case "denied":finish("You weren't let in", "Ask them for a new link if that wasn't meant to happen.");break;@@ -317,6 +785,7 @@try { localStorage.setItem("muxin-name", state.name); } catch (_) {}connect(ticket);});+ wireScreen();$("cancel").addEventListener("click", () => { send({ op: "bye" }); finish("You left", ""); });$("leave").addEventListener("click", () => { send({ op: "bye" }); finish("You left", ""); });}diff --git a/src/share/guest.rs b/src/share/guest.rsindex b188cdc..fe1ff73 100644--- a/src/share/guest.rs+++ b/src/share/guest.rs@@ -1,59 +1,139 @@//! Joining someone's share from Muxin: connect through the link's server,//! check that the answer comes from the share's own certificate, prove the-//! link, then watch (and type, when let) the session shared.+//! link, then open what's shared on channels of our own, as on a machine's+//! link: a session, the desktop, a server (forwarded to a port here).-use std::sync::Arc;-use std::sync::atomic::{AtomicBool, Ordering};+use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};use std::time::Duration;use serde_json::{Value, json};-use tokio::sync::mpsc;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::sync::{mpsc, oneshot};use webrtc::data_channel::DataChannel;use webrtc::peer_connection::{PeerConnection, RTCPeerConnectionState, RTCSessionDescription};+use super::host::{Desktop, Port};use super::rtc::{self, Event};use super::signal;use super::ticket::{Ticket, hex};-/// The channel the shared session arrives on.-const SESSION: u32 = 1;-/// What's shared, as its host describes it.#[derive(Clone, Debug, Default)]pub struct Info {+ /// A whole machine (its sessions, maybe its desktop and servers), not+ /// one session.+ pub whole_machine: bool,pub title: String,pub agent: String,pub machine: String,pub by: String,pub can_type: bool,+ pub desktop: Desktop,+ pub can_control: bool,+ /// May start, end and restart its sessions.+ pub can_manage: bool,+ /// The agent CLIs there, to start.+ pub agents: Vec<String>,+ pub ports: Vec<Port>,+ /// The machine is a Mac (its desktop's ⌘ stays ⌘).+ pub mac: bool,/// Unix seconds.pub ends_at: i64,}+/// One of a shared machine's sessions.+#[derive(Clone, Debug, PartialEq)]+pub struct Session {+ pub name: String,+ pub title: String,+ pub agent: String,+ /// "running" or "exited".+ pub status: String,+ /// Printed something in the last few seconds.+ pub busy: bool,+}+/// What happens, in order: the code to read out, what's shared, waiting,-/// let in (or not), then the session.+/// let in (or not), then what changes while in. What's opened arrives on its+/// own channel (`Joined::open`).#[derive(Debug)]pub enum Update {Code(String),Info(Info),Waiting,- Admitted { can_type: bool },+ Admitted { can_type: bool, can_control: bool, can_manage: bool },Denied,Typing(bool),- Output(Vec<u8>),- /// The session's size; draw at it.- Size(u16, u16),- /// The session ended (with its code).- Exited(Option<i32>),+ Control(bool),+ /// Starting and ending sessions allowed, or not.+ Manage(bool),+ /// The desktop or the servers shared changed.+ Access { desktop: Desktop, ports: Vec<Port> },+ /// A shared machine's sessions, when they change.+ Sessions(Vec<Session>),/// The share ended or the connection dropped, and why.Ended(String),}-/// A joined share: keys to send, and leaving.+/// A channel's frames: (kind, payload), then CLOSE.+pub type Frames = mpsc::UnboundedReceiver<(u8, Vec<u8>)>;++/// A server forwarded to a port on this computer.+struct Forward {+ port: u16,+ local: u16,+ task: tokio::task::JoinHandle<()>,+}++/// What a forwarded server sends waits while this much is on its way.+const QUEUED_MAX: usize = 8 << 20;++/// Frames to the host, in order, sent by one task. None is ever dropped+/// (a key, a mouse button let go); only a forwarded server's bytes wait while+/// too much is already queued.+#[derive(Clone)]+struct Out {+ tx: mpsc::UnboundedSender<Vec<u8>>,+ queued: Arc<AtomicUsize>,+}++impl Out {+ fn push(&self, frame: Vec<u8>) {+ self.queued.fetch_add(frame.len(), Ordering::Relaxed);+ let _ = self.tx.send(frame);+ }++ /// Like `push`, once there's room (false: the connection is gone).+ async fn push_paced(&self, frame: Vec<u8>) -> bool {+ while self.queued.load(Ordering::Relaxed) > QUEUED_MAX {+ if self.tx.is_closed() {+ return false;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ self.push(frame);+ !self.tx.is_closed()+ }+}++/// A joined share: open channels on it, send on them, leave.pub struct Joined {- dc: Arc<dyn DataChannel>,+ out: Out,pc: Arc<dyn PeerConnection>,- can_type: Arc<AtomicBool>,+ channels: Mutex<HashMap<u32, mpsc::UnboundedSender<(u8, Vec<u8>)>>>,+ /// Requests waiting for the host's answer, by channel.+ replies: Mutex<HashMap<u32, oneshot::Sender<Result<Value, String>>>>,+ /// Calls (start, end, restart) waiting for theirs, by number.+ calls: Mutex<HashMap<u64, oneshot::Sender<Result<String, String>>>>,+ next: AtomicU32,+ can_type: AtomicBool,+ can_control: AtomicBool,+ can_manage: AtomicBool,+ forwards: Mutex<Vec<Forward>>,+ /// One server opened here at a time (a double click opens it once).+ forwarding: tokio::sync::Mutex<()>,/// Where sending runs (keys can come from any thread, the window's included).runtime: tokio::runtime::Handle,}@@ -63,25 +143,162 @@ impl Joined {self.can_type.load(Ordering::Relaxed)}- /// Keys for the session (dropped unless the host lets this guest type;- /// the host drops them too).- pub fn send_keys(&self, keys: &[u8]) {- if !self.can_type() {- return;+ pub fn can_control(&self) -> bool {+ self.can_control.load(Ordering::Relaxed)+ }++ #[cfg(test)]+ pub fn can_manage(&self) -> bool {+ self.can_manage.load(Ordering::Relaxed)+ }++ /// Asks the host to start a session (`{"op": "start", "agent"}`), or end+ /// or restart one (`{"op": "end" | "restart", "session"}`): the+ /// session's name, or why not.+ pub async fn call(&self, mut req: Value) -> Result<String, String> {+ let id = self.next.fetch_add(1, Ordering::Relaxed) as u64;+ let (tx, answer) = oneshot::channel();+ self.calls.lock().unwrap().insert(id, tx);+ req["req"] = json!(id);+ self.out.push(rtc::json_frame(&req));+ let answer = tokio::time::timeout(Duration::from_secs(60), answer).await;+ self.calls.lock().unwrap().remove(&id);+ match answer {+ Ok(Ok(r)) => r,+ Ok(Err(_)) => Err("The share ended.".into()),+ Err(_) => Err("No answer from the computer sharing it.".into()),}- let dc = self.dc.clone();- let frame = super::frame(SESSION, super::DATA, keys);- self.runtime.spawn(async move {- let _ = rtc::send(&dc, frame).await;+ }++ /// A shared machine's sessions now (they also come when they change).+ pub fn refresh_sessions(&self) {+ self.out.push(rtc::json_frame(&json!({ "op": "sessions" })));+ }++ /// Asks for something on a channel of its own: `{"op": "watch",+ /// "session"}`, `{"op": "desktop"}` or `{"op": "tcp", "port"}`. The+ /// host's answer, and the channel's frames.+ pub async fn open(&self, mut req: Value) -> Result<(u32, Value, Frames), String> {+ let channel = self.next.fetch_add(1, Ordering::Relaxed);+ let (tx, frames) = mpsc::unbounded_channel();+ let (reply_tx, reply) = oneshot::channel();+ self.channels.lock().unwrap().insert(channel, tx);+ self.replies.lock().unwrap().insert(channel, reply_tx);+ req["channel"] = json!(channel);+ self.out.push(rtc::json_frame(&req));+ // The host may first update the machine's agent, then wait up to 20s+ // for a desktop to start: give it that and more.+ let result = match tokio::time::timeout(Duration::from_secs(90), reply).await {+ Ok(Ok(r)) => r,+ Ok(Err(_)) => Err("The share ended.".into()),+ Err(_) => Err("No answer from the computer sharing it.".into()),+ };+ match result {+ Ok(reply) => Ok((channel, reply, frames)),+ Err(e) => {+ self.replies.lock().unwrap().remove(&channel);+ self.close(channel);+ Err(e)+ }+ }+ }++ /// A frame on one of our channels (the host drops what it doesn't allow:+ /// keys unless we may type, the mouse unless we may control).+ pub fn send(&self, channel: u32, kind: u8, payload: &[u8]) {+ self.out.push(super::frame(channel, kind, payload));+ }++ /// Keys for a session (dropped here too unless we may type).+ pub fn send_keys(&self, channel: u32, keys: &[u8]) {+ if self.can_type() {+ self.send(channel, super::DATA, keys);+ }+ }++ pub fn close(&self, channel: u32) {+ if self.channels.lock().unwrap().remove(&channel).is_some() {+ self.send(channel, super::CLOSE, &[]);+ }+ }++ /// Opens one of the shared servers on this computer: its port here (the+ /// same as there when it's free). Only this computer can reach it.+ pub async fn forward(self: &Arc<Self>, port: u16) -> Result<u16, String> {+ let _one_at_a_time = self.forwarding.lock().await;+ if let Some(f) = self.forwards.lock().unwrap().iter().find(|f| f.port == port) {+ return Ok(f.local);+ }+ let listener = match tokio::net::TcpListener::bind(("127.0.0.1", port)).await {+ Ok(l) => l,+ Err(_) => tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.map_err(|e| format!("Couldn't open a port here: {e}"))?,+ };+ let local = listener.local_addr().map_err(|e| e.to_string())?.port();+ let me = Arc::downgrade(self);+ let task = tokio::spawn(async move {+ while let Ok((stream, _)) = listener.accept().await {+ let Some(me) = me.upgrade() else { return };+ tokio::spawn(async move { me.serve_tcp(stream, port).await });+ }+ });+ self.forwards.lock().unwrap().push(Forward { port, local, task });+ Ok(local)+ }++ /// Where a shared server is open here, when it is.+ #[cfg(test)]+ pub fn forwarded(&self, port: u16) -> Option<u16> {+ self.forwards.lock().unwrap().iter().find(|f| f.port == port).map(|f| f.local)+ }++ /// One connection to a forwarded server, over a channel of its own.+ async fn serve_tcp(self: Arc<Self>, stream: tokio::net::TcpStream, port: u16) {+ let Ok((channel, _, mut frames)) = self.open(json!({ "op": "tcp", "port": port })).await else { return };+ let _ = stream.set_nodelay(true);+ let (mut reader, mut writer) = stream.into_split();+ let out = self.out.clone();+ // What the program here sends; the reply keeps coming after it's done.+ let up = tokio::spawn(async move {+ let mut buf = vec![0u8; 32 * 1024];+ loop {+ match reader.read(&mut buf).await {+ Ok(0) | Err(_) => break,+ Ok(n) => {+ if !out.push_paced(super::frame(channel, super::DATA, &buf[..n])).await {+ break;+ }+ }+ }+ }+ });+ while let Some((kind, bytes)) = frames.recv().await {+ if kind == super::CLOSE || (kind == super::DATA && writer.write_all(&bytes).await.is_err()) {+ break;+ }+ }+ up.abort();+ self.close(channel);+ }++ /// Stops forwarding servers no longer shared.+ fn keep_forwards(&self, ports: &[Port]) {+ self.forwards.lock().unwrap().retain(|f| {+ let keep = ports.iter().any(|p| p.port == f.port);+ if !keep {+ f.task.abort();+ }+ keep});}pub fn leave(&self) {- let (dc, pc) = (self.dc.clone(), self.pc.clone());+ let (out, pc) = (self.out.clone(), self.pc.clone());self.runtime.spawn(async move {- let _ = rtc::send(&dc, rtc::json_frame(&json!({ "op": "bye" }))).await;+ out.push(rtc::json_frame(&json!({ "op": "bye" })));+ tokio::time::sleep(Duration::from_millis(200)).await;let _ = pc.close().await;});+ self.keep_forwards(&[]);}}@@ -147,18 +364,55 @@ pub async fn join(link: &str, name: &str) -> Result<(Arc<Joined>, mpsc::Unboundelet _ = tx.send(Update::Code(ticket.code(&my_fp)));let hello = json!({ "op": "hello", "v": 1, "name": name, "client": "app", "proof": ticket.proof(&host_fp, &my_fp) });rtc::send(&dc, rtc::json_frame(&hello)).await?;- let joined = Arc::new(Joined { dc: dc.clone(), pc: pc.clone(), can_type: Arc::new(AtomicBool::new(false)), runtime: tokio::runtime::Handle::current() });- let can_type = joined.can_type.clone();+ let (to_host, mut outgoing) = mpsc::unbounded_channel::<Vec<u8>>();+ let out = Out { tx: to_host, queued: Arc::new(AtomicUsize::new(0)) };+ let (writer, queued) = (dc.clone(), out.queued.clone());+ tokio::spawn(async move {+ while let Some(f) = outgoing.recv().await {+ let n = f.len();+ let sent = rtc::send(&writer, f).await;+ queued.fetch_sub(n, Ordering::Relaxed);+ if sent.is_err() {+ break;+ }+ }+ });+ let joined = Arc::new(Joined {+ out,+ pc: pc.clone(),+ channels: Mutex::new(HashMap::new()),+ replies: Mutex::new(HashMap::new()),+ calls: Mutex::new(HashMap::new()),+ next: AtomicU32::new(1),+ can_type: AtomicBool::new(false),+ can_control: AtomicBool::new(false),+ can_manage: AtomicBool::new(false),+ forwards: Mutex::new(Vec::new()),+ forwarding: tokio::sync::Mutex::new(()),+ runtime: tokio::runtime::Handle::current(),+ });+ let j = joined.clone();tokio::spawn(async move {- let why = relay(&dc, &tx, &can_type, &mut events).await;+ let why = relay(&dc, &tx, &j, &mut events).await;+ // Everything open ends with it.+ j.channels.lock().unwrap().clear();+ for (_, r) in j.replies.lock().unwrap().drain() {+ let _ = r.send(Err(why.clone()));+ }+ for (_, r) in j.calls.lock().unwrap().drain() {+ let _ = r.send(Err(why.clone()));+ }+ j.keep_forwards(&[]);let _ = tx.send(Update::Ended(why));+ rtc::forget(&dc);let _ = pc.close().await;});Ok((joined, rx))}-/// The host's messages and the session, until it ends: why.-async fn relay(dc: &Arc<dyn DataChannel>, tx: &mpsc::UnboundedSender<Update>, can_type: &AtomicBool, events: &mut mpsc::UnboundedReceiver<Event>) -> String {+/// The host's messages and the channels' frames, until it ends: why.+async fn relay(dc: &Arc<dyn DataChannel>, tx: &mpsc::UnboundedSender<Update>, joined: &Joined, events: &mut mpsc::UnboundedReceiver<Event>) -> String {+ let mut pieces = rtc::Pieces::default();loop {let msg = tokio::select! {m = rtc::next_message(dc) => m,@@ -168,46 +422,102 @@ async fn relay(dc: &Arc<dyn DataChannel>, tx: &mpsc::UnboundedSender<Update>, ca},};let Some(msg) = msg else { return "The connection dropped.".into() };+ let Some(msg) = pieces.add(msg) else { continue };let Some((channel, kind, body)) = super::parse_frame(&msg) else { continue };- if channel == SESSION {- let _ = match kind {- super::DATA => tx.send(Update::Output(body.to_vec())),- super::SIZE if body.len() == 4 => tx.send(Update::Size(u16::from_be_bytes([body[0], body[1]]), u16::from_be_bytes([body[2], body[3]]))),- super::EXIT => tx.send(Update::Exited((body.len() == 4).then(|| i32::from_be_bytes([body[0], body[1], body[2], body[3]])))),- super::CLOSE => return "The session ended.".into(),- _ => Ok(()),- };+ if channel != 0 {+ let mut channels = joined.channels.lock().unwrap();+ if let Some(sink) = channels.get(&channel) {+ let _ = sink.send((kind, body.to_vec()));+ if kind == super::CLOSE {+ channels.remove(&channel);+ }+ }continue;}- if channel != 0 || kind != super::JSON {+ if kind != super::JSON {continue;}let m: Value = serde_json::from_slice(body).unwrap_or(Value::Null);- match m["event"].as_str().unwrap_or("") {+ let update = match m["event"].as_str().unwrap_or("") {"share" => {let info = Info {+ whole_machine: m["kind"] == "machine",title: text(&m["title"], 120),agent: text(&m["agent"], 40),machine: text(&m["machine"], 80),by: text(&m["by"], 80),can_type: m["can_type"].as_bool().unwrap_or(false),+ desktop: desktop(&m["desktop"]),+ can_control: m["can_control"].as_bool().unwrap_or(false),+ can_manage: m["can_manage"].as_bool().unwrap_or(false),+ agents: m["agents"].as_array().into_iter().flatten().take(16).map(|a| text(a, 20)).filter(|a| !a.is_empty()).collect(),+ ports: ports(&m["ports"]),+ mac: m["mac"].as_bool().unwrap_or(false),ends_at: m["ends_at"].as_i64().unwrap_or(0),};- let _ = tx.send(Update::Info(info));- }- "waiting" => {- let _ = tx.send(Update::Waiting);+ Update::Info(info)}+ "waiting" => Update::Waiting,"admitted" => {- let allowed = m["can_type"].as_bool().unwrap_or(false);- can_type.store(allowed, Ordering::Relaxed);- let _ = tx.send(Update::Admitted { can_type: allowed });- let _ = rtc::send(dc, rtc::json_frame(&json!({ "op": "watch", "channel": SESSION }))).await;+ let flag = |k: &str| m[k].as_bool().unwrap_or(false);+ let (can_type, can_control, can_manage) = (flag("can_type"), flag("can_control"), flag("can_manage"));+ joined.can_type.store(can_type, Ordering::Relaxed);+ joined.can_control.store(can_control, Ordering::Relaxed);+ joined.can_manage.store(can_manage, Ordering::Relaxed);+ Update::Admitted { can_type, can_control, can_manage }+ }+ "manage" => {+ let allowed = m["allowed"].as_bool().unwrap_or(false);+ joined.can_manage.store(allowed, Ordering::Relaxed);+ Update::Manage(allowed)+ }+ // Answers to `call`.+ "done" | "failed" => {+ let id = m["req"].as_u64().unwrap_or(0);+ if let Some(r) = joined.calls.lock().unwrap().remove(&id) {+ let _ = r.send(if m["event"] == "done" { Ok(text(&m["session"], 120)) } else { Err(text(&m["error"], 200)) });+ }+ continue;}"typing" => {let allowed = m["allowed"].as_bool().unwrap_or(false);- can_type.store(allowed, Ordering::Relaxed);- let _ = tx.send(Update::Typing(allowed));+ joined.can_type.store(allowed, Ordering::Relaxed);+ Update::Typing(allowed)+ }+ "control" => {+ let allowed = m["allowed"].as_bool().unwrap_or(false);+ joined.can_control.store(allowed, Ordering::Relaxed);+ Update::Control(allowed)+ }+ "access" => {+ let ports = ports(&m["ports"]);+ joined.keep_forwards(&ports);+ let can_control = m["can_control"].as_bool().unwrap_or(false);+ if joined.can_control.swap(can_control, Ordering::Relaxed) != can_control {+ let _ = tx.send(Update::Control(can_control));+ }+ Update::Access { desktop: desktop(&m["desktop"]), ports }+ }+ "sessions" => {+ let list = m["sessions"].as_array().into_iter().flatten().take(200);+ Update::Sessions(+ list.map(|s| Session {+ name: text(&s["name"], 120),+ title: text(&s["title"], 120),+ agent: text(&s["agent"], 40),+ status: text(&s["status"], 20),+ busy: s["busy"].as_bool().unwrap_or(false),+ })+ .collect(),+ )+ }+ // Answers to `open`.+ "watching" | "desktop" | "tcp" | "refused" => {+ let channel = m["channel"].as_u64().unwrap_or(0) as u32;+ if let Some(r) = joined.replies.lock().unwrap().remove(&channel) {+ let _ = r.send(if m["event"] == "refused" { Err(text(&m["error"], 200)) } else { Ok(m) });+ }+ continue;}"denied" => {let _ = tx.send(Update::Denied);@@ -222,11 +532,25 @@ async fn relay(dc: &Arc<dyn DataChannel>, tx: &mpsc::UnboundedSender<Update>, ca.into();}"error" => return text(&m["error"], 200),- _ => {}- }+ _ => continue,+ };+ let _ = tx.send(update);}}+fn desktop(v: &Value) -> Desktop {+ match v.as_str() {+ Some("view") => Desktop::View,+ Some("control") => Desktop::Control,+ _ => Desktop::None,+ }+}++fn ports(v: &Value) -> Vec<Port> {+ let list = v.as_array().into_iter().flatten().take(32);+ list.filter_map(|p| Some(Port { port: p["port"].as_u64().filter(|n| (1..=65535).contains(n))? as u16, name: text(&p["name"], 60), host: String::new() })).collect()+}+/// A string from the host, cut short and without control characters (it's/// shown, so it can't carry terminal escapes or run on forever).fn text(v: &Value, max: usize) -> String {diff --git a/src/share/host.rs b/src/share/host.rsindex adf5e1b..e877621 100644--- a/src/share/host.rs+++ b/src/share/host.rs@@ -1,12 +1,16 @@//! Hosting shares: each one waits for guests at the share server, checks-//! them, asks the user to let them in, then relays the one session shared.+//! them, asks the user to let them in, then relays what's shared: one+//! session, or a machine (its sessions, its desktop, servers the user+//! picked).//!//! The gateway is the security boundary. A guest never speaks the machine's-//! link protocol: it may say `hello`, `watch` and `bye`, and send keys on-//! the channel it watches, which reach the session only when the user let-//! that guest type. Its size is never applied (the session keeps the-//! user's), and nothing else it asks for (another session, a shell, files)-//! exists here.+//! link protocol. It may ask for what the share holds (`sessions`, `watch`,+//! `desktop`, `tcp`, `close`) on channels of its own, and what it sends on+//! them gets through only as the user allows: keys to a session when the+//! user lets it type, mouse and keyboard to the desktop when the user lets+//! it control, bytes to a server the user picked. Its size is never applied+//! (sessions keep the user's), and nothing else (a shell, files, other+//! ports) exists here.use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};@@ -34,36 +38,92 @@ const MAX_BAD_PROOFS: u32 = 20;const CHECK_IN: Duration = Duration::from_secs(2);/// The longest a share can last.pub const MAX_TTL: Duration = Duration::from_secs(7 * 24 * 3600);+/// Channels one guest can have open at once (sessions, the desktop, servers).+const MAX_CHANNELS: usize = 32;+/// How often a machine share's guests hear about its sessions.+const SESSIONS_EVERY: Duration = Duration::from_secs(3);-/// What's shared: one session.+/// Frame kinds of the desktop (agent/src/desktop.rs).+pub const FRAME: u8 = 20;+pub const INPUT: u8 = 21;+pub const TILES: u8 = 23;++/// What's shared: one session, or (`session_id` empty) a machine.#[derive(Clone, Debug, Serialize)]pub struct Target {- /// `<machine>/<session>`.+ /// `<machine>/<session>`; empty for a machine.pub session_id: String,pub machine_id: String,/// The session's name on the machine.pub name: String,+ /// The session's title, or the machine's name.pub title: String,- /// "claude", "codex", "shell"...+ /// "claude", "codex", "shell"...; empty for a machine.pub agent: String,pub machine_name: String,+ /// The machine's platform ("darwin-arm64"), for its desktop's keys.+ pub platform: String,/// Who shares it, as guests see it.pub by: String,}-#[derive(Clone, Copy, Debug)]+impl Target {+ pub fn is_machine(&self) -> bool {+ self.session_id.is_empty()+ }+}++/// What guests can do with a machine's desktop.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum Desktop {+ #[default]+ None,+ View,+ Control,+}++/// A server on the machine guests can open.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]+pub struct Port {+ pub port: u16,+ /// What it is ("Checkout dev"), as the user knows it.+ pub name: String,+ /// Where the machine's agent connects for it (127.0.0.1 when empty).+ #[serde(skip)]+ pub host: String,+}++#[derive(Clone, Debug)]pub struct Options {/// Ask before letting each guest in.pub approve: bool,- /// New guests may type.+ /// Guests may type in sessions.pub can_type: bool,+ /// Guests may start, end and restart a machine's sessions (only people+ /// let in, who may type): anything runs there, as the sharer.+ pub manage: bool,+ /// A machine's desktop.+ pub desktop: Desktop,+ /// A machine's servers.+ pub ports: Vec<Port>,pub ttl: Duration,}-/// Where the shared session's machine is reached.+/// Where the shared machine is reached.#[async_trait::async_trait]pub trait Source: Send + Sync + 'static {async fn link(&self) -> Result<Arc<Link>, String>;++ /// Starts a session there, with `agent` ("shell", "claude", ...) in its+ /// home folder: its name.+ async fn start(&self, agent: &str) -> Result<String, String>;++ /// Ends a session there (`restart`: starts its program again).+ async fn stop(&self, name: &str, restart: bool) -> Result<(), String>;++ /// The agent CLIs there ("claude", "codex", ...).+ fn agents(&self) -> Vec<String>;}/// The machine through Muxin's engine: its agent up to date, then its link.@@ -79,6 +139,22 @@ impl Source for EngineSource {crate::fleet::sessions::agent::ensure(&spec, probe.as_ref()).await?;crate::fleet::link::get(&spec).await.ok_or_else(|| format!("Can't reach {} right now.", spec.name))}++ async fn start(&self, agent: &str) -> Result<String, String> {+ let req = crate::fleet::sessions::StartSession { machine_id: self.machine_id.clone(), agent: agent.into(), cwd: "~".into(), cols: 120, rows: 36, ..Default::default() };+ let info = self.engine.start_session(req).await?;+ Ok(info.id.split_once('/').map(|(_, n)| n.to_string()).unwrap_or(info.id))+ }++ async fn stop(&self, name: &str, restart: bool) -> Result<(), String> {+ use crate::fleet::sessions::Control;+ let id = format!("{}/{name}", self.machine_id);+ self.engine.control_session(&id, if restart { Control::Restart } else { Control::Stop }).await.map(|_| ())+ }++ fn agents(&self) -> Vec<String> {+ self.engine.current().machines.iter().find(|m| m.id == self.machine_id).map(|m| m.agents.clone()).unwrap_or_default()+ }}/// A guest, as the UI shows it.@@ -92,6 +168,10 @@ pub struct GuestView {/// "waiting" (for the user to let them in) or "in".pub state: String,pub can_type: bool,+ /// Uses the desktop's mouse and keyboard.+ pub can_control: bool,+ /// Starts and ends sessions.+ pub can_manage: bool,/// "direct" or "relay", once known.pub path: String,}@@ -104,9 +184,14 @@ pub struct ShareView {pub target: Target,pub approve: bool,pub can_type: bool,+ pub manage: bool,+ pub desktop: Desktop,+ pub ports: Vec<Port>,/// Unix seconds.pub ends_at: i64,pub guests: Vec<GuestView>,+ /// Why the machine couldn't be reached for a guest, until it can.+ pub problem: Option<String>,}struct Guest {@@ -119,6 +204,8 @@ struct Guest {#[derive(Clone, Copy, PartialEq)]struct Control {can_type: bool,+ can_control: bool,+ can_manage: bool,/// Why the guest is being let go.end: Option<&'static str>,}@@ -134,15 +221,24 @@ struct Share {target: Target,source: Arc<dyn Source>,options: Mutex<Options>,+ /// Bumps when the desktop or servers shared change.+ access: watch::Sender<u64>,ends_at: Mutex<SystemTime>,guests: Mutex<HashMap<u64, Arc<Guest>>>,stop: watch::Sender<Option<&'static str>>,bad_proofs: Mutex<u32>,+ /// Why the machine couldn't be reached for a guest (the sharer sees it;+ /// guests hear only that it can't be reached).+ problem: Mutex<Option<String>>,}impl Share {+ fn options(&self) -> Options {+ self.options.lock().unwrap().clone()+ }+fn view(&self) -> ShareView {- let o = *self.options.lock().unwrap();+ let o = self.options();let mut guests: Vec<GuestView> = self.guests.lock().unwrap().values().map(|g| g.view.lock().unwrap().clone()).collect();guests.sort_by_key(|g| g.id);ShareView {@@ -151,23 +247,59 @@ impl Share {target: self.target.clone(),approve: o.approve,can_type: o.can_type,+ manage: o.manage,+ desktop: o.desktop,+ ports: o.ports,ends_at: unix(*self.ends_at.lock().unwrap()),guests,+ problem: self.problem.lock().unwrap().clone(),+ }+ }++ /// The machine, for a guest. When it can't be reached, why goes to the+ /// sharer, and the guest hears only that (not this computer's paths or+ /// fixes that are the sharer's to make).+ async fn machine(&self) -> Result<Arc<Link>, String> {+ let result = self.source.link().await;+ let problem = result.as_ref().err().cloned();+ let news = {+ let mut p = self.problem.lock().unwrap();+ let news = *p != problem;+ *p = problem;+ news+ };+ if news {+ changed();}+ result.map_err(|e| {+ tracing::warn!("share: can't reach {}: {e}", self.target.machine_name);+ format!("{} can't be reached from {}'s computer right now.", self.target.machine_name, self.target.by)+ })}fn ends_in(&self) -> Duration {self.ends_at.lock().unwrap().duration_since(SystemTime::now()).unwrap_or(Duration::ZERO)}- fn info(&self, can_type: bool) -> Value {+ /// What's shared, as the guest hears it (`control`: this guest's own).+ fn info(&self, control: &Control) -> Value {+ let o = self.options();json!({"event": "share",+ "kind": if self.target.is_machine() { "machine" } else { "session" },"title": self.target.title,"agent": self.target.agent,"machine": self.target.machine_name,"by": self.target.by,- "can_type": can_type,+ "can_type": control.can_type,+ "desktop": o.desktop,+ "can_control": control.can_control,+ "can_manage": control.can_manage,+ // What can be started there (with `can_manage`).+ "agents": if self.target.is_machine() { self.source.agents() } else { Vec::new() },+ // A Mac's ⌘ stays ⌘ on its desktop.+ "mac": self.target.platform.starts_with("darwin"),+ "ports": o.ports,"ends_at": unix(*self.ends_at.lock().unwrap()),})}@@ -202,7 +334,7 @@ pub fn subscribe() -> watch::Receiver<u64> {/// Every share running.pub fn list() -> Vec<ShareView> {let mut all: Vec<ShareView> = registry().shares.lock().unwrap().values().map(|s| s.view()).collect();- all.sort_by(|a, b| a.target.session_id.cmp(&b.target.session_id).then(a.id.cmp(&b.id)));+ all.sort_by(|a, b| a.target.machine_id.cmp(&b.target.machine_id).then(a.target.session_id.cmp(&b.target.session_id)).then(a.id.cmp(&b.id)));all}@@ -214,8 +346,9 @@ fn guest(share: &str, guest: u64) -> Option<Arc<Guest>> {find(share)?.guests.lock().unwrap().get(&guest).cloned()}-/// Starts sharing a session; the view carries the link to give out. Runs-/// on the current Tokio runtime until stopped, expired, or the app quits.+/// Starts sharing a session or a machine; the view carries the link to give+/// out. Runs on the current Tokio runtime until stopped, expired, or the+/// app quits.pub async fn start(server: &str, target: Target, options: Options, source: Arc<dyn Source>) -> Result<ShareView, String> {let (cert, fingerprint) = rtc::certificate()?;let ticket = Ticket::new(server, fingerprint)?;@@ -224,6 +357,10 @@ pub async fn start(server: &str, target: Target, options: Options, source: Arc<d// The first check-in: the server answers, and keeps the room for us.server.check_in(&ticket.room(), &key).await.map_err(|e| e.to_string())?;let ttl = options.ttl.min(MAX_TTL);+ // Only a machine has a desktop, servers and sessions to start; starting+ // them is for people let in, who may type.+ let manage = options.manage && options.approve && options.can_type && target.is_machine();+ let options = if target.is_machine() { Options { ttl, manage, ..options } } else { Options { ttl, manage, desktop: Desktop::None, ports: Vec::new(), ..options } };let share = Arc::new(Share {ticket,server,@@ -232,11 +369,13 @@ pub async fn start(server: &str, target: Target, options: Options, source: Arc<dcert,target,source,- options: Mutex::new(Options { ttl, ..options }),+ options: Mutex::new(options),+ access: watch::channel(0).0,ends_at: Mutex::new(SystemTime::now() + ttl),guests: Mutex::new(HashMap::new()),stop: watch::channel(None).0,bad_proofs: Mutex::new(0),+ problem: Mutex::new(None),});registry().shares.lock().unwrap().insert(share.ticket.room(), share.clone());changed();@@ -280,8 +419,59 @@ pub fn remove(share: &str, guest_id: u64) {/// Lets a guest type, or not (right away).pub fn set_typing(share: &str, guest_id: u64, allowed: bool) {if let Some(g) = guest(share, guest_id) {- g.control.send_modify(|c| c.can_type = allowed);- g.view.lock().unwrap().can_type = allowed;+ // No typing, no starting sessions either.+ g.control.send_modify(|c| {+ c.can_type = allowed;+ c.can_manage &= allowed;+ });+ let mut v = g.view.lock().unwrap();+ v.can_type = allowed;+ v.can_manage &= allowed;+ drop(v);+ changed();+ }+}++/// Lets a guest start, end and restart sessions, or not (one who may type,+/// on a machine share).+pub fn set_managing(share: &str, guest_id: u64, allowed: bool) {+ let Some(s) = find(share) else { return };+ if let Some(g) = guest(share, guest_id) {+ let allowed = allowed && s.target.is_machine() && g.view.lock().unwrap().can_type;+ g.control.send_modify(|c| c.can_manage = allowed);+ g.view.lock().unwrap().can_manage = allowed;+ changed();+ }+}++/// Whether guests let in can start, end and restart sessions (those who may+/// type), for a machine share already going.+pub fn set_manage(id: &str, manage: bool) {+ let Some(s) = find(id) else { return };+ let manage = {+ let mut o = s.options.lock().unwrap();+ o.manage = manage && o.approve && o.can_type && s.target.is_machine();+ o.manage+ };+ for g in s.guests.lock().unwrap().values() {+ let mut v = g.view.lock().unwrap();+ if v.state == "in" {+ let allowed = manage && v.can_type;+ v.can_manage = allowed;+ g.control.send_modify(|c| c.can_manage = allowed);+ }+ }+ changed();+}++/// Lets a guest use the desktop's mouse and keyboard, or not (only while+/// the share lets guests control it at all).+pub fn set_control(share: &str, guest_id: u64, allowed: bool) {+ let Some(s) = find(share) else { return };+ let allowed = allowed && s.options().desktop == Desktop::Control;+ if let Some(g) = guest(share, guest_id) {+ g.control.send_modify(|c| c.can_control = allowed);+ g.view.lock().unwrap().can_control = allowed;changed();}}@@ -292,11 +482,13 @@ pub fn set_typing(share: &str, guest_id: u64, allowed: bool) {pub fn set_options(id: &str, approve: bool, can_type: bool) {let Some(s) = find(id) else { return };let can_type = can_type && approve;- {+ let manage = {let mut o = s.options.lock().unwrap();o.approve = approve;o.can_type = can_type;- }+ o.manage &= can_type;+ o.manage+ };for g in s.guests.lock().unwrap().values() {let waiting = g.view.lock().unwrap().state == "waiting";if waiting {@@ -305,12 +497,42 @@ pub fn set_options(id: &str, approve: bool, can_type: bool) {}continue;}- g.control.send_modify(|c| c.can_type = can_type);- g.view.lock().unwrap().can_type = can_type;+ g.control.send_modify(|c| {+ c.can_type = can_type;+ c.can_manage = manage;+ });+ let mut v = g.view.lock().unwrap();+ v.can_type = can_type;+ v.can_manage = manage;}changed();}+/// What a machine share's guests can do with its desktop, and which of its+/// servers they can open: guests in follow it right away. Using the desktop+/// is then given to each person (set_control).+pub fn set_access(id: &str, desktop: Desktop, ports: Vec<Port>) {+ let Some(s) = find(id) else { return };+ if !s.target.is_machine() {+ return;+ }+ {+ let mut o = s.options.lock().unwrap();+ o.desktop = desktop;+ o.ports = ports;+ }+ // Using the desktop is given person by person (set_control); a desktop+ // no longer under control takes it back from everyone.+ if desktop != Desktop::Control {+ for g in s.guests.lock().unwrap().values() {+ g.control.send_modify(|c| c.can_control = false);+ g.view.lock().unwrap().can_control = false;+ }+ }+ s.access.send_modify(|n| *n += 1);+ changed();+}+/// Ends a share this long from now (a week at most).pub fn set_ends_in(id: &str, ttl: Duration) {if let Some(s) = find(id) {@@ -415,7 +637,9 @@ async fn connect_guest(share: Arc<Share>, id: String, offer: String, ice: Value)share.connecting.fetch_sub(1, Ordering::Relaxed);let Some((pc, dc, events)) = connected else { return };let host_fp = hex(&share.ticket.fingerprint);+ let dc_of_guest = dc.clone();run_guest(&share, &pc, dc, &host_fp, &guest_fp, events).await;+ rtc::forget(&dc_of_guest);let _ = pc.close().await;}@@ -425,8 +649,10 @@ async fn run_guest(share: &Arc<Share>, pc: &Arc<dyn PeerConnection>, dc: Arc<dynlet (msg_tx, mut from_guest) = mpsc::unbounded_channel::<Vec<u8>>();let reader = dc.clone();tokio::spawn(async move {+ let mut pieces = rtc::Pieces::default();while let Some(m) = rtc::next_message(&reader).await {- if msg_tx.send(m).is_err() {+ let Some(frame) = pieces.add(m) else { continue };+ if msg_tx.send(frame).is_err() {break;}}@@ -447,9 +673,13 @@ async fn run_guest(share: &Arc<Share>, pc: &Arc<dyn PeerConnection>, dc: Arc<dynrtc::flush(&dc).await;return;}- let options = *share.options.lock().unwrap();+ let options = share.options();let id = registry().next_guest.fetch_add(1, Ordering::Relaxed) + 1;let client = if hello["client"] == "browser" { "browser" } else { "app" };+ // Only someone the user let in types, or controls the desktop.+ // The desktop's mouse and keyboard: only for someone the user picks (set_control).+ let can_control = false;+ let can_manage = options.manage;let view = GuestView {id,name: clean_name(hello["name"].as_str().unwrap_or("")),@@ -457,13 +687,15 @@ async fn run_guest(share: &Arc<Share>, pc: &Arc<dyn PeerConnection>, dc: Arc<dynclient: client.into(),state: if options.approve { "waiting" } else { "in" }.into(),can_type: options.can_type,+ can_control,+ can_manage,path: String::new(),};let (decide_tx, decide_rx) = oneshot::channel();let guest = Arc::new(Guest {view: Mutex::new(view),decide: Mutex::new(options.approve.then_some(decide_tx)),- control: watch::channel(Control { can_type: options.can_type, end: None }).0,+ control: watch::channel(Control { can_type: options.can_type, can_control, can_manage, end: None }).0,});share.guests.lock().unwrap().insert(id, guest.clone());changed();@@ -476,7 +708,7 @@ async fn run_guest(share: &Arc<Share>, pc: &Arc<dyn PeerConnection>, dc: Arc<dyn}});- let result = admitted(share, &guest, &dc, decide_rx, options, &mut from_guest, &mut events).await;+ let result = admitted(share, &guest, &dc, decide_rx, options.approve, &mut from_guest, &mut events).await;if let Err(why) = result {let _ = rtc::send(&dc, rtc::json_frame(&json!({ "event": "ended", "why": why }))).await;rtc::flush(&dc).await;@@ -485,20 +717,21 @@ async fn run_guest(share: &Arc<Share>, pc: &Arc<dyn PeerConnection>, dc: Arc<dynchanged();}-/// Lets the guest in (asking first when the share says so), then relays-/// the session until something ends it: Err(why) to tell the guest.+/// Lets the guest in (asking first when the share says so), then serves+/// what it asks for until something ends it: Err(why) to tell the guest.async fn admitted(share: &Arc<Share>,guest: &Arc<Guest>,dc: &Arc<dyn DataChannel>,decide: oneshot::Receiver<bool>,- options: Options,+ approve: bool,from_guest: &mut mpsc::UnboundedReceiver<Vec<u8>>,events: &mut mpsc::UnboundedReceiver<Event>,) -> Result<(), &'static str> {let mut control = guest.control.subscribe();- rtc::send(dc, rtc::json_frame(&share.info(options.can_type))).await.map_err(|_| "gone")?;- if options.approve {+ let first = *control.borrow();+ rtc::send(dc, rtc::json_frame(&share.info(&first))).await.map_err(|_| "gone")?;+ if approve {rtc::send(dc, rtc::json_frame(&json!({ "event": "waiting" }))).await.map_err(|_| "gone")?;let mut decide = decide;let yes = loop {@@ -517,125 +750,608 @@ async fn admitted(guest.view.lock().unwrap().state = "in".into();changed();}- let can_type = control.borrow().can_type;- rtc::send(dc, rtc::json_frame(&json!({ "event": "admitted", "can_type": can_type }))).await.map_err(|_| "gone")?;+ let now = *control.borrow();+ rtc::send(dc, rtc::json_frame(&json!({ "event": "admitted", "can_type": now.can_type, "can_control": now.can_control, "can_manage": now.can_manage }))).await.map_err(|_| "gone")?;- // The session, once the guest asks for it.- let mut watching: Option<Watching> = None;+ let mut open = Open::new(share, dc);+ let mut access = share.access.subscribe();+ // A machine's sessions, sent as they change, by a task of their own (the+ // machine may be slow to answer; keys shouldn't wait for it).+ let (refresh, refreshes) = mpsc::unbounded_channel::<()>();+ let feed = share.target.is_machine().then(|| tokio::spawn(sessions_feed(share.clone(), dc.clone(), refreshes)));+ let mut last = now;let result = loop {- let session = async {- match watching.as_mut() {- Some(w) => w.frames.recv().await,- None => std::future::pending().await,- }- };tokio::select! {m = from_guest.recv() => {let Some(m) = m else { break Ok(()) };+ let c = *control.borrow();match super::parse_frame(&m) {Some((0, super::JSON, body)) => {let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null);- match req["op"].as_str().unwrap_or("") {- "watch" => {- let channel = req["channel"].as_u64().filter(|c| (1..1 << 20).contains(c)).unwrap_or(1) as u32;- if let Some(w) = watching.take() {- w.close();- }- let can_type = control.borrow().can_type;- match watch_session(share, channel, can_type).await {- Ok(w) => watching = Some(w),- Err(e) => {- let _ = rtc::send(dc, rtc::error_frame(&e)).await;- }- }- }- "bye" => break Ok(()),- _ => {}+ if req["op"] == "bye" {+ break Ok(());}- }- // Keys, only from a guest the user lets type.- Some((channel, super::DATA, keys)) => {- if let Some(w) = watching.as_ref().filter(|w| w.guest_channel == channel && w.can_type) {- w.link.send(w.link_channel, crate::fleet::link::DATA, keys);+ if req["op"] == "sessions" {+ let _ = refresh.send(());+ continue;+ }+ if matches!(req["op"].as_str(), Some("start" | "end" | "restart")) {+ // Answered when it's done, then the sessions as they are.+ let (share, dc, refresh) = (share.clone(), dc.clone(), refresh.clone());+ tokio::spawn(async move {+ let reply = manage(&share, &req, &c).await;+ let _ = rtc::send(&dc, rtc::json_frame(&reply)).await;+ let _ = refresh.send(());+ });+ continue;}+ open.request(&req, &c);}- _ => {}+ Some((channel, kind, payload)) => open.pass(channel, kind, payload, &c),+ None => {}}}- f = session => {- let w = watching.as_ref().expect("watching");- match f {- Some((kind, bytes)) if [super::DATA, super::SIZE, super::EXIT].contains(&kind) => {- if rtc::send(dc, super::frame(w.guest_channel, kind, &bytes)).await.is_err() {- break Ok(());- }- }- Some(_) => {}- None => {- let channel = w.guest_channel;- watching = None;- let _ = rtc::send(dc, super::frame(channel, super::CLOSE, &[])).await;- }+ o = open.opened.1.recv() => {+ // A channel the guest asked for, opened on the machine (or not).+ let Some(o) = o else { continue };+ open.landed(o).await;+ }+ p = open.ended.1.recv() => {+ // A channel ended on the machine's side, or the guest fell too+ // far behind to keep.+ let Some((channel, generation, gone)) = p else { continue };+ if gone {+ break Ok(());}+ if open.channels.get(&channel).is_some_and(|j| j.generation == generation) {+ open.channels.remove(&channel);+ }+ }+ _ = access.changed() => {+ // The desktop or the servers shared changed: what's open beyond+ // them closes, and the guest hears what it has now.+ let c = *control.borrow();+ open.prune().await;+ let o = share.options();+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "access", "desktop": o.desktop, "ports": o.ports, "can_control": c.can_control }))).await;}_ = control.changed() => {let c = *control.borrow();if let Some(why) = c.end {break Err(why);}- if watching.as_ref().is_some_and(|w| w.can_type != c.can_type) {- // Typing on or off: attach again the other way (the- // session server enforces it too).- let channel = watching.as_ref().map(|w| w.guest_channel).unwrap_or(1);- if let Some(w) = watching.take() {- w.close();- }- watching = watch_session(share, channel, c.can_type).await.ok();+ if c.can_type != last.can_type {+ // Typing on or off: sessions attach again the other way+ // (the session server enforces it too).+ open.retype(c.can_type);+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "typing", "allowed": c.can_type }))).await;+ }+ if c.can_control != last.can_control {+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "control", "allowed": c.can_control }))).await;+ }+ if c.can_manage != last.can_manage {+ let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "manage", "allowed": c.can_manage }))).await;}- let _ = rtc::send(dc, rtc::json_frame(&json!({ "event": "typing", "allowed": c.can_type }))).await;+ last = c;}e = events.recv() => if gone(e) { break Ok(()) },}};- if let Some(w) = watching {- w.close();+ if let Some(feed) = feed {+ feed.abort();}+ open.close_all();result}+/// A machine's sessions to a guest: now, whenever they change (checked every+/// few seconds), and right away when asked.+async fn sessions_feed(share: Arc<Share>, dc: Arc<dyn DataChannel>, mut refreshes: mpsc::UnboundedReceiver<()>) {+ let mut sent = Value::Null;+ let mut force = true;+ loop {+ if let Ok(list) = sessions(&share).await+ && (force || list != sent)+ {+ if rtc::send(&dc, rtc::json_frame(&json!({ "event": "sessions", "sessions": list }))).await.is_err() {+ return;+ }+ sent = list;+ }+ force = false;+ tokio::select! {+ _ = tokio::time::sleep(SESSIONS_EVERY) => {}+ r = refreshes.recv() => match r {+ Some(()) => force = true,+ None => return,+ },+ }+ }+}++/// A guest starting, ending or restarting a session: `{"op", "req", "agent"+/// | "session"}`, answered `{"event": "done", "req", "session"}` or+/// `{"event": "failed", "req", "error"}`. Only on a machine share, for a+/// guest let do it; only sessions that are there, agents installed there.+async fn manage(share: &Arc<Share>, req: &Value, c: &Control) -> Value {+ let id = req["req"].as_u64().unwrap_or(0);+ let done = async {+ if !share.target.is_machine() || !c.can_manage {+ return Err(format!("Ask {} to let you start and end sessions.", share.target.by));+ }+ let op = req["op"].as_str().unwrap_or("");+ if op == "start" {+ let agent = req["agent"].as_str().unwrap_or("shell");+ if agent != "shell" && !share.source.agents().iter().any(|a| a == agent) {+ return Err(format!("{agent} isn't installed on {}.", share.target.machine_name));+ }+ return share.source.start(agent).await;+ }+ let name = req["session"].as_str().unwrap_or("").to_string();+ let list = sessions(share).await?;+ if name.is_empty() || !list.as_array().into_iter().flatten().any(|s| s["name"] == name) {+ return Err("That session isn't there anymore.".into());+ }+ share.source.stop(&name, op == "restart").await.map(|()| name)+ };+ match done.await {+ Ok(session) => json!({ "event": "done", "req": id, "session": session }),+ Err(e) => json!({ "event": "failed", "req": id, "error": e }),+ }+}+/// The peer connection failed or closed.fn gone(e: Option<Event>) -> bool {matches!(e, None | Some(Event::State(RTCPeerConnectionState::Failed | RTCPeerConnectionState::Closed)))}-/// The shared session, attached for one guest.-struct Watching {+/// What a guest's channel is joined to.+#[derive(Clone, PartialEq)]+enum Kind {+ Session { name: String, can_type: bool },+ Desktop,+ Tcp(u16),+}++/// One of the guest's channels, joined to one of the machine's.+struct Joined {link: Arc<Link>,link_channel: u32,- guest_channel: u32,- can_type: bool,- frames: mpsc::UnboundedReceiver<(u8, Vec<u8>)>,+ kind: Kind,+ /// Tells this joining from an earlier one on the same channel.+ generation: u64,+ pump: tokio::task::JoinHandle<()>,}-impl Watching {+impl Joined {fn close(self) {+ self.pump.abort();self.link.close_channel(self.link_channel);}}-async fn watch_session(share: &Arc<Share>, guest_channel: u32, can_type: bool) -> Result<Watching, String> {- let link = share.source.link().await?;+/// What a request on channel 0 got going: the reply, and the machine's+/// channel to join.+type Attached = (Value, Arc<Link>, u32, mpsc::UnboundedReceiver<(u8, Vec<u8>)>, Kind);++/// A channel's opening, done: which request it was (`ticket`), whether the+/// guest gets a reply (not for a session attaching again), and the result.+struct Opened {+ channel: u32,+ ticket: u64,+ reply: bool,+ result: Result<Attached, String>,+}++/// A guest's open channels, and those being opened.+struct Open {+ share: Arc<Share>,+ dc: Arc<dyn DataChannel>,+ channels: HashMap<u32, Joined>,+ /// Channels being opened, by the ticket of the latest request for each:+ /// an older one landing (or one closed meanwhile) is let go.+ pending: HashMap<u32, u64>,+ opened: (mpsc::UnboundedSender<Opened>, mpsc::UnboundedReceiver<Opened>),+ /// (channel, generation, the guest is gone) as pumps end.+ ended: (mpsc::UnboundedSender<(u32, u64, bool)>, mpsc::UnboundedReceiver<(u32, u64, bool)>),+ generation: u64,+}++impl Open {+ fn new(share: &Arc<Share>, dc: &Arc<dyn DataChannel>) -> Self {+ Open {+ share: share.clone(),+ dc: dc.clone(),+ channels: HashMap::new(),+ pending: HashMap::new(),+ opened: mpsc::unbounded_channel(),+ ended: mpsc::unbounded_channel(),+ generation: 0,+ }+ }++ /// A request on channel 0: `watch`, `desktop`, `tcp`, `close`. Opening+ /// asks the machine, so it runs beside the guest's loop; `landed` finishes it.+ fn request(&mut self, req: &Value, c: &Control) {+ let op = req["op"].as_str().unwrap_or("");+ let Some(channel) = req["channel"].as_u64().filter(|ch| (1..1 << 20).contains(ch)).map(|ch| ch as u32) else { return };+ if !matches!(op, "watch" | "desktop" | "tcp" | "close") {+ return;+ }+ // A channel holds one thing: asking again replaces it.+ self.close(channel);+ if op == "close" {+ return;+ }+ if self.channels.len() + self.pending.len() >= MAX_CHANNELS {+ let refused = json!({ "event": "refused", "channel": channel, "error": "Too much open at once. Close something first." });+ let dc = self.dc.clone();+ tokio::spawn(async move { rtc::send(&dc, rtc::json_frame(&refused)).await });+ return;+ }+ let share = self.share.clone();+ let (session, quality, port, can_type) = (req["session"].as_str().unwrap_or("").to_string(), req["quality"].as_str().unwrap_or("").to_string(), req["port"].as_u64().unwrap_or(0), c.can_type);+ let op = op.to_string();+ self.begin(channel, true, async move {+ match op.as_str() {+ "watch" => open_watch(&share, channel, &session, can_type).await,+ "desktop" => open_desktop(&share, channel, &quality).await,+ _ => open_tcp(&share, channel, port).await,+ }+ });+ }++ /// Opens a channel beside the loop.+ fn begin(&mut self, channel: u32, reply: bool, opening: impl std::future::Future<Output = Result<Attached, String>> + Send + 'static) {+ self.generation += 1;+ let ticket = self.generation;+ self.pending.insert(channel, ticket);+ let done = self.opened.0.clone();+ tokio::spawn(async move {+ let result = opening.await;+ let _ = done.send(Opened { channel, ticket, reply, result });+ });+ }++ /// A channel's opening is done: the reply first, then what it carries.+ async fn landed(&mut self, o: Opened) {+ if self.pending.get(&o.channel) != Some(&o.ticket) {+ // Closed or asked again meanwhile: not wanted anymore.+ if let Ok((_, link, link_channel, _, _)) = o.result {+ link.close_channel(link_channel);+ }+ return;+ }+ self.pending.remove(&o.channel);+ match o.result {+ Ok((reply, link, link_channel, frames, kind)) => {+ if o.reply {+ let _ = rtc::send(&self.dc, rtc::json_frame(&reply)).await;+ }+ self.join(o.channel, link, link_channel, frames, kind);+ }+ Err(e) if o.reply => {+ let _ = rtc::send(&self.dc, rtc::json_frame(&json!({ "event": "refused", "channel": o.channel, "error": e }))).await;+ }+ // A session that couldn't attach again: the guest's channel ends.+ Err(_) => {+ let _ = rtc::send(&self.dc, super::frame(o.channel, super::CLOSE, &[])).await;+ }+ }+ }++ /// Lets go of a channel, open or being opened.+ fn close(&mut self, channel: u32) {+ self.pending.remove(&channel);+ if let Some(j) = self.channels.remove(&channel) {+ j.close();+ }+ }++ /// Joins a guest channel to a machine channel: what the machine sends of+ /// the kinds that belong there goes to the guest, then CLOSE.+ fn join(&mut self, channel: u32, link: Arc<Link>, link_channel: u32, frames: mpsc::UnboundedReceiver<(u8, Vec<u8>)>, kind: Kind) {+ self.generation += 1;+ let generation = self.generation;+ let (dc, ended) = (self.dc.clone(), self.ended.0.clone());+ let desktop = kind == Kind::Desktop;+ let passes: &'static [u8] = match kind {+ Kind::Session { .. } => &[super::DATA, super::SIZE, super::EXIT],+ Kind::Desktop => &[TILES, FRAME],+ Kind::Tcp(_) => &[super::DATA],+ };+ let pump = tokio::spawn(async move {+ let sent = if desktop { pump_desktop(&dc, channel, frames).await } else { pump(&dc, channel, frames, passes).await };+ let sent = match sent {+ Ok(()) => rtc::send(&dc, super::frame(channel, super::CLOSE, &[])).await,+ e => e,+ };+ let _ = ended.send((channel, generation, sent.is_err()));+ });+ self.channels.insert(channel, Joined { link, link_channel, kind, generation, pump });+ }++ /// A frame on one of the guest's channels: through only as allowed.+ fn pass(&mut self, channel: u32, kind: u8, payload: &[u8], c: &Control) {+ if kind == super::CLOSE {+ self.close(channel);+ return;+ }+ let Some(j) = self.channels.get(&channel) else { return };+ let through = match (&j.kind, kind) {+ (Kind::Session { can_type, .. }, super::DATA) => *can_type && c.can_type,+ (Kind::Desktop, INPUT) => c.can_control && self.share.options().desktop == Desktop::Control,+ (Kind::Tcp(_), super::DATA) => true,+ _ => false,+ };+ if through {+ j.link.send(j.link_channel, kind, payload);+ }+ }++ /// Sessions attach again with typing on or off (beside the loop).+ fn retype(&mut self, can_type: bool) {+ let sessions: Vec<(u32, String)> = self.channels.iter().filter_map(|(ch, j)| if let Kind::Session { name, .. } = &j.kind { Some((*ch, name.clone())) } else { None }).collect();+ for (channel, name) in sessions {+ self.close(channel);+ let share = self.share.clone();+ self.begin(channel, false, async move {+ let (link, link_channel, frames) = attach(&share, &name, can_type).await?;+ Ok((Value::Null, link, link_channel, frames, Kind::Session { name, can_type }))+ });+ }+ }++ /// Closes what the share no longer allows (the desktop, servers).+ async fn prune(&mut self) {+ let o = self.share.options();+ let gone: Vec<u32> = self+ .channels+ .iter()+ .filter(|(_, j)| match &j.kind {+ Kind::Desktop => o.desktop == Desktop::None,+ Kind::Tcp(port) => !o.ports.iter().any(|p| p.port == *port),+ Kind::Session { .. } => false,+ })+ .map(|(ch, _)| *ch)+ .collect();+ for channel in gone {+ self.close(channel);+ let _ = rtc::send(&self.dc, super::frame(channel, super::CLOSE, &[])).await;+ }+ }++ fn close_all(&mut self) {+ self.pending.clear();+ for (_, j) in self.channels.drain() {+ j.close();+ }+ }+}++/// A session: the shared one, or (a machine) one of its sessions.+async fn open_watch(share: &Arc<Share>, channel: u32, asked: &str, can_type: bool) -> Result<Attached, String> {+ let name = if share.target.is_machine() {+ let list = sessions(share).await?;+ let known = list.as_array().into_iter().flatten().any(|s| s["name"] == asked);+ if asked.is_empty() || !known {+ return Err("That session isn't there anymore.".into());+ }+ asked.to_string()+ } else {+ share.target.name.clone()+ };+ let (link, link_channel, frames) = attach(share, &name, can_type).await?;+ let reply = json!({ "event": "watching", "channel": channel, "session": name });+ Ok((reply, link, link_channel, frames, Kind::Session { name, can_type }))+}++async fn attach(share: &Arc<Share>, name: &str, can_type: bool) -> Result<(Arc<Link>, u32, mpsc::UnboundedReceiver<(u8, Vec<u8>)>), String> {+ let link = share.machine().await?;if !supports_sharing(link.version()) {return Err(format!("Muxin's agent on {} needs an update to share sessions.", share.target.machine_name));}let (link_channel, frames) = link.open_channel();- let request = json!({ "op": "attach", "name": share.target.name, "channel": link_channel, "watch_only": !can_type, "sizes": true });- let reply = link.request(request, Duration::from_secs(15)).await?;+ let request = json!({ "op": "attach", "name": name, "channel": link_channel, "watch_only": !can_type, "sizes": true });+ let reply = match link.request(request, Duration::from_secs(15)).await {+ Ok(r) => r,+ Err(e) => {+ link.close_channel(link_channel);+ return Err(e);+ }+ };if reply["ok"].as_bool() != Some(true) {link.close_channel(link_channel);return Err(reply["error"].as_str().unwrap_or("The session couldn't be shown.").to_string());}- Ok(Watching { link, link_channel, guest_channel, can_type, frames })+ Ok((link, link_channel, frames))+}++/// The machine's desktop, at one of the qualities a guest can pick.+async fn open_desktop(share: &Arc<Share>, channel: u32, quality: &str) -> Result<Attached, String> {+ if !share.target.is_machine() || share.options().desktop == Desktop::None {+ return Err("The desktop isn't shared.".into());+ }+ let link = share.machine().await?;+ let (link_channel, frames) = link.open_channel();+ let (quality, (fps, jpeg, max_width)) = desktop_quality(quality);+ let request = json!({ "op": "desktop", "channel": link_channel, "fps": fps, "quality": jpeg, "max_width": max_width, "tiles": true, "display": "" });+ let reply = match link.request(request, Duration::from_secs(20)).await {+ Ok(r) => r,+ Err(e) => {+ link.close_channel(link_channel);+ return Err(e);+ }+ };+ if reply["ok"].as_bool() != Some(true) {+ link.close_channel(link_channel);+ return Err(reply["error"].as_str().unwrap_or("The desktop couldn't be shown.").to_string());+ }+ let reply = json!({ "event": "desktop", "channel": channel, "width": reply["width"], "height": reply["height"], "quality": quality });+ Ok((reply, link, link_channel, frames, Kind::Desktop))+}++/// One of the servers the user picked, on the machine itself.+async fn open_tcp(share: &Arc<Share>, channel: u32, port: u64) -> Result<Attached, String> {+ let shared = share.options().ports.into_iter().find(|p| p.port as u64 == port).filter(|_| share.target.is_machine());+ let Some(shared) = shared else {+ return Err("That server isn't shared.".into());+ };+ let link = share.machine().await?;+ let (link_channel, frames) = link.open_channel();+ let request = json!({ "op": "tcp", "channel": link_channel, "port": port, "host": shared.host });+ let reply = match link.request(request, Duration::from_secs(15)).await {+ Ok(r) => r,+ Err(e) => {+ link.close_channel(link_channel);+ return Err(e);+ }+ };+ if reply["ok"].as_bool() != Some(true) {+ link.close_channel(link_channel);+ return Err(reply["error"].as_str().unwrap_or("That server didn't answer.").to_string());+ }+ Ok((json!({ "event": "tcp", "channel": channel, "port": port }), link, link_channel, frames, Kind::Tcp(port as u16)))+}++/// A machine channel's frames of the kinds that belong, to the guest's+/// channel, as they come (waiting while the guest catches up).+async fn pump(dc: &Arc<dyn DataChannel>, channel: u32, mut frames: mpsc::UnboundedReceiver<(u8, Vec<u8>)>, passes: &[u8]) -> Result<(), String> {+ while let Some((kind, bytes)) = frames.recv().await {+ if passes.contains(&kind) {+ rtc::send(dc, super::frame(channel, kind, &bytes)).await?;+ }+ }+ Ok(())+}++/// Bytes on their way to a guest before the desktop holds back.+const DESKTOP_BACKLOG: usize = 512 << 10;++/// The desktop to a guest. While its connection is behind, what changed+/// waits and only the newest of each part of the screen goes once it+/// catches up: a slow guest sees fewer frames, never an old screen or a+/// broken one.+async fn pump_desktop(dc: &Arc<dyn DataChannel>, channel: u32, mut frames: mpsc::UnboundedReceiver<(u8, Vec<u8>)>) -> Result<(), String> {+ let mut waiting = Tiles::default();+ loop {+ let next = if waiting.is_empty() {+ frames.recv().await+ } else {+ tokio::select! {+ f = frames.recv() => f,+ _ = tokio::time::sleep(Duration::from_millis(30)) => Some((0, Vec::new())),+ }+ };+ match next {+ None => return Ok(()),+ Some((TILES, bytes)) => {+ if !waiting.add(&bytes) {+ continue;+ }+ }+ Some((FRAME, bytes)) => {+ rtc::send(dc, super::frame(channel, FRAME, &bytes)).await?;+ continue;+ }+ Some(_) => {}+ }+ if waiting.is_empty() || dc.outstanding_bytes().await.unwrap_or(0) > DESKTOP_BACKLOG {+ continue;+ }+ rtc::send(dc, super::frame(channel, TILES, &waiting.take())).await?;+ }+}++/// Screen patches waiting to go: `[width][height][count]` then each+/// `[x][y][w][h][len: u32][jpeg]` (agent/src/desktop.rs). A patch replaces+/// the ones before it that it covers.+#[derive(Default)]+struct Tiles {+ size: (u16, u16),+ patches: Vec<([u16; 4], Vec<u8>)>,+}++impl Tiles {+ fn is_empty(&self) -> bool {+ self.patches.is_empty()+ }++ /// Adds a TILES message's patches (false: it didn't read).+ fn add(&mut self, msg: &[u8]) -> bool {+ let u16_at = |o: usize| msg.get(o..o + 2).map(|b| u16::from_be_bytes([b[0], b[1]]));+ let (Some(w), Some(h), Some(count)) = (u16_at(0), u16_at(2), u16_at(4)) else { return false };+ let mut new = Vec::with_capacity(count as usize);+ let mut o = 6;+ for _ in 0..count {+ let (Some(x), Some(y), Some(pw), Some(ph)) = (u16_at(o), u16_at(o + 2), u16_at(o + 4), u16_at(o + 6)) else { return false };+ let Some(len) = msg.get(o + 8..o + 12).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize) else { return false };+ let Some(jpeg) = msg.get(o + 12..o + 12 + len) else { return false };+ new.push(([x, y, pw, ph], jpeg.to_vec()));+ o += 12 + len;+ }+ if self.size != (w, h) {+ self.patches.clear();+ self.size = (w, h);+ }+ let covers = |a: &[u16; 4], b: &[u16; 4]| a[0] <= b[0] && a[1] <= b[1] && a[0] as u32 + a[2] as u32 >= b[0] as u32 + b[2] as u32 && a[1] as u32 + a[3] as u32 >= b[1] as u32 + b[3] as u32;+ self.patches.retain(|(old, _)| !new.iter().any(|(r, _)| covers(r, old)));+ self.patches.extend(new);+ true+ }++ /// One TILES message of everything waiting.+ fn take(&mut self) -> Vec<u8> {+ let patches = std::mem::take(&mut self.patches);+ let mut msg = Vec::with_capacity(6 + patches.iter().map(|(_, j)| 12 + j.len()).sum::<usize>());+ for v in [self.size.0, self.size.1, patches.len() as u16] {+ msg.extend(v.to_be_bytes());+ }+ for (r, jpeg) in patches {+ for v in r {+ msg.extend(v.to_be_bytes());+ }+ msg.extend((jpeg.len() as u32).to_be_bytes());+ msg.extend(jpeg);+ }+ msg+ }+}++/// The desktop qualities a guest can pick, as (frames a second, JPEG+/// quality, widest frame): nothing heavier than "max". Medium unless asked.+pub const QUALITIES: [&str; 4] = ["low", "medium", "high", "max"];++fn desktop_quality(name: &str) -> (&'static str, (u32, u32, u32)) {+ match name {+ "low" => ("low", (10, 45, 1280)),+ "high" => ("high", (24, 75, 1920)),+ "max" => ("max", (30, 85, 2560)),+ _ => ("medium", (15, 60, 1600)),+ }+}++/// A machine's sessions, as a machine share's guests see them: no folders+/// or commands, just what to pick from.+async fn sessions(share: &Arc<Share>) -> Result<Value, String> {+ let link = share.machine().await?;+ let reply = link.request(json!({ "op": "list" }), Duration::from_secs(10)).await?;+ let now = chrono::Utc::now().timestamp();+ let list: Vec<Value> = reply["sessions"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|s| {+ json!({+ "name": s["name"],+ "title": s["title"],+ "agent": s["agent"],+ "status": s["status"],+ "busy": s["last_output"].as_i64().is_some_and(|t| now - t < 6),+ })+ })+ .collect();+ Ok(Value::Array(list))}/// Agents from 0.2.9 attach watchers that can't type and report sizes.@@ -683,6 +1399,41 @@ mod tests {assert_eq!(clean_name(&"x".repeat(100)).len(), 40);}+ fn tiles(size: (u16, u16), patches: &[([u16; 4], &[u8])]) -> Vec<u8> {+ let mut t = Tiles { size, patches: patches.iter().map(|(r, j)| (*r, j.to_vec())).collect() };+ t.take()+ }++ #[test]+ fn a_slow_guest_gets_the_newest_of_each_part() {+ let mut waiting = Tiles::default();+ assert!(waiting.add(&tiles((100, 50), &[([0, 0, 64, 32], b"a"), ([64, 0, 36, 32], b"b")])));+ // A later patch over the first one replaces it; the other stays.+ assert!(waiting.add(&tiles((100, 50), &[([0, 0, 64, 32], b"c")])));+ // One that only overlaps keeps both, in order.+ assert!(waiting.add(&tiles((100, 50), &[([32, 0, 40, 32], b"d")])));+ let kept: Vec<&[u8]> = waiting.patches.iter().map(|(_, j)| j.as_slice()).collect();+ assert_eq!(kept, [b"b".as_slice(), b"c", b"d"]);+ let mut again = Tiles::default();+ assert!(again.add(&waiting.take()));+ assert_eq!(again.patches.len(), 3);+ assert!(waiting.is_empty());+ // A new size starts over; a cut-short message doesn't read.+ assert!(again.add(&tiles((200, 100), &[([0, 0, 64, 32], b"e")])));+ assert_eq!(again.patches.len(), 1);+ let whole = tiles((200, 100), &[([0, 0, 64, 32], b"jpeg")]);+ assert!(!again.add(&whole[..whole.len() - 1]));+ }++ #[test]+ fn guests_pick_only_the_desktop_qualities_offered() {+ for q in QUALITIES {+ assert_eq!(desktop_quality(q).0, q);+ }+ assert_eq!(desktop_quality("").0, "medium");+ assert_eq!(desktop_quality("8k").1, desktop_quality("medium").1);+ }+#[test]fn knows_which_agents_share() {assert!(supports_sharing("0.2.9"));diff --git a/src/share/mod.rs b/src/share/mod.rsindex 1897cef..ba724fa 100644--- a/src/share/mod.rs+++ b/src/share/mod.rs@@ -1,4 +1,4 @@-//! Sharing a session by link, peer to peer from this computer.+//! Sharing a session or a machine by link, peer to peer from this computer.//!//! The person sharing gets a link; whoever opens it joins from Muxin or a//! browser, straight to this computer over WebRTC (a data channel; an@@ -26,13 +26,22 @@//! anyone with the link watch).//!//! On the data channel each message is one frame, `[channel: u32 BE][kind:-//! u8][payload]`, the link's kinds (`fleet::link`): JSON on channel 0, a-//! terminal on the others (DATA, EXIT, SIZE, CLOSE).+//! u8][payload]`, or, for one over 48 KB, its parts in order: MORE frames,+//! then the last part with the frame's kind. The link's kinds+//! (`fleet::link`): JSON on channel 0; on+//! the others what the guest opened: a terminal (DATA, EXIT, SIZE, CLOSE),+//! the desktop (TILES and FRAME out, INPUT in) or a server (DATA, CLOSE).//!//! Guest to host: `{"op": "hello", "v": 1, "name", "client": "app" |-//! "browser", "proof"}`, then `{"op": "watch", "channel": n}`. Host to guest:-//! `{"event": "share", ...}` (what's shared), `"waiting"`, `"admitted"`,-//! `"denied"`, `"typing"` (`allowed` changed), `"ended"` (`why`), `"error"`.+//! "browser", "proof"}`; once in, `{"op": "watch", "channel", "session"}`+//! (a machine's session; a session's share ignores the name), `{"op":+//! "desktop", "channel"}`, `{"op": "tcp", "channel", "port"}`, `{"op":+//! "close", "channel"}`, `{"op": "bye"}`. Host to guest: `{"event":+//! "share", ...}` (what's shared), `"waiting"`, `"admitted"`, `"denied"`,+//! `"sessions"` (a machine's, when they change), replies `"watching"`,+//! `"desktop"`, `"tcp"` or `"refused"` (`channel`, `error`), `"typing"` and+//! `"control"` (`allowed` changed), `"access"` (the desktop or servers+//! shared changed), `"ended"` (`why`), `"error"`.pub mod guest;pub mod host;@@ -48,6 +57,8 @@ pub const DATA: u8 = 0;pub const EXIT: u8 = 2;pub const SIZE: u8 = 3;pub const CLOSE: u8 = 11;+/// Part of a frame too big for one message; the rest follows on its channel.+pub const MORE: u8 = 12;/// A frame for the data channel.pub fn frame(channel: u32, kind: u8, payload: &[u8]) -> Vec<u8> {diff --git a/src/share/rtc.rs b/src/share/rtc.rsindex 8afbc59..a5c5d09 100644--- a/src/share/rtc.rs+++ b/src/share/rtc.rs@@ -1,7 +1,8 @@//! WebRTC for both sides of a share: a peer connection with one data//! channel, its events as a stream, and the certificate checks.-use std::sync::Arc;+use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock};use std::time::Duration;use bytes::BytesMut;@@ -147,9 +148,64 @@ pub async fn gathered(pc: &Arc<dyn PeerConnection>, events: &mut mpsc::Unbounded}}-/// Sends a frame, waiting while too much is already on its way; an error-/// when the other side has gone or fell too far behind.+/// The largest message sent: a data channel carries 64 KB a message (RFC+/// 8841's default) and maybe no more, so a bigger frame (a whole screen)+/// goes in pieces: `[channel][MORE][part]`..., then the last part with the+/// frame's own kind. The other side puts them back together (`Pieces`).+const PIECE: usize = 48 * 1024;++/// What one channel sends goes one frame at a time, so its pieces never mix+/// with another frame's (other channels' frames may come in between).+fn channel_lock(dc: &Arc<dyn DataChannel>, channel: u32) -> Arc<tokio::sync::Mutex<()>> {+ let key = (Arc::as_ptr(dc) as *const () as usize, channel);+ LOCKS.get_or_init(Default::default).lock().unwrap().entry(key).or_default().clone()+}++/// Each data channel's per-channel send locks, by its address.+static LOCKS: OnceLock<Mutex<HashMap<(usize, u32), Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();++/// Forgets a closed data channel's locks.+pub fn forget(dc: &Arc<dyn DataChannel>) {+ if let Some(locks) = LOCKS.get() {+ let id = Arc::as_ptr(dc) as *const () as usize;+ locks.lock().unwrap().retain(|(d, _), _| *d != id);+ }+}++/// Sends a frame (in pieces when it's big), waiting while too much is+/// already on its way; an error when the other side has gone or fell too far+/// behind. A frame always goes whole: the sending carries on even when the+/// caller stops waiting for it.pub async fn send(dc: &Arc<dyn DataChannel>, frame: Vec<u8>) -> Result<(), String> {+ let Some((channel, kind, _)) = super::parse_frame(&frame) else { return Ok(()) };+ let lock = channel_lock(dc, channel);+ if frame.len() <= PIECE {+ let _one_at_a_time = lock.lock().await;+ return send_one(dc, frame).await;+ }+ let dc = dc.clone();+ let sending = tokio::spawn(async move {+ let _one_at_a_time = lock.lock().await;+ for part in parts_of(channel, kind, &frame[5..]) {+ send_one(&dc, part).await?;+ }+ Ok(())+ });+ sending.await.map_err(|e| e.to_string())?+}++/// A frame's payload as messages of at most `PIECE` bytes: MORE frames,+/// then the last part with its own kind.+fn parts_of(channel: u32, kind: u8, payload: &[u8]) -> Vec<Vec<u8>> {+ let mut parts: Vec<Vec<u8>> = payload.chunks(PIECE - 5).map(|p| super::frame(channel, super::MORE, p)).collect();+ if let Some(last) = parts.last_mut() {+ last[4] = kind;+ }+ parts+}++/// One message, once there's room for it.+async fn send_one(dc: &Arc<dyn DataChannel>, frame: Vec<u8>) -> Result<(), String> {let mut waited = Duration::ZERO;while dc.outstanding_bytes().await.unwrap_or(0) > MAX_BUFFERED {if waited > Duration::from_secs(10) {@@ -173,6 +229,51 @@ pub async fn flush(dc: &Arc<dyn DataChannel>) {tokio::time::sleep(Duration::from_millis(150)).await;}+/// Frames put back together from their pieces (see `PIECE`), per channel.+#[derive(Default)]+pub struct Pieces {+ parts: HashMap<u32, Vec<u8>>,+ held: usize,+ /// Channels whose frame was too big: its remaining parts are let go too.+ dropping: std::collections::HashSet<u32>,+}++impl Pieces {+ /// The most held at once: a frame bigger than this is dropped (the+ /// other side sending more than any frame needs).+ const MAX: usize = 64 << 20;++ /// A message off the data channel: the frame, once its last piece is in.+ pub fn add(&mut self, msg: Vec<u8>) -> Option<Vec<u8>> {+ let (channel, kind, body) = super::parse_frame(&msg)?;+ if self.dropping.contains(&channel) {+ // The rest of a frame that was too big, up to and with its last part.+ if kind != super::MORE {+ self.dropping.remove(&channel);+ }+ return None;+ }+ if kind == super::MORE {+ if self.held + body.len() > Self::MAX {+ self.held -= self.parts.remove(&channel).map_or(0, |p| p.len());+ self.dropping.insert(channel);+ return None;+ }+ self.held += body.len();+ self.parts.entry(channel).or_default().extend_from_slice(body);+ return None;+ }+ match self.parts.remove(&channel) {+ None => Some(msg),+ Some(mut whole) => {+ self.held -= whole.len();+ whole.extend_from_slice(body);+ Some(super::frame(channel, kind, &whole))+ }+ }+ }+}+/// What arrives on a data channel, as frames (None: it closed).pub async fn next_message(dc: &Arc<dyn DataChannel>) -> Option<Vec<u8>> {loop {@@ -212,6 +313,46 @@ pub fn error_frame(why: &str) -> Vec<u8> {mod tests {use super::*;+ #[test]+ fn big_frames_go_in_pieces_and_come_back_whole() {+ let big: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();+ let parts = parts_of(7, super::super::DATA, &big);+ assert!(parts.len() > 1 && parts.iter().all(|p| p.len() <= PIECE));+ assert!(parts[..parts.len() - 1].iter().all(|p| p[4] == super::super::MORE));+ let mut pieces = Pieces::default();+ // Another channel's frame in between doesn't get mixed in.+ assert_eq!(pieces.add(parts[0].clone()), None);+ let small = super::super::frame(9, super::super::DATA, b"hi");+ assert_eq!(pieces.add(small.clone()), Some(small));+ let mut whole = None;+ for p in &parts[1..] {+ whole = pieces.add(p.clone());+ }+ assert_eq!(whole, Some(super::super::frame(7, super::super::DATA, &big)));+ assert_eq!(pieces.held, 0);+ }++ #[test]+ fn a_frame_too_big_is_let_go_whole() {+ let mut pieces = Pieces::default();+ let part = vec![1u8; PIECE - 5];+ let more = super::super::frame(3, super::super::MORE, &part);+ let mut parts = 0;+ while pieces.held + part.len() <= Pieces::MAX {+ assert_eq!(pieces.add(more.clone()), None);+ parts += 1;+ }+ assert!(parts > 0);+ // Over the limit: this part and the rest go, the last one too.+ assert_eq!(pieces.add(more.clone()), None);+ assert_eq!(pieces.add(more.clone()), None);+ assert_eq!(pieces.add(super::super::frame(3, super::super::DATA, b"end")), None);+ assert_eq!(pieces.held, 0);+ // The next frame on that channel comes through.+ let next = super::super::frame(3, super::super::DATA, b"next");+ assert_eq!(pieces.add(next.clone()), Some(next));+ }+#[test]fn reads_one_fingerprint() {let a = "AA:".repeat(31) + "AA";diff --git a/src/share/tests.rs b/src/share/tests.rsindex 10d2f9c..bf6a15b 100644--- a/src/share/tests.rs+++ b/src/share/tests.rs@@ -1,4 +1,4 @@-//! A share end to end: a share server, an agent with a session, a host and+//! Shares end to end: a share server, an agent with sessions, a host and//! guests, all on this computer. Needs the server running and an agent//! build, and moves HOME (so it runs alone)://!@@ -14,8 +14,8 @@ use std::time::Duration;use serde_json::json;use tokio::sync::mpsc;-use super::guest::{self, Update};-use super::host::{self, Options, Source, Target};+use super::guest::{self, Frames, Update};+use super::host::{self, Desktop, Options, Port, Source, Target};use crate::config::MachineSpec;use crate::fleet::link::{self, Link};@@ -26,6 +26,28 @@ impl Source for Local {async fn link(&self) -> Result<Arc<Link>, String> {link::get(&self.0).await.ok_or_else(|| "no link".to_string())}++ async fn start(&self, agent: &str) -> Result<String, String> {+ let l = self.link().await?;+ let n = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos()).unwrap_or(0) % 100_000;+ let name = format!("{agent}-{n}");+ let home = std::env::var("HOME").unwrap_or_default();+ let r = l.request(json!({ "op": "start", "name": name, "agent": agent, "title": "Started by a guest", "cwd": home, "cols": 100, "rows": 30 }), Duration::from_secs(15)).await?;+ if r["ok"] != true {+ return Err(r["error"].as_str().unwrap_or("didn't start").to_string());+ }+ Ok(name)+ }++ async fn stop(&self, name: &str, restart: bool) -> Result<(), String> {+ let l = self.link().await?;+ let r = l.request(json!({ "op": if restart { "restart" } else { "stop" }, "name": name }), Duration::from_secs(15)).await?;+ if r["ok"] == true { Ok(()) } else { Err(r["error"].as_str().unwrap_or("didn't stop").to_string()) }+ }++ fn agents(&self) -> Vec<String> {+ vec!["shell".into()]+ }}/// Waits for an update that `want` accepts, skipping others.@@ -42,12 +64,12 @@ async fn next(rx: &mut mpsc::UnboundedReceiver<Update>, what: &str, want: impl Ftokio::time::timeout(Duration::from_secs(20), wait).await.unwrap_or_else(|_| panic!("no {what}"))}-/// Everything the guest's terminal got, until `needle` shows up (or not).-async fn output_until(rx: &mut mpsc::UnboundedReceiver<Update>, needle: &str, within: Duration) -> (String, bool) {+/// Everything a guest's terminal got, until `needle` shows up (or not).+async fn output_until(frames: &mut Frames, needle: &str, within: Duration) -> (String, bool) {let mut text = String::new();let deadline = tokio::time::Instant::now() + within;- while let Ok(Some(u)) = tokio::time::timeout_at(deadline, rx.recv()).await {- if let Update::Output(b) = u {+ while let Ok(Some((kind, b))) = tokio::time::timeout_at(deadline, frames.recv()).await {+ if kind == super::DATA {text.push_str(&String::from_utf8_lossy(&b));if text.contains(needle) {return (text, true);@@ -57,37 +79,59 @@ async fn output_until(rx: &mut mpsc::UnboundedReceiver<Update>, needle: &str, wi(text, false)}-async fn screen(l: &Link) -> String {- let r = l.request(json!({ "op": "read", "name": "shared", "lines": 50 }), Duration::from_secs(10)).await.unwrap();- r["text"].as_str().unwrap_or("").to_string()-}--#[tokio::test(flavor = "multi_thread", worker_threads = 4)]-#[ignore]-async fn a_guest_watches_then_types_when_let() {- let (Ok(server), Ok(agent)) = (std::env::var("MUXIN_TEST_SHARE_SERVER"), std::env::var("MUXIN_TEST_AGENT")) else {- panic!("set MUXIN_TEST_SHARE_SERVER and MUXIN_TEST_AGENT");- };- // A home of its own: the agent and its sessions live there.- let home = std::env::temp_dir().join(format!("muxin-share-test-{}", std::process::id()));+/// A home of its own with the test agent in it (the agent and its sessions+/// live there), and a link to that agent.+async fn test_machine(tag: &str) -> (std::path::PathBuf, MachineSpec, Arc<Link>) {+ let agent = std::env::var("MUXIN_TEST_AGENT").expect("set MUXIN_TEST_AGENT");+ let home = std::env::temp_dir().join(format!("muxin-share-{tag}-{}", std::process::id()));std::fs::create_dir_all(home.join(".muxen/bin")).unwrap();std::fs::copy(&agent, home.join(".muxen/bin/muxen-agent")).unwrap();unsafe { std::env::set_var("HOME", &home) };let spec: MachineSpec = toml::from_str("name = \"Here\"\nid = \"here\"\nhost = \"local\"").unwrap();+ // Not a link to another test's agent (in its home, gone now).+ link::reset("here");let l = link::get(&spec).await.expect("link to the test agent");- let started = l.request(json!({ "op": "start", "name": "shared", "agent": "shell", "cwd": home.display().to_string(), "cols": 100, "rows": 30 }), Duration::from_secs(15)).await.unwrap();+ (home, spec, l)+}++async fn start_session(l: &Link, home: &std::path::Path, name: &str, title: &str) {+ let started = l.request(json!({ "op": "start", "name": name, "title": title, "agent": "shell", "cwd": home.display().to_string(), "cols": 100, "rows": 30 }), Duration::from_secs(15)).await.unwrap();assert_eq!(started["ok"], true, "{started}");+}- let target = Target {- session_id: "here/shared".into(),+fn target(session: &str, title: &str, agent: &str, machine_name: &str) -> Target {+ Target {+ session_id: if session.is_empty() { String::new() } else { format!("here/{session}") },machine_id: "here".into(),- name: "shared".into(),- title: "Checkout fix".into(),- agent: "shell".into(),- machine_name: "Here".into(),+ name: session.into(),+ title: title.into(),+ agent: agent.into(),+ machine_name: machine_name.into(),+ platform: String::new(),by: "Adib".into(),- };- let share = host::start(&server, target, Options { approve: true, can_type: false, ttl: Duration::from_secs(120) }, Arc::new(Local(spec.clone()))).await.expect("share");+ }+}++fn options(approve: bool, desktop: Desktop, ports: Vec<Port>, ttl: u64) -> Options {+ Options { approve, can_type: false, manage: false, desktop, ports, ttl: Duration::from_secs(ttl) }+}++async fn screen(l: &Link, name: &str) -> String {+ let r = l.request(json!({ "op": "read", "name": name, "lines": 50 }), Duration::from_secs(10)).await.unwrap();+ r["text"].as_str().unwrap_or("").to_string()+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+#[ignore]+async fn a_guest_watches_then_types_when_let() {+ let server = std::env::var("MUXIN_TEST_SHARE_SERVER").expect("set MUXIN_TEST_SHARE_SERVER");+ let (home, spec, l) = test_machine("session").await;+ start_session(&l, &home, "shared", "").await;+ let share = host::start(&server, target("shared", "Checkout fix", "shell", "Here"), options(true, Desktop::Control, vec![Port { port: 22, name: "ssh".into(), ..Default::default() }], 120), Arc::new(Local(spec.clone())))+ .await+ .expect("share");+ // A session's share has no desktop or servers, whatever was asked.+ assert_eq!((share.desktop, share.ports.len()), (Desktop::None, 0));assert!(share.link.contains("/s#1."));// A link with the wrong secret gets nowhere.@@ -122,11 +166,19 @@ async fn a_guest_watches_then_types_when_let() {let sam = waiting.guests.iter().find(|g| g.name == "Sam").expect("Sam knocks");assert_eq!((sam.code.as_str(), sam.state.as_str(), sam.client.as_str()), (code.as_str(), "waiting", "app"));host::admit(&share.id, sam.id, true);- next(&mut rx, "admitted", |u| matches!(u, Update::Admitted { can_type: false })).await;- match next(&mut rx, "the size", |u| matches!(u, Update::Size(..))).await {- Update::Size(c, r) => assert_eq!((c, r), (100, 30)),- _ => unreachable!(),+ next(&mut rx, "admitted", |u| matches!(u, Update::Admitted { can_type: false, can_control: false, can_manage: false })).await;+ // The shared session, whatever name is asked for.+ let (channel, reply, mut frames) = joined.open(json!({ "op": "watch", "session": "other" })).await.expect("watch");+ assert_eq!(reply["session"], "shared");+ match tokio::time::timeout(Duration::from_secs(10), frames.recv()).await {+ Ok(Some((super::SIZE, b))) => assert_eq!(b, [0, 100, 0, 30]),+ other => panic!("the size first: {other:?}"),}+ // Nothing else is there.+ let desktop = joined.open(json!({ "op": "desktop" })).await.err().expect("no desktop");+ assert!(desktop.contains("isn't shared"), "{desktop}");+ let tcp = joined.open(json!({ "op": "tcp", "port": 22 })).await.err().expect("no servers");+ assert!(tcp.contains("isn't shared"), "{tcp}");// On this computer the connection is direct (no relay offered anyway).let mut path = String::new();@@ -144,20 +196,22 @@ async fn a_guest_watches_then_types_when_let() {let attached = l.request(json!({ "op": "attach", "name": "shared", "channel": owner }), Duration::from_secs(10)).await.unwrap();assert_eq!(attached["ok"], true);l.send(owner, link::DATA, b"echo FROM_OWNER\r");- let (_, seen) = output_until(&mut rx, "FROM_OWNER", Duration::from_secs(10)).await;+ let (_, seen) = output_until(&mut frames, "FROM_OWNER", Duration::from_secs(10)).await;assert!(seen, "the guest sees the session");- joined.send_keys(b"echo FROM_SAM_EARLY\r");- // Bypassing the app's own check: the host drops it too.+ // Bypassing the app's own check: the host drops it.+ joined.send(channel, super::DATA, b"echo FROM_SAM_EARLY\r");tokio::time::sleep(Duration::from_millis(1500)).await;- assert!(!screen(&l).await.contains("FROM_SAM_EARLY"));+ assert!(!screen(&l, "shared").await.contains("FROM_SAM_EARLY"));// Let Sam type.host::set_typing(&share.id, sam.id, true);next(&mut rx, "typing allowed", |u| matches!(u, Update::Typing(true))).await;- joined.send_keys(b"echo FROM_SAM\r");- let (_, typed) = output_until(&mut rx, "FROM_SAM", Duration::from_secs(10)).await;+ // The session attaches again, typing: its frames come on the same channel.+ tokio::time::sleep(Duration::from_millis(500)).await;+ joined.send_keys(channel, b"echo FROM_SAM\r");+ let (_, typed) = output_until(&mut frames, "FROM_SAM", Duration::from_secs(10)).await;assert!(typed, "Sam's keys reach the session once let");- assert!(screen(&l).await.contains("FROM_SAM"));+ assert!(screen(&l, "shared").await.contains("FROM_SAM"));// Someone the user doesn't let in hears so.let (_, mut kim) = guest::join(&share.link, "Kim").await.expect("join");@@ -181,32 +235,192 @@ async fn a_guest_watches_then_types_when_let() {let _ = std::fs::remove_dir_all(&home);}+/// A small server on this computer: says back what it hears.+async fn echo_server() -> u16 {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ tokio::spawn(async move {+ while let Ok((mut s, _)) = listener.accept().await {+ tokio::spawn(async move {+ let (mut r, mut w) = s.split();+ let _ = tokio::io::copy(&mut r, &mut w).await;+ });+ }+ });+ port+}++#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+#[ignore]+async fn a_guest_uses_a_shared_machine() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let server = std::env::var("MUXIN_TEST_SHARE_SERVER").expect("set MUXIN_TEST_SHARE_SERVER");+ let (home, spec, l) = test_machine("machine").await;+ start_session(&l, &home, "api", "API server").await;+ start_session(&l, &home, "web", "Web").await;+ let (echo, closed) = (echo_server().await, echo_server().await);+ let ports = vec![Port { port: echo, name: "Echo".into(), ..Default::default() }];+ let share = host::start(&server, target("", "Here", "", "Here"), options(true, Desktop::View, ports, 120), Arc::new(Local(spec.clone()))).await.expect("share");++ let (joined, mut rx) = guest::join(&share.link, "Sam").await.expect("join");+ let info = match next(&mut rx, "what's shared", |u| matches!(u, Update::Info(_))).await {+ Update::Info(i) => i,+ _ => unreachable!(),+ };+ assert!(info.whole_machine);+ assert_eq!((info.title.as_str(), info.desktop, info.can_control, info.ports.len()), ("Here", Desktop::View, false, 1));+ // Nothing opens before the user lets Sam in.+ next(&mut rx, "waiting", |u| matches!(u, Update::Waiting)).await;+ let early = tokio::time::timeout(Duration::from_secs(3), joined.open(json!({ "op": "watch", "session": "api" }))).await;+ assert!(!matches!(early, Ok(Ok(_))), "nothing before being let in");+ let sam = host::list().into_iter().find(|s| s.id == share.id).unwrap().guests.into_iter().find(|g| g.name == "Sam").unwrap();+ host::admit(&share.id, sam.id, true);+ next(&mut rx, "admitted", |u| matches!(u, Update::Admitted { .. })).await;++ // The machine's sessions, as they are.+ let names = |u: &Update| match u {+ Update::Sessions(list) => list.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),+ _ => Vec::new(),+ };+ let list = next(&mut rx, "the sessions", |u| matches!(u, Update::Sessions(_))).await;+ assert_eq!(names(&list), ["api", "web"]);++ // Two sessions at once, each on its channel; a made-up one is refused.+ let (api, _, mut api_frames) = joined.open(json!({ "op": "watch", "session": "api" })).await.expect("watch api");+ let (_, _, mut web_frames) = joined.open(json!({ "op": "watch", "session": "web" })).await.expect("watch web");+ let nope = joined.open(json!({ "op": "watch", "session": "nope" })).await.err().expect("refused");+ assert!(nope.contains("isn't there"), "{nope}");+ let (owner, _owner_rx) = l.open_channel();+ l.request(json!({ "op": "attach", "name": "web", "channel": owner }), Duration::from_secs(10)).await.unwrap();+ l.send(owner, link::DATA, b"echo ON_WEB\r");+ assert!(output_until(&mut web_frames, "ON_WEB", Duration::from_secs(10)).await.1, "web's output on web's channel");+ assert!(!output_until(&mut api_frames, "ON_WEB", Duration::from_secs(1)).await.1, "not on api's");++ // Typing only once let.+ joined.send(api, super::DATA, b"echo SAM_EARLY\r");+ tokio::time::sleep(Duration::from_millis(1200)).await;+ assert!(!screen(&l, "api").await.contains("SAM_EARLY"));+ host::set_typing(&share.id, sam.id, true);+ next(&mut rx, "typing allowed", |u| matches!(u, Update::Typing(true))).await;+ tokio::time::sleep(Duration::from_millis(500)).await;+ joined.send_keys(api, b"echo SAM_TYPED\r");+ assert!(output_until(&mut api_frames, "SAM_TYPED", Duration::from_secs(10)).await.1);++ // Starting and ending sessions: not until let.+ let refused = joined.call(json!({ "op": "start", "agent": "shell" })).await.err().expect("not let yet");+ assert!(refused.contains("Ask"), "{refused}");+ host::set_managing(&share.id, sam.id, true);+ next(&mut rx, "starting sessions allowed", |u| matches!(u, Update::Manage(true))).await;+ assert!(joined.can_manage());+ let started = joined.call(json!({ "op": "start", "agent": "shell" })).await.expect("a terminal started");+ next(&mut rx, "the session started", |u| names(u).contains(&started)).await;+ assert!(joined.call(json!({ "op": "start", "agent": "claude" })).await.is_err(), "only agents installed there");+ assert!(joined.call(json!({ "op": "end", "session": "made-up" })).await.is_err(), "only sessions that are there");+ assert_eq!(joined.call(json!({ "op": "end", "session": started.clone() })).await.as_deref(), Ok(started.as_str()));+ next(&mut rx, "the session gone", |u| matches!(u, Update::Sessions(_)) && !names(u).contains(&started)).await;++ // A session started later shows up.+ start_session(&l, &home, "later", "Later").await;+ let list = next(&mut rx, "the new session", |u| names(u).contains(&"later".to_string())).await;+ assert_eq!(names(&list).len(), 3);++ // The shared server, and only it.+ let (echo_ch, _, mut echo_frames) = joined.open(json!({ "op": "tcp", "port": echo })).await.expect("tcp");+ joined.send(echo_ch, super::DATA, b"ping");+ match tokio::time::timeout(Duration::from_secs(5), echo_frames.recv()).await {+ Ok(Some((super::DATA, b))) => assert_eq!(b, b"ping"),+ other => panic!("the echo: {other:?}"),+ }+ // A frame bigger than a data channel message goes in pieces, and comes+ // back (in the server's own reads) whole.+ let big: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();+ joined.send(echo_ch, super::DATA, &big);+ let mut back = Vec::new();+ while back.len() < big.len() {+ match tokio::time::timeout(Duration::from_secs(10), echo_frames.recv()).await {+ Ok(Some((super::DATA, b))) => back.extend(b),+ other => panic!("the big echo, {} bytes in: {other:?}", back.len()),+ }+ }+ assert!(back == big, "300 KB through and back, in order");+ let refused = joined.open(json!({ "op": "tcp", "port": closed })).await.err().expect("not shared");+ assert!(refused.contains("isn't shared"), "{refused}");+ // Forwarded to a port here, as the app's Open does.+ let local = joined.forward(echo).await.expect("forward");+ let mut conn = tokio::net::TcpStream::connect(("127.0.0.1", local)).await.unwrap();+ conn.write_all(b"hello through").await.unwrap();+ let mut got = [0u8; 13];+ tokio::time::timeout(Duration::from_secs(5), conn.read_exact(&mut got)).await.expect("echo in time").unwrap();+ assert_eq!(&got, b"hello through");+ // Viewing the desktop never lets the mouse through.+ host::set_control(&share.id, sam.id, true);+ assert!(!host::list()[0].guests[0].can_control);++ // Taking the servers and the desktop back closes what's open on them.+ host::set_access(&share.id, Desktop::None, Vec::new());+ match next(&mut rx, "the access", |u| matches!(u, Update::Access { .. })).await {+ Update::Access { desktop, ports } => assert_eq!((desktop, ports.len()), (Desktop::None, 0)),+ _ => unreachable!(),+ }+ let closed_too = tokio::time::timeout(Duration::from_secs(5), async {+ while let Some((kind, _)) = echo_frames.recv().await {+ if kind == super::CLOSE {+ return true;+ }+ }+ true+ });+ assert!(closed_too.await.unwrap_or(false), "the server's channel closes");+ assert!(joined.open(json!({ "op": "tcp", "port": echo })).await.is_err());+ assert!(joined.open(json!({ "op": "desktop" })).await.is_err());+ assert!(joined.forwarded(echo).is_none(), "the forward here stops too");++ host::stop(&share.id);+ next(&mut rx, "the end", |u| matches!(u, Update::Ended(_))).await;+ for name in ["api", "web", "later"] {+ let _ = l.request(json!({ "op": "stop", "name": name }), Duration::from_secs(10)).await;+ }+ let _ = std::fs::remove_dir_all(&home);+}+/// Hosts a share for a browser to join by hand (or by a browser driver):/// writes the link to `MUXIN_TEST_LINK_FILE`, lets guests in, lets them type-/// 15 seconds later, and keeps the session busy. Stops after 10 minutes.+/// 15 seconds later, and keeps the sessions busy. Stops after 10 minutes.+/// `MUXIN_TEST_SHARE_MACHINE=1` shares the machine (two sessions and a small+/// web server) instead of one session; `MUXIN_TEST_SHARE_DESKTOP=view` or+/// `control` shares its desktop too (this computer's screen: not on yours).#[tokio::test(flavor = "multi_thread", worker_threads = 4)]#[ignore]async fn hosts_for_a_browser() {- let (Ok(server), Ok(agent), Ok(link_file)) = (std::env::var("MUXIN_TEST_SHARE_SERVER"), std::env::var("MUXIN_TEST_AGENT"), std::env::var("MUXIN_TEST_LINK_FILE")) else {+ let (Ok(server), Ok(link_file)) = (std::env::var("MUXIN_TEST_SHARE_SERVER"), std::env::var("MUXIN_TEST_LINK_FILE")) else {panic!("set MUXIN_TEST_SHARE_SERVER, MUXIN_TEST_AGENT and MUXIN_TEST_LINK_FILE");};- let home = std::env::temp_dir().join(format!("muxin-share-browser-{}", std::process::id()));- std::fs::create_dir_all(home.join(".muxen/bin")).unwrap();- std::fs::copy(&agent, home.join(".muxen/bin/muxen-agent")).unwrap();- unsafe { std::env::set_var("HOME", &home) };- let spec: MachineSpec = toml::from_str("name = \"Here\"\nid = \"here\"\nhost = \"local\"").unwrap();- let l = link::get(&spec).await.expect("link to the test agent");- l.request(json!({ "op": "start", "name": "shared", "agent": "shell", "cwd": home.display().to_string(), "cols": 100, "rows": 30 }), Duration::from_secs(15)).await.unwrap();- let target = Target {- session_id: "here/shared".into(),- machine_id: "here".into(),- name: "shared".into(),- title: "Checkout fix".into(),- agent: "claude".into(),- machine_name: "Forge".into(),- by: "Adib".into(),+ let machine = std::env::var("MUXIN_TEST_SHARE_MACHINE").is_ok_and(|v| v == "1");+ let desktop = match std::env::var("MUXIN_TEST_SHARE_DESKTOP").unwrap_or_default().as_str() {+ "view" => Desktop::View,+ "control" => Desktop::Control,+ _ => Desktop::None,+ };+ let (home, spec, l) = test_machine("browser").await;+ start_session(&l, &home, "shared", "Checkout fix").await;+ let share = if machine {+ start_session(&l, &home, "tests", "Tests").await;+ let web = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = web.local_addr().unwrap().port();+ tokio::spawn(async move {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ while let Ok((mut s, _)) = web.accept().await {+ let mut buf = [0u8; 2048];+ let _ = s.read(&mut buf).await;+ let body = "<h1>Hello from the shared machine</h1>";+ let _ = s.write_all(format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len()).as_bytes()).await;+ }+ });+ let ports = vec![Port { port, name: "Checkout dev".into(), ..Default::default() }];+ host::start(&server, target("", "Forge", "", "Forge"), options(true, desktop, ports, 600), Arc::new(Local(spec))).await.expect("share")+ } else {+ host::start(&server, target("shared", "Checkout fix", "claude", "Forge"), options(true, Desktop::None, Vec::new(), 600), Arc::new(Local(spec))).await.expect("share")};- let share = host::start(&server, target, Options { approve: true, can_type: false, ttl: Duration::from_secs(600) }, Arc::new(Local(spec))).await.expect("share");std::fs::write(&link_file, &share.link).unwrap();let (owner, _rx) = l.open_channel();l.request(json!({ "op": "attach", "name": "shared", "channel": owner }), Duration::from_secs(10)).await.unwrap();@@ -235,6 +449,8 @@ async fn hosts_for_a_browser() {}}host::stop(&share.id);- let _ = l.request(json!({ "op": "stop", "name": "shared" }), Duration::from_secs(10)).await;+ for name in ["shared", "tests"] {+ let _ = l.request(json!({ "op": "stop", "name": name }), Duration::from_secs(10)).await;+ }let _ = std::fs::remove_dir_all(&home);}diff --git a/src/ui/desktop.rs b/src/ui/desktop.rsindex 1ef3d7f..6078660 100644--- a/src/ui/desktop.rs+++ b/src/ui/desktop.rs@@ -1,6 +1,6 @@//! A machine's desktop, live: frames from its agent over the machine's link-//! (see agent/src/desktop.rs), and the mouse and keyboard sent back. X11-//! machines for now.+//! (see agent/src/desktop.rs), and the mouse and keyboard sent back. Or a+//! desktop someone shared with you, the same way over the share.use std::cell::Cell;use std::rc::Rc;@@ -20,6 +20,7 @@ use super::theme::ActiveTheme;use crate::fleet::Engine;use crate::fleet::desktop::{FRAME, INPUT, TILES, keysym};use crate::fleet::link::Link;+use crate::share::guest;const CONTEXT: &str = "Desktop";@@ -73,27 +74,40 @@ pub const NATIVE: u32 = 16384;/// Monitor sizes with a short name, offered when the monitor has them.const SIZES: [((u32, u32), &str); 4] = [((1280, 720), "720p"), ((1920, 1080), "1080p"), ((2560, 1440), "1440p"), ((3840, 2160), "4K")];-/// The desktop's channel on the machine's link.-struct Remote {- link: Arc<Link>,- channel: u32,+/// The desktop's channel: on the machine's link, or on a share.+enum Remote {+ Link(Arc<Link>, u32),+ Shared(Arc<guest::Joined>, u32),}impl Remote {fn input(&self, event: Value) {- self.link.send(self.channel, INPUT, &serde_json::to_vec(&event).unwrap_or_default());+ let bytes = serde_json::to_vec(&event).unwrap_or_default();+ match self {+ Remote::Link(link, channel) => link.send(*channel, INPUT, &bytes),+ Remote::Shared(joined, channel) => joined.send(*channel, INPUT, &bytes),+ }}}impl Drop for Remote {fn drop(&mut self) {- self.link.close_channel(self.channel);+ match self {+ Remote::Link(link, channel) => link.close_channel(*channel),+ Remote::Shared(joined, channel) => joined.close(*channel),+ }}}pub struct DesktopView {engine: Arc<Engine>,machine: String,+ /// Someone's shared desktop (no machine of ours), and whether we may use+ /// its mouse and keyboard.+ shared: Option<Arc<guest::Joined>>,+ can_control: bool,+ /// A shared desktop's quality ("low" to "max", see share::host).+ quality: &'static str,/// One of the machine's displays (None: the whole desktop, or a Mac's main display).display: Option<String>,/// The frame width asked for (None: native on a local network, else 1080p).@@ -156,9 +170,25 @@ impl Focusable for DesktopView {impl DesktopView {pub fn new(engine: Arc<Engine>, machine_id: String, window: &mut Window, cx: &mut Context<Self>) -> Self {+ Self::make(engine, machine_id, None, "medium", window, cx)+ }++ /// A desktop someone shared with you: input goes there only while they+ /// let you control it (`set_control`).+ pub fn shared(engine: Arc<Engine>, joined: Arc<guest::Joined>, mac: bool, quality: &'static str, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let mut view = Self::make(engine, String::new(), Some(joined), quality, window, cx);+ view.mac = mac;+ view+ }++ fn make(engine: Arc<Engine>, machine_id: String, shared: Option<Arc<guest::Joined>>, quality: &'static str, window: &mut Window, cx: &mut Context<Self>) -> Self {+ let can_control = shared.as_ref().is_none_or(|j| j.can_control());let mut view = DesktopView {engine,machine: machine_id,+ shared,+ can_control,+ quality,display: None,width: None,via: String::new(),@@ -196,6 +226,11 @@ impl DesktopView {view.platform = view.engine.current().machines.iter().find(|m| m.id == view.machine).map(|m| m.platform.clone()).unwrap_or_default();view.mac = view.platform.starts_with("darwin");view.start(window, cx);+ if view.shared.is_some() {+ let blur = cx.on_focus_out(&view.focus, window, |this, _, _, _| this.let_go());+ view._subscriptions = vec![blur];+ return view;+ }// Keys and buttons held when the view loses the keyboard (another// app, ⌘Q, a click elsewhere): let go on the machine too.let blur = cx.on_focus_out(&view.focus, window, |this, _, _, _| this.let_go());@@ -247,6 +282,31 @@ impl DesktopView {cx.notify();}+ /// Lets the mouse and keyboard through, or not (a shared desktop).+ pub fn set_control(&mut self, allowed: bool, cx: &mut Context<Self>) {+ if !allowed {+ self.let_go();+ }+ self.can_control = allowed;+ cx.notify();+ }++ /// A shared desktop's quality.+ pub fn quality(&self) -> &'static str {+ self.quality+ }++ /// Asks a shared desktop for another quality: a new stream, the picture+ /// kept until it comes.+ pub fn set_quality(&mut self, quality: &'static str, window: &mut Window, cx: &mut Context<Self>) {+ if quality != self.quality && self.shared.is_some() {+ self.quality = quality;+ self.retries = 0;+ self.start(window, cx);+ cx.notify();+ }+ }+/// How the stream travels, e.g. "Direct · Local network".pub fn via(&self) -> &str {&self.via@@ -345,75 +405,101 @@ impl DesktopView {let (engine, machine_id, wanted, mut display) = (self.engine.clone(), self.machine.clone(), self.width, self.display.clone().unwrap_or_default());let (canvas, pending) = (self.canvas.clone(), self.pending.clone());let rt = engine.runtime().clone();- rt.spawn(async move {- let Some((spec, _)) = engine.machine(&machine_id) else {- let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".into(), false));- return;- };- if engine.is_demo() {- let _ = tx.unbounded_send(Msg::Ended("The demo has no desktops to show.".into(), false));- return;- }- // Its monitors as they are now (one may have been added, removed- // or resized since), for the picker; a gone one falls back to the default.- if let Ok(displays) = engine.displays(&machine_id).await {- if !display.is_empty() && display != "all" && !displays.iter().any(|d| d.id == display) {- display.clear();- let _ = tx.unbounded_send(Msg::Gone);- }- // The default: the main monitor (the agent's own default on- // Linux is the whole desktop).- if display.is_empty()- && displays.iter().any(|d| d.id == "all")- && let Some(main) = displays.iter().find(|d| d.main && d.id != "all")- {- display = main.id.clone();- }- }- let Some(link) = crate::fleet::link::get(&spec).await else {- let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name), true));- return;- };- let network = link.network();- // Full resolution on a local network; 1080p further away.- let width = wanted.unwrap_or(if matches!(network, Some("Local network" | "This computer")) { NATIVE } else { 1920 });- let via = [Some(if link.transport() == "direct" { "Direct" } else { "Over ssh" }), network].into_iter().flatten().collect::<Vec<_>>().join(" · ");- let (channel, mut frames) = link.open_channel();- let request = json!({ "op": "desktop", "channel": channel, "fps": 30, "quality": 78, "max_width": width, "tiles": true, "display": display });- match link.request(request, Duration::from_secs(20)).await {- Ok(r) if r["ok"].as_bool() == Some(true) => {- let (w, h) = (r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32);- let note = r["note"].as_str().map(str::to_string);- let _ = tx.unbounded_send(Msg::Ready(Arc::new(Remote { link: link.clone(), channel }), w, h, format!("{via}|{width}"), note));+ if let Some(joined) = self.shared.clone() {+ let (tx, quality) = (tx.clone(), self.quality);+ rt.spawn(async move {+ let (channel, reply, mut frames) = match joined.open(json!({ "op": "desktop", "quality": quality })).await {+ Ok(opened) => opened,+ Err(e) => {+ let _ = tx.unbounded_send(Msg::Ended(e, false));+ return;+ }+ };+ let (w, h) = (reply["width"].as_u64().unwrap_or(0) as u32, reply["height"].as_u64().unwrap_or(0) as u32);+ let _ = tx.unbounded_send(Msg::Ready(Arc::new(Remote::Shared(joined, channel)), w, h, "Shared".into(), None));+ while let Some((kind, bytes)) = frames.recv().await {+ if kind != TILES && kind != FRAME {+ continue;+ }+ let canvas = canvas.clone();+ let changed = tokio::task::spawn_blocking(move || if kind == TILES { paint_tiles(&canvas, &bytes) } else { paint_frame(&canvas, &bytes) }).await.unwrap_or(false);+ if changed && !pending.swap(true, std::sync::atomic::Ordering::AcqRel) && tx.unbounded_send(Msg::Changed).is_err() {+ return;+ }}- Ok(r) => {- link.close_channel(channel);- let why = r["error"].as_str().unwrap_or("The machine can't show its desktop.").to_string();- let _ = tx.unbounded_send(if r["no_session"].as_bool() == Some(true) { Msg::NoScreen(why) } else { Msg::Ended(why, false) });+ let _ = tx.unbounded_send(Msg::Ended("They stopped sharing the desktop.".into(), false));+ });+ } else {+ rt.spawn(async move {+ let Some((spec, _)) = engine.machine(&machine_id) else {+ let _ = tx.unbounded_send(Msg::Ended("That machine is gone.".into(), false));return;- }- Err(e) => {- link.close_channel(channel);- let _ = tx.unbounded_send(Msg::Ended(e, true));+ };+ if engine.is_demo() {+ let _ = tx.unbounded_send(Msg::Ended("The demo has no desktops to show.".into(), false));return;}- }- while let Some((kind, bytes)) = frames.recv().await {- if kind != TILES && kind != FRAME {- continue;+ // Its monitors as they are now (one may have been added, removed+ // or resized since), for the picker; a gone one falls back to the default.+ if let Ok(displays) = engine.displays(&machine_id).await {+ if !display.is_empty() && display != "all" && !displays.iter().any(|d| d.id == display) {+ display.clear();+ let _ = tx.unbounded_send(Msg::Gone);+ }+ // The default: the main monitor (the agent's own default on+ // Linux is the whole desktop).+ if display.is_empty()+ && displays.iter().any(|d| d.id == "all")+ && let Some(main) = displays.iter().find(|d| d.main && d.id != "all")+ {+ display = main.id.clone();+ }}- // Decoding is real work; keep it off the runtime's async threads.- let canvas = canvas.clone();- let changed = tokio::task::spawn_blocking(move || if kind == TILES { paint_tiles(&canvas, &bytes) } else { paint_frame(&canvas, &bytes) })- .await- .unwrap_or(false);- // One draw request at a time; the view takes the newest picture.- if changed && !pending.swap(true, std::sync::atomic::Ordering::AcqRel) && tx.unbounded_send(Msg::Changed).is_err() {+ let Some(link) = crate::fleet::link::get(&spec).await else {+ let _ = tx.unbounded_send(Msg::Ended(format!("Can't reach the agent on {}.", spec.name), true));return;+ };+ let network = link.network();+ // Full resolution on a local network; 1080p further away.+ let width = wanted.unwrap_or(if matches!(network, Some("Local network" | "This computer")) { NATIVE } else { 1920 });+ let via = [Some(if link.transport() == "direct" { "Direct" } else { "Over ssh" }), network].into_iter().flatten().collect::<Vec<_>>().join(" · ");+ let (channel, mut frames) = link.open_channel();+ let request = json!({ "op": "desktop", "channel": channel, "fps": 30, "quality": 78, "max_width": width, "tiles": true, "display": display });+ match link.request(request, Duration::from_secs(20)).await {+ Ok(r) if r["ok"].as_bool() == Some(true) => {+ let (w, h) = (r["width"].as_u64().unwrap_or(0) as u32, r["height"].as_u64().unwrap_or(0) as u32);+ let note = r["note"].as_str().map(str::to_string);+ let _ = tx.unbounded_send(Msg::Ready(Arc::new(Remote::Link(link.clone(), channel)), w, h, format!("{via}|{width}"), note));+ }+ Ok(r) => {+ link.close_channel(channel);+ let why = r["error"].as_str().unwrap_or("The machine can't show its desktop.").to_string();+ let _ = tx.unbounded_send(if r["no_session"].as_bool() == Some(true) { Msg::NoScreen(why) } else { Msg::Ended(why, false) });+ return;+ }+ Err(e) => {+ link.close_channel(channel);+ let _ = tx.unbounded_send(Msg::Ended(e, true));+ return;+ }}- }- let _ = tx.unbounded_send(Msg::Ended("The desktop stream stopped.".into(), true));- });+ while let Some((kind, bytes)) = frames.recv().await {+ if kind != TILES && kind != FRAME {+ continue;+ }+ // Decoding is real work; keep it off the runtime's async threads.+ let canvas = canvas.clone();+ let changed = tokio::task::spawn_blocking(move || if kind == TILES { paint_tiles(&canvas, &bytes) } else { paint_frame(&canvas, &bytes) })+ .await+ .unwrap_or(false);+ // One draw request at a time; the view takes the newest picture.+ if changed && !pending.swap(true, std::sync::atomic::Ordering::AcqRel) && tx.unbounded_send(Msg::Changed).is_err() {+ return;+ }+ }+ let _ = tx.unbounded_send(Msg::Ended("The desktop stream stopped.".into(), true));+ });+ }let feed = cx.spawn_in(window, async move |this, cx| {while let Some(first) = rx.next().await {@@ -575,7 +661,7 @@ impl DesktopView {}fn send(&self, event: Value) {- if let Some(r) = &self.remote {+ if let Some(r) = self.remote.as_ref().filter(|_| self.can_control) {r.input(event);}}@@ -592,6 +678,9 @@ impl DesktopView {}fn mouse_button(&mut self, button: MouseButton, position: Point<Pixels>, down: bool, window: &mut Window, cx: &mut Context<Self>) {+ if !self.can_control {+ return;+ }let b = match button {MouseButton::Left => 1,MouseButton::Middle => 2,@@ -647,6 +736,9 @@ impl DesktopView {}fn key(&mut self, key: &str, down: bool, cx: &mut Context<Self>) {+ if !self.can_control {+ return;+ }if let Some(sym) = keysym(key) {self.send(json!({ "t": "key", "keysym": sym, "down": down }));self.keys_down.retain(|x| *x != sym);diff --git a/src/ui/detail.rs b/src/ui/detail.rsindex 2a1d4f5..0775925 100644--- a/src/ui/detail.rs+++ b/src/ui/detail.rs@@ -111,6 +111,9 @@ impl Root {.into_any_element(),);}+ if !self.engine.is_demo() {+ buttons.push(self.machine_share_button(&m, m.host.is_empty() || offline, cx));+ }{let mid = m.id.clone();buttons.push(diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rsindex e1980d6..34722af 100644--- a/src/ui/dialogs.rs+++ b/src/ui/dialogs.rs@@ -42,6 +42,8 @@ pub enum DialogEvent {DisplayAdded(String, String),/// A share joined and let in: open its session.JoinedShare(super::share::JoinedHandle),+ /// Open the Join dialog instead (with a link pasted here).+ JoinShare(Option<String>),}pub(super) fn frame(theme: &Theme, title: impl Into<SharedString>, intro: Option<SharedString>) -> gpui::Div {@@ -104,6 +106,8 @@ pub struct AddMachineDialog {network: Option<Vec<crate::fleet::discover::NetworkHost>>,/// What to do before a picked machine can be added (a Mac with Remote Login off).note: Option<String>,+ /// A share link pasted where a machine goes: joined instead.+ share_link: Option<String>,error: Option<String>,_subscriptions: Vec<Subscription>,}@@ -119,6 +123,7 @@ impl AddMachineDialog {InputEvent::Cancel => cx.emit(DialogEvent::Dismissed),InputEvent::Changed => {this.error = None;+ this.share_link = [&this.name, &this.host].into_iter().map(|i| i.read(cx).text().trim().to_string()).find(|t| crate::share::ticket::Ticket::parse(t).is_ok());cx.notify()}};@@ -143,7 +148,7 @@ impl AddMachineDialog {}).detach();let hosts = if engine.demo_world().is_some() { Vec::new() } else { ssh_hosts() };- AddMachineDialog { engine, name, host, hosts, tailnet: Vec::new(), network: None, note: None, error: None, _subscriptions: subs }+ AddMachineDialog { engine, name, host, hosts, tailnet: Vec::new(), network: None, note: None, share_link: None, error: None, _subscriptions: subs }}pub fn first_focus(&self, cx: &App) -> FocusHandle {@@ -151,6 +156,10 @@ impl AddMachineDialog {}fn submit(&mut self, cx: &mut Context<Self>) {+ if let Some(link) = self.share_link.clone() {+ cx.emit(DialogEvent::JoinShare(Some(link)));+ return;+ }let machine = NewMachine { name: self.name.read(cx).text().to_string(), host: self.host.read(cx).text().to_string() };match self.engine.add_machine(machine) {Ok(id) => cx.emit(DialogEvent::MachineAdded(id)),@@ -264,6 +273,27 @@ impl Render for AddMachineDialog {.children(self.note.clone().map(|n| {div().flex().items_start().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(icon("info", 13., theme.info)).child(div().flex_1().min_w(px(0.)).child(n))}))+ // Someone else's machine comes by link: a way there, or the link pasted here.+ .child({+ let (text, button) = match &self.share_link {+ Some(_) => ("That's a share link: join it instead.", Button::new("am-join", "Join").style(ButtonStyle::Primary)),+ None => ("Someone sent you a link to their machine or session?", Button::new("am-join", "Join a share…").style(ButtonStyle::Outlined)),+ };+ let link = self.share_link.clone();+ div()+ .flex()+ .items_center()+ .gap(px(10.))+ .px(px(12.))+ .py(px(9.))+ .rounded(px(9.))+ .border_1()+ .border_color(if link.is_some() { theme.accent } else { theme.border_variant })+ .bg(theme.surface)+ .child(icon("link", 14., theme.text_muted))+ .child(div().flex_1().min_w(px(0.)).text_size(px(12.5)).text_color(theme.text_muted).child(text))+ .child(button.icon("link").on_click(cx.listener(move |_, _, _, cx| cx.emit(DialogEvent::JoinShare(link.clone())))))+ }).children(error_line(&theme, &self.error)).child(footer(vec![Button::new("am-cloud", "New cloud machine…").style(ButtonStyle::Ghost).icon("cloud").on_click(cx.listener(|_, _, _, cx| cx.emit(DialogEvent::NewCloudMachine))).into_any_element(),diff --git a/src/ui/input.rs b/src/ui/input.rsindex b5c96c7..4b7aa21 100644--- a/src/ui/input.rs+++ b/src/ui/input.rs@@ -8,7 +8,7 @@ use gpui::{App, Bounds, ClipboardItem, Context, CursorStyle, ElementId, ElementInputHandler, Entity,EntityInputHandler, EventEmitter, FocusHandle, Focusable, GlobalElementId, KeyBinding, LayoutId,MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point, ShapedLine,- SharedString, Style, TextRun, UTF16Selection, Window, actions, div, fill, point, prelude::*, px,+ SharedString, Style, TextRun, UTF16Selection, Window, actions, anchored, deferred, div, fill, point, prelude::*, px,relative, size,};use unicode_segmentation::UnicodeSegmentation;@@ -68,6 +68,8 @@ pub struct TextInput {secret: bool,/// No frame of its own (it sits in one, like the palette's).bare: bool,+ /// Its right-click menu (Cut, Copy, Paste, Select All), where it opened.+ menu: Option<Point<Pixels>>,}impl EventEmitter<InputEvent> for TextInput {}@@ -88,6 +90,7 @@ impl TextInput {mono: false,secret: false,bare: false,+ menu: None,}}@@ -218,6 +221,78 @@ impl TextInput {}}+ /// Right-click: the edit menu, with the cursor where it was clicked+ /// (a selection stays, to cut or copy).+ fn on_right_mouse_down(&mut self, event: &MouseDownEvent, window: &mut Window, cx: &mut Context<Self>) {+ window.focus(&self.focus_handle);+ if self.selected_range.is_empty() {+ self.move_to(self.index_for_mouse_position(event.position), cx);+ }+ self.menu = Some(event.position);+ cx.notify();+ }++ /// The edit menu: each item runs its action, then it closes.+ fn edit_menu(&self, at: Point<Pixels>, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = cx.theme();+ let selected = !self.selected_range.is_empty() && !self.secret;+ let has_text = !self.content.is_empty();+ let key = |k: &str| if cfg!(target_os = "macos") { format!("⌘{k}") } else { format!("Ctrl+{k}") };+ let items: [(&str, String, bool, fn(&mut Self, &mut Window, &mut Context<Self>)); 4] = [+ ("Cut", key("X"), selected, |this, window, cx| this.cut(&Cut, window, cx)),+ ("Copy", key("C"), selected, |this, window, cx| this.copy(&Copy, window, cx)),+ ("Paste", key("V"), true, |this, window, cx| this.paste(&Paste, window, cx)),+ ("Select All", key("A"), has_text, |this, window, cx| this.select_all(&SelectAll, window, cx)),+ ];+ let rows = items.into_iter().enumerate().map(|(i, (label, keys, on, run))| {+ div()+ .id(("input-menu", i))+ .flex()+ .items_center()+ .h(px(28.))+ .mx(px(4.))+ .px(px(10.))+ .rounded(px(6.))+ .text_size(px(13.))+ .text_color(theme.text)+ .when(!on, |d| d.opacity(0.4))+ .when(on, |d| {+ d.cursor_pointer().hover(|st| st.bg(theme.element_hover)).on_mouse_down(+ MouseButton::Left,+ cx.listener(move |this, _, window, cx| {+ cx.stop_propagation();+ this.menu = None;+ run(this, window, cx);+ cx.notify();+ }),+ )+ })+ .child(div().flex_1().child(label))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(keys))+ });+ deferred(+ anchored().position(at).snap_to_window_with_margin(px(8.)).child(+ div()+ .id("input-menu")+ .occlude()+ .w(px(190.))+ .py(px(4.))+ .rounded(px(9.))+ .bg(theme.elevated)+ .border_1()+ .border_color(theme.border)+ .shadow_lg()+ .font_family(ui_font())+ .children(rows)+ .on_mouse_down_out(cx.listener(|this, _, _, cx| {+ this.menu = None;+ cx.notify();+ })),+ ),+ )+ .with_priority(2)+ }+fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _: &mut Context<Self>) {self.is_selecting = false;}@@ -665,6 +740,7 @@ impl Render for TextInput {.on_action(cx.listener(Self::enter)).on_action(cx.listener(Self::escape)).on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))+ .on_mouse_down(MouseButton::Right, cx.listener(Self::on_right_mouse_down)).on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up)).on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up)).on_mouse_move(cx.listener(Self::on_mouse_move))@@ -681,6 +757,7 @@ impl Render for TextInput {.line_height(px(18.)).overflow_hidden().child(TextElement { input: cx.entity() })+ .children(self.menu.map(|at| self.edit_menu(at, cx)))}}diff --git a/src/ui/menu.rs b/src/ui/menu.rsindex 23c56b2..2a1db43 100644--- a/src/ui/menu.rs+++ b/src/ui/menu.rs@@ -31,6 +31,11 @@ pub enum MenuTarget {Editors { machine: String, path: String },/// A shared session's guests and link (by session id).Share(String),+ /// A share someone gave you (by its id here), one of its machine's+ /// sessions, its desktop.+ Joined(String),+ JoinedSession(String, String),+ JoinedDesktop(String),}pub struct ContextMenu {@@ -100,11 +105,15 @@ enum Action {/// A share's guest: let in (or not), let type (or not), removed.ShareAdmit(String, u64, bool),ShareTyping(String, u64, bool),+ ShareControl(String, u64, bool),+ ShareManage(String, u64, bool),ShareRemove(String, u64),ShareExtend(String),ShareStop(String),/// The Share dialog of a session (its link and options).ShareOptions(String),+ /// Something to do with a share someone gave you.+ Joined(String, super::share::JoinedAction),}enum Item {@@ -345,14 +354,45 @@ impl Root {items.push(Item::Action { label: "End session…".into(), glyph: Glyph::Icon("power"), action: Action::End(id.clone()), danger: true });items}+ MenuTarget::Joined(id) | MenuTarget::JoinedSession(id, _) | MenuTarget::JoinedDesktop(id) => self+ .joined_menu(&menu.target)+ .into_iter()+ .map(|item| {+ use super::share::JoinedItem;+ let glyph_of = |glyph: &'static str| if glyph.is_empty() { Glyph::None } else { Glyph::Icon(glyph) };+ match item {+ JoinedItem::Do { label, glyph, action, danger, picked } => {+ Item::Action { label, glyph: if picked { Glyph::Selected } else { glyph_of(glyph) }, action: Action::Joined(id.clone(), action), danger }+ }+ JoinedItem::Agent { label, agent, action: Some(action) } => Item::Action { label, glyph: Glyph::Agent(agent), action: Action::Joined(id.clone(), action), danger: false },+ JoinedItem::Agent { label, agent, action: None } => Item::Off { label, glyph: Glyph::Agent(agent) },+ JoinedItem::Off { label, glyph } => Item::Off { label, glyph: glyph_of(glyph) },+ JoinedItem::Note(text) => Item::Note(text),+ JoinedItem::Separator => Item::Separator,+ }+ })+ .collect(),MenuTarget::Share(sid) => {let Some(share) = self.share_of(sid).cloned() else { return Vec::new() };let mut items = vec![Item::Note(format!("Ends in {}", super::share::time_left(share.ends_at)))];+ if let Some(problem) = &share.problem {+ items.insert(0, Item::Note(format!("Guests can't reach {} right now: {problem}", share.target.machine_name)));+ }if share.guests.is_empty() {items.push(Item::Note("No one has joined yet.".into()));}for g in &share.guests {- let state = if g.state == "waiting" { "waiting" } else if g.can_type { "typing" } else { "watching" };+ let state = if g.state == "waiting" {+ "waiting"+ } else if g.can_manage {+ "can start sessions"+ } else if g.can_control {+ "using the desktop"+ } else if g.can_type {+ "typing"+ } else {+ "watching"+ };let how = if g.client == "browser" { "browser" } else { "Muxin" };let path = if g.path.is_empty() { String::new() } else { format!(" · {}", g.path) };items.push(Item::Separator);@@ -363,6 +403,14 @@ impl Root {} else {let label = if g.can_type { format!("Stop {} typing", g.name) } else { format!("Let {} type", g.name) };items.push(act(&label, "keyboard", Action::ShareTyping(share.id.clone(), g.id, !g.can_type)));+ if share.target.is_machine() && g.can_type {+ let label = if g.can_manage { format!("Stop {} starting sessions", g.name) } else { format!("Let {} start and end sessions", g.name) };+ items.push(act(&label, "square-terminal", Action::ShareManage(share.id.clone(), g.id, !g.can_manage)));+ }+ if share.desktop == crate::share::host::Desktop::Control {+ let label = if g.can_control { format!("Stop {} using the desktop", g.name) } else { format!("Let {} use the desktop", g.name) };+ items.push(act(&label, "monitor", Action::ShareControl(share.id.clone(), g.id, !g.can_control)));+ }items.push(Item::Action { label: format!("Remove {}", g.name), glyph: Glyph::Icon("user-x"), action: Action::ShareRemove(share.id.clone(), g.id), danger: true });}}@@ -591,9 +639,12 @@ impl Root {}Action::ShareAdmit(share, guest, yes) => crate::share::host::admit(&share, guest, yes),Action::ShareTyping(share, guest, allowed) => crate::share::host::set_typing(&share, guest, allowed),+ Action::ShareControl(share, guest, allowed) => crate::share::host::set_control(&share, guest, allowed),+ Action::ShareManage(share, guest, allowed) => crate::share::host::set_managing(&share, guest, allowed),Action::ShareRemove(share, guest) => crate::share::host::remove(&share, guest),Action::ShareExtend(share) => crate::share::host::extend(&share, std::time::Duration::from_secs(3600)),Action::ShareOptions(session) => self.show_share(&session, window, cx),+ Action::Joined(id, action) => self.run_joined(&id, action, window, cx),Action::ShareStop(share) => {crate::share::host::stop(&share);self.notify_user("Stopped sharing. The link doesn't work anymore.", false, cx);diff --git a/src/ui/palette.rs b/src/ui/palette.rsindex b527fb6..fa41bf8 100644--- a/src/ui/palette.rs+++ b/src/ui/palette.rs@@ -293,12 +293,14 @@ impl Root {Command::NewVm => self.show_vm_dialog(None, window, cx),Command::NewSchedule => self.show_schedule_dialog(None, window, cx),Command::NewSession => self.show_new_session(None, window, cx),- Command::JoinShare => self.show_join(None, window, cx),- Command::Share => {- if let Route::Session(id) = self.route.clone() {- self.show_share(&id, window, cx);- }+ Command::JoinShare => {+ self.show_join(None, window, cx);}+ Command::Share => match self.route.clone() {+ Route::Session(id) => self.show_share(&id, window, cx),+ Route::Machine(id) => self.show_share(&format!("machine:{id}"), window, cx),+ _ => {}+ },Command::NewWorkspace => self.show_new_workspace(None, window, cx),Command::CopyFiles => self.show_copy_files(None, None, window, cx),Command::CheckMachines => self.engine.trigger_check(None),@@ -478,6 +480,7 @@ impl Root {let rename = self.rename_target().map(|(_, name)| item(&format!("Rename {name}…"), "pencil", None, Run::Do(Command::Rename)));let share = match &self.route {Route::Session(id) if !self.engine.is_demo() => self.snapshot.sessions.iter().find(|x| &x.id == id && x.persistent).map(|x| item(&format!("Share {}…", x.title), "link", None, Run::Do(Command::Share))),+ Route::Machine(id) if !self.engine.is_demo() => self.snapshot.machines.iter().find(|m| &m.id == id && !m.is_down()).map(|m| item(&format!("Share {}…", m.name), "link", None, Run::Do(Command::Share))),_ => None,};let all = [@@ -488,7 +491,7 @@ impl Root {item("Go to Schedules", "clock", Some("schedules"), Run::Go(Route::Schedules)),item("New session…", "square-terminal", Some("new-session"), Run::Do(Command::NewSession)),item("New workspace…", "layers", None, Run::Do(Command::NewWorkspace)),- item("Join a shared session…", "link", None, Run::Do(Command::JoinShare)),+ item("Join a share…", "link", None, Run::Do(Command::JoinShare)),item("Copy files between machines…", "folder", None, Run::Do(Command::CopyFiles)),item("Go to Overview", "gauge", Some("overview"), Run::Go(Route::Overview)),item("Go to Jobs", "workflow", Some("jobs"), Run::Go(Route::Jobs)),diff --git a/src/ui/root.rs b/src/ui/root.rsindex 7b26340..afca494 100644--- a/src/ui/root.rs+++ b/src/ui/root.rs@@ -53,6 +53,7 @@ actions!(ToggleActivity,ToggleSidebar,AddMachine,+ JoinShare,NewSession,SplitRight,SplitDown,@@ -149,6 +150,8 @@ pub fn menus() -> Vec<Menu> {MenuItem::separator(),MenuItem::action("Add Machine…", AddMachine),MenuItem::action("New Session…", NewSession),+ MenuItem::separator(),+ MenuItem::action("Join a Share…", JoinShare),],},Menu {@@ -411,7 +414,7 @@ pub struct Root {pub(super) shares: Vec<crate::share::host::ShareView>,pub(super) knocks_seen: HashSet<(String, u64)>,/// Sessions others shared with you, joined here.- pub(super) joined: Vec<super::share::JoinedSession>,+ pub(super) joined: Vec<super::share::JoinedShare>,pub(super) joined_count: u32,/// A share link opened with Muxin, for the Join dialog on the next render.pending_join: Option<String>,@@ -1013,7 +1016,14 @@ impl Root {"activity" => self.show(Route::Activity, cx),"about" => self.navigate(Route::About, window, cx),// A share link, in the Join dialog.- "join" => self.show_join((!arg.is_empty()).then(|| arg.to_string()), window, cx),+ "join" => {+ self.show_join((!arg.is_empty()).then(|| arg.to_string()), window, cx);+ }+ // A share link, joined right away (for screenshots).+ "join-go" => {+ let dialog = self.show_join(Some(arg.to_string()), window, cx);+ dialog.update(cx, |d, cx| d.join(cx));+ }// The Share dialog for a session."share" => self.show_share(arg, window, cx),// "desktop:<machine>", or "desktop:<machine>@<display>" for one of its displays.@@ -1800,6 +1810,9 @@ impl Root {DialogEvent::OpenSettings => self.open_settings_tab(super::settings::SettingsTab::GitHub, window, cx),DialogEvent::OpenCloudSettings => self.open_settings_tab(super::settings::SettingsTab::Cloud, window, cx),DialogEvent::NewCloudMachine => self.show_cloud_dialog(window, cx),+ DialogEvent::JoinShare(link) => {+ let _ = self.show_join(link.clone(), window, cx);+ }DialogEvent::NewVm => self.show_vm_dialog(None, window, cx),DialogEvent::ScheduleSaved => {self.notify_user("Scheduled".to_string(), false, cx);@@ -1996,6 +2009,10 @@ impl Root {self.show_add_machine(window, cx);}+ fn join_share(&mut self, _: &JoinShare, window: &mut Window, cx: &mut Context<Self>) {+ let _ = self.show_join(None, window, cx);+ }+/// ⌘T: a new session on the machine being looked at, if any.fn new_session(&mut self, _: &NewSession, window: &mut Window, cx: &mut Context<Self>) {let machine = match &self.route {@@ -2050,7 +2067,7 @@ impl Root {let runner_machines: Vec<&Machine> = Self::machine_order(&s, &favorites);let unassigned: Vec<&Runner> = s.runners.iter().filter(|r| r.machine_id.is_none() && matches_runner(r)).collect();- rows.push(self.section_header("Machines", runner_machines.len(), true, cx).into_any_element());+ rows.push(self.section_header("Machines", Some(runner_machines.len()), Some(SectionAdd::Machine), cx).into_any_element());let pinned_desktops = cx.global::<super::theme::Appearance>().desktops.clone();let forwards = self.engine.forwards();// The tree: where each machine sits (not while searching, which lists them flat).@@ -2145,12 +2162,14 @@ impl Root {}self.sidebar_indent.set(0.);}- if !self.joined.is_empty() {- rows.push(self.section_header("Shared with you", self.joined.len(), false, cx).into_any_element());+ // Always there (but in the demo), so joining a share is easy to find.+ if !self.engine.is_demo() {+ let count = (!self.joined.is_empty()).then_some(self.joined.len());+ rows.push(self.section_header("Shared with you", count, Some(SectionAdd::Share), cx).into_any_element());rows.extend(self.joined_rows(&theme, cx));}if !unassigned.is_empty() {- rows.push(self.section_header("On GitHub only", unassigned.len(), false, cx).into_any_element());+ rows.push(self.section_header("On GitHub only", Some(unassigned.len()), None, cx).into_any_element());for r in unassigned {rows.push(self.runner_row(&theme, &s, r, selected_runner.as_deref() == Some(&r.id), cx).into_any_element());}@@ -2320,7 +2339,7 @@ impl Root {.on_click(cx.listener(|this, _, _, cx| this.show(Route::Activity, cx)))}- fn section_header(&self, title: &'static str, count: usize, with_add: bool, cx: &mut Context<Self>) -> impl IntoElement {+ fn section_header(&self, title: &'static str, count: Option<usize>, add: Option<SectionAdd>, cx: &mut Context<Self>) -> impl IntoElement {let theme = cx.theme();div().flex()@@ -2334,15 +2353,16 @@ impl Root {.font_weight(FontWeight::MEDIUM).text_color(theme.text_placeholder).child(title)- .child(div().font_family(mono_font()).child(count.to_string()))+ .children(count.map(|n| div().font_family(mono_font()).child(n.to_string()))).child(div().flex_1())- .when(with_add, |d| {- d.child(- Button::icon_only("sidebar-add-machine", "plus")- .tooltip(tip("Add machine", &super::shortcuts::label_for(cx, "add-machine")))- .on_click(cx.listener(|this, _, window, cx| this.show_add_machine(window, cx))),- )- })+ .children(add.map(|add| match add {+ SectionAdd::Machine => Button::icon_only("sidebar-add-machine", "plus")+ .tooltip(tip("Add machine", &super::shortcuts::label_for(cx, "add-machine")))+ .on_click(cx.listener(|this, _, window, cx| this.show_add_machine(window, cx))),+ SectionAdd::Share => Button::icon_only("sidebar-join-share", "plus").tooltip("Join a share (paste a link someone sent you)").on_click(cx.listener(|this, _, window, cx| {+ let _ = this.show_join(None, window, cx);+ })),+ }))}#[allow(clippy::too_many_arguments)]@@ -2816,7 +2836,13 @@ impl Root {fn render_toolbar(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {let theme = cx.theme();let s = self.snapshot.clone();- let (section, title) = route_title(&s, &self.route);+ let (section, mut title) = route_title(&s, &self.route);+ // A shared machine goes by its name.+ if let Route::Shared(id) = &self.route+ && let Some(j) = self.joined.iter().find(|j| &j.id == id && j.info.whole_machine)+ {+ title = j.info.title.clone();+ }// Without the sidebar, the macOS window buttons sit on this bar.let traffic_lights = self.sidebar_hidden && cfg!(target_os = "macos") && !window.is_fullscreen();div()@@ -3243,7 +3269,7 @@ impl Root {}},Route::About => self.render_about(cx),- Route::Shared(id) => self.render_joined(&id, window, cx),+ Route::Shared(id) => self.render_joined(&id, cx),Route::Github | Route::GithubRepo(_) | Route::GithubItem(..) => self.render_github(window, cx),Route::Settings => match &self.settings {Some(page) => page.clone().into_any_element(),@@ -3259,7 +3285,7 @@ impl Root {impl Render for Root {fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {if let Some(link) = self.pending_join.take() {- self.show_join(Some(link), window, cx);+ let _ = self.show_join(Some(link), window, cx);}let theme = cx.theme();// A drag released outside the window never reaches `on_drop`.@@ -3288,6 +3314,8 @@ impl Render for Root {let modal_top = if window_height > 800. { 96. } else { 40. };let modal_max_height = (window_height - modal_top - 24.).max(200.);let page = self.render_page(window, cx);+ // Someone asking to join a share: over whatever page shows.+ let knocks = self.knock_cards(cx);let modal = self.modal.as_ref().map(|m| match m {Modal::AddMachine(d) => d.clone().into_any_element(),Modal::Install(d) => d.clone().into_any_element(),@@ -3340,6 +3368,7 @@ impl Render for Root {.on_action(cx.listener(Self::go_forward)).on_action(cx.listener(Self::toggle_activity)).on_action(cx.listener(Self::add_machine))+ .on_action(cx.listener(Self::join_share)).on_action(cx.listener(Self::new_session)).on_action(cx.listener(|this, _: &SplitRight, window, cx| this.split_session(false, window, cx))).on_action(cx.listener(|this, _: &SplitDown, window, cx| this.split_session(true, window, cx)))@@ -3378,7 +3407,14 @@ impl Render for Root {.flex_1().min_w(px(0.)).child(self.render_toolbar(window, cx))- .child(div().flex_1().min_h(px(0.)).child(page)),+ .child(+ div()+ .relative()+ .flex_1()+ .min_h(px(0.))+ .child(page)+ .when(!knocks.is_empty(), |d| d.child(div().absolute().top_0().left_0().right_0().flex().flex_col().children(knocks))),+ ),).when(!self.sidebar_hidden, |d| d.child(self.sidebar_handle(&theme, cx))).on_action(cx.listener(|this, _: &ToggleSidebar, _, cx| this.toggle_sidebar(cx)))@@ -3423,6 +3459,13 @@ impl Focusable for Root {}}+/// What a sidebar section's + adds.+#[derive(Clone, Copy)]+enum SectionAdd {+ Machine,+ Share,+}+pub(super) fn github_status(theme: &Theme, s: &Snapshot) -> (gpui::Hsla, String) {let g = &s.github;if g.token_source.is_empty() && !s.demo {diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 293cd16..34232c1 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -687,15 +687,7 @@ impl Root {}None => body.into_any_element(),};- // Over the terminal, not above it: the session keeps its size.- let knocks = self.knock_cards(&info.id, cx);- let body = div()- .relative()- .flex_1()- .min_h(px(0.))- .flex()- .child(body)- .when(!knocks.is_empty(), |d| d.child(div().absolute().top_0().left_0().right_0().flex().flex_col().children(knocks)));+ let body = div().flex_1().min_h(px(0.)).flex().child(body);div().size_full().flex().flex_col().child(header).child(body).into_any_element()}diff --git a/src/ui/share.rs b/src/ui/share.rsindex 3e66c66..88132b9 100644--- a/src/ui/share.rs+++ b/src/ui/share.rs@@ -1,26 +1,36 @@-//! Sharing in the window: the Share dialog and the session header's button,-//! letting guests in, and sessions others shared with you (joined from a-//! link). The sharing itself is crate::share.+//! Sharing in the window: the Share dialog (a session, or a whole machine),+//! letting guests in, and shares others gave you (joined from a link). The+//! sharing itself is crate::share.+use std::collections::HashMap;+use std::sync::atomic::{AtomicU32, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;use gpui::{AnyElement, App, ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, SharedString, Subscription, Window, div, prelude::*, px};+use serde_json::json;use tokio::sync::mpsc;+use super::desktop::DesktopView;use super::dialogs::{DialogEvent, error_line, field, footer, frame};use super::input::{InputEvent, TextInput};-use super::kit::{self, Button, ButtonStyle, card, icon};+use super::kit::{self, Button, ButtonStyle, card, icon, section_title};use super::root::{Modal, Route, Root};use super::terminal::{RemoteIo, RemoteOutput, TerminalView};use super::theme::{ActiveTheme, Theme, mono_font};use crate::fleet::Engine;+use crate::fleet::model::Machine;+use crate::fleet::ports::ListeningPort;use crate::fleet::sessions::SessionInfo;+use crate::share::host::{Desktop, Port};use crate::share::{guest, host};/// How long a share lasts: what the dialog offers.const DURATIONS: &[(&str, u64)] = &[("15 min", 15 * 60), ("1 hour", 3600), ("8 hours", 8 * 3600), ("1 day", 24 * 3600)];+/// Sessions of a shared machine kept open at once (switching back is instant).+const OPEN_SESSIONS: usize = 6;+/// "42 min", "3 hours".pub(super) fn time_left(ends_at: i64) -> String {let left = ends_at - chrono::Utc::now().timestamp();@@ -34,19 +44,65 @@ pub(super) fn time_left(ends_at: i64) -> String {}}+/// A share's key in the window: its session's id, or `machine:<id>`.+pub(super) fn share_key(t: &host::Target) -> String {+ if t.is_machine() { format!("machine:{}", t.machine_id) } else { t.session_id.clone() }+}+fn fact(theme: &Theme, glyph: &'static str, text: impl Into<SharedString>) -> impl IntoElement {div().flex().items_center().gap(px(10.)).text_size(px(13.)).text_color(theme.text).child(icon(glyph, 15., theme.text_muted)).child(text.into())}+/// A choice among a few, as a small button (the durations, the desktop).+fn choice(theme: &Theme, id: (&'static str, usize), label: &'static str, picked: bool, enabled: bool) -> gpui::Stateful<gpui::Div> {+ div()+ .id(id)+ .px(px(10.))+ .h(px(26.))+ .flex()+ .items_center()+ .rounded(px(6.))+ .border_1()+ .text_size(px(12.))+ .when(enabled, |d| d.cursor_pointer())+ .text_color(if enabled { theme.text } else { theme.text_placeholder })+ .border_color(if picked { theme.accent } else { theme.border_variant })+ .bg(if picked { theme.accent.opacity(0.12) } else { theme.element })+ .child(label)+}++/// A checkbox that can't be ticked yet (it needs another option first).+fn off_checkbox(theme: &Theme, label: &'static str) -> AnyElement {+ div()+ .flex()+ .items_center()+ .gap(px(8.))+ .text_size(px(12.5))+ .text_color(theme.text_placeholder)+ .child(div().size(px(15.)).rounded(px(4.)).border_1().border_color(theme.border_variant))+ .child(label)+ .into_any_element()+}++/// A server as the user knows it: its page's title, its container, its program.+fn server_name(p: &ListeningPort) -> String {+ p.title.clone().filter(|t| !t.trim().is_empty()).or_else(|| p.container.clone()).or_else(|| Some(p.process.clone()).filter(|x| !x.is_empty())).unwrap_or_else(|| format!("Port {}", p.port))+}+// ----------------------------------------------------------------------------// Sharing a session+// Sharing-/// Sharing a session: one click makes the link and copies it (you let each-/// person in, they watch, for an hour); what they can do and for how long-/// change here afterwards, while it runs.+/// Sharing a session or a machine: one click makes the link and copies it+/// (you let each person in, they watch, for an hour); what they can do and+/// for how long change here afterwards, while it runs.pub struct ShareDialog {engine: Arc<Engine>,target: host::Target,+ /// A machine whose desktop can be shown.+ has_desktop: bool,+ /// A machine's servers, to pick which to share; its other ports shown too.+ servers: Option<Result<Vec<ListeningPort>, String>>,+ all_ports: bool,/// The share, once made.share: Option<String>,creating: bool,@@ -58,12 +114,15 @@ pub struct ShareDialog {impl EventEmitter<DialogEvent> for ShareDialog {}impl ShareDialog {- /// The share this session has, or a new one made right away.- pub fn new(engine: Arc<Engine>, target: host::Target, existing: Option<String>, cx: &mut Context<Self>) -> Self {- let mut dialog = ShareDialog { engine, target, share: existing, creating: false, copied: false, error: None, focus: cx.focus_handle() };+ /// The share this session or machine has, or a new one made right away.+ pub fn new(engine: Arc<Engine>, target: host::Target, has_desktop: bool, existing: Option<String>, cx: &mut Context<Self>) -> Self {+ let mut dialog = ShareDialog { engine, target, has_desktop, servers: None, all_ports: false, share: existing, creating: false, copied: false, error: None, focus: cx.focus_handle() };if dialog.share.is_none() {dialog.create(cx);}+ if dialog.target.is_machine() {+ dialog.load_servers(cx);+ }dialog}@@ -78,7 +137,7 @@ impl ShareDialog {self.creating = true;self.error = None;cx.notify();- let options = host::Options { approve: true, can_type: false, ttl: Duration::from_secs(3600) };+ let options = host::Options { approve: true, can_type: false, manage: false, desktop: Desktop::None, ports: Vec::new(), ttl: Duration::from_secs(3600) };let source = Arc::new(host::EngineSource { engine: self.engine.clone(), machine_id: self.target.machine_id.clone() });let (target, server) = (self.target.clone(), self.engine.settings().share_server());let job = self.engine.runtime().spawn(async move { host::start(&server, target, options, source).await });@@ -100,6 +159,27 @@ impl ShareDialog {.detach();}+ /// What's listening on the machine, sites first.+ fn load_servers(&mut self, cx: &mut Context<Self>) {+ let (engine, id) = (self.engine.clone(), self.target.machine_id.clone());+ let job = engine.runtime().spawn({+ let engine = engine.clone();+ async move { engine.ports(&id).await }+ });+ cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string())).map(|mut list| {+ list.sort_by_key(|p| (!p.is_site(), p.port));+ list.dedup_by_key(|p| p.port);+ list+ });+ let _ = this.update(cx, |this, cx| {+ this.servers = Some(result);+ cx.notify();+ });+ })+ .detach();+ }+fn render_making(&mut self, theme: &Theme, cx: &mut Context<Self>) -> AnyElement {let title = format!("Share {}", self.target.title);match self.error.clone() {@@ -116,26 +196,117 @@ impl ShareDialog {}}+ /// Off, view or control: what guests get of the machine's screen.+ fn desktop_row(&self, theme: &Theme, view: &host::ShareView) -> AnyElement {+ let options = [(Desktop::None, "Off"), (Desktop::View, "View"), (Desktop::Control, "Control")];+ let choices = options.into_iter().enumerate().map(|(i, (d, label))| {+ // Control is for people you let in.+ let enabled = d != Desktop::Control || view.approve;+ let (id, ports) = (view.id.clone(), view.ports.clone());+ choice(theme, ("share-desktop", i), label, view.desktop == d, enabled).when(enabled, |el| el.on_click(move |_, _, _| host::set_access(&id, d, ports.clone())))+ });+ let (note, warn) = match view.desktop {+ Desktop::None => ("They don't see the screen.", false),+ Desktop::View => ("They see the screen, live. You can let someone control it.", false),+ Desktop::Control => ("You choose who can use its mouse and keyboard, as you.", true),+ };+ let note = if view.approve || view.desktop != Desktop::None { note } else { "Control is only for people you let in." };+ div()+ .flex()+ .flex_col()+ .gap(px(5.))+ .child(div().flex().items_center().gap(px(8.)).child(icon("monitor", 14., theme.text_muted)).child(div().flex_1().text_size(px(12.5)).child("Desktop")).children(choices))+ .child(div().pl(px(22.)).text_size(px(11.5)).text_color(if warn { theme.warning } else { theme.text_placeholder }).child(note))+ .into_any_element()+ }++ /// The machine's servers, each one to share or not: its web servers+ /// (and any picked), its other ports on request.+ fn servers_rows(&self, theme: &Theme, view: &host::ShareView, cx: &mut Context<Self>) -> AnyElement {+ let all_ports = self.all_ports;+ let shown = |p: &&ListeningPort| all_ports || p.is_site() || view.ports.iter().any(|x| x.port == p.port);+ let others = match &self.servers {+ Some(Ok(list)) => list.iter().filter(|p| !shown(p)).count(),+ _ => 0,+ };+ let list: AnyElement = match &self.servers {+ None => div().flex().items_center().gap(px(8.)).text_size(px(12.)).text_color(theme.text_muted).child(kit::spinner("share-servers", 12., theme.text_muted)).child("Looking for servers…").into_any_element(),+ Some(Err(e)) => div().text_size(px(12.)).text_color(theme.text_muted).child(e.clone()).into_any_element(),+ Some(Ok(list)) if list.is_empty() => div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("Nothing is listening on {} right now.", self.target.machine_name)).into_any_element(),+ Some(Ok(list)) if !list.iter().any(|p| shown(&p)) => div().text_size(px(12.)).text_color(theme.text_placeholder).child("No web servers there right now.").into_any_element(),+ Some(Ok(list)) => div()+ .flex()+ .flex_col()+ .gap(px(6.))+ .children(list.iter().filter(shown).take(24).map(|p| {+ let on = view.ports.iter().any(|x| x.port == p.port);+ let (id, desktop, ports) = (view.id.clone(), view.desktop, view.ports.clone());+ let port = Port { port: p.port, name: server_name(p), host: p.host.clone() };+ let label = format!("{} · {}", server_name(p), p.port);+ kit::checkbox(theme, ("share-port", p.port as usize), on, label, move |now, _, _| {+ let mut ports = ports.clone();+ ports.retain(|x| x.port != port.port);+ if *now {+ ports.push(port.clone());+ }+ host::set_access(&id, desktop, ports);+ })+ }))+ .into_any_element(),+ };+ div()+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(div().flex().items_center().gap(px(8.)).child(icon("network", 14., theme.text_muted)).child(div().text_size(px(12.5)).child("Servers")))+ .child(+ div()+ .pl(px(22.))+ .flex()+ .flex_col()+ .gap(px(8.))+ .child(list)+ .when(others > 0 || all_ports, |d| {+ d.child(+ div()+ .id("share-all-ports")+ .text_size(px(12.))+ .text_color(theme.text_accent)+ .cursor_pointer()+ .child(if all_ports { "Only web servers".to_string() } else { format!("Show {others} other port{}", if others == 1 { "" } else { "s" }) })+ .on_click(cx.listener(|this, _, _, cx| {+ this.all_ports = !this.all_ports;+ cx.notify()+ })),+ )+ })+ .child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child("They open in Muxin, at localhost on their computer.")),+ )+ .into_any_element()+ }+fn render_share(&mut self, theme: &Theme, view: host::ShareView, cx: &mut Context<Self>) -> AnyElement {let link = view.link.clone();+ let machine = self.target.is_machine();let (id, id2, id3) = (view.id.clone(), view.id.clone(), view.id.clone());let (approve, can_type) = (view.approve, view.can_type);let left = view.ends_at - chrono::Utc::now().timestamp();+ let type_label = if machine { "They can type in sessions" } else { "They can type" };let typing_row = if approve {- kit::checkbox(theme, "share-type", can_type, "They can type", move |on, _, _| host::set_options(&id2, true, *on)).into_any_element()+ kit::checkbox(theme, "share-type", can_type, type_label, move |on, _, _| host::set_options(&id2, true, *on)).into_any_element()} else {- div()- .flex()- .items_center()- .gap(px(8.))- .text_size(px(12.5))- .text_color(theme.text_placeholder)- .child(div().size(px(15.)).rounded(px(4.)).border_1().border_color(theme.border_variant))- .child("They can type")- .into_any_element()+ off_checkbox(theme, type_label)};- frame(theme, format!("Share {}", self.target.title), Some(if self.copied { "Link copied. Send it to anyone: it opens in their browser or in Muxin." } else { "Send the link to anyone: it opens in their browser or in Muxin." }.into()))+ let intro = match (self.copied, machine) {+ (true, false) => "Link copied. Send it to anyone: it opens in their browser or in Muxin.".to_string(),+ (false, false) => "Send the link to anyone: it opens in their browser or in Muxin.".to_string(),+ (copied, true) => format!("{}They see {}'s sessions, in their browser or in Muxin.", if copied { "Link copied. " } else { "" }, self.target.machine_name),+ };+ let what = if machine { "its sessions" } else { "this session" };+ let problem = view.problem.clone().map(|p| format!("Guests can't reach {} right now: {p}", self.target.machine_name));+ frame(theme, format!("Share {}", self.target.title), Some(intro.into())).w(px(540.))+ .children(error_line(theme, &problem)).child(div().flex()@@ -167,7 +338,11 @@ impl ShareDialog {.flex_col().gap(px(3.)).child(kit::checkbox(theme, "share-approve", approve, "Ask me before letting someone in", move |on, _, _| host::set_options(&id, *on, *on && can_type)))- .child(div().pl(px(23.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(if approve { "You see who's asking, and their code." } else { "Anyone with the link can watch." })),+ .child(div().pl(px(23.)).text_size(px(11.5)).text_color(theme.text_placeholder).child(if approve {+ "You see who's asking, and their code.".to_string()+ } else {+ format!("Anyone with the link can watch {what}.")+ })),).child(div()@@ -175,12 +350,35 @@ impl ShareDialog {.flex_col().gap(px(3.)).child(typing_row)- .child(div().pl(px(23.)).text_size(px(11.5)).text_color(if approve && can_type { theme.warning } else { theme.text_placeholder }).child(if approve {- "Their keys go to this session, as you."- } else {- "Only for people you let in."+ .child(div().pl(px(23.)).text_size(px(11.5)).text_color(if approve && can_type { theme.warning } else { theme.text_placeholder }).child(match (approve, machine) {+ (true, false) => "Their keys go to this session, as you.",+ (true, true) => "Their keys go to the session they open, as you.",+ (false, _) => "Only for people you let in.",})),)+ .when(machine, |d| {+ let id = view.id.clone();+ let can = approve && can_type;+ let row = if can {+ kit::checkbox(theme, "share-manage", view.manage, "They can start and end sessions", move |on, _, _| host::set_manage(&id, *on)).into_any_element()+ } else {+ off_checkbox(theme, "They can start and end sessions")+ };+ d.child(+ div()+ .flex()+ .flex_col()+ .gap(px(3.))+ .child(row)+ .child(div().pl(px(23.)).text_size(px(11.5)).text_color(if view.manage { theme.warning } else { theme.text_placeholder }).child(if can {+ format!("A terminal there runs anything, on {} as you.", self.target.machine_name)+ } else {+ "Only for people you let in who can type.".to_string()+ })),+ )+ })+ .when(machine && self.has_desktop, |d| d.child(self.desktop_row(theme, &view)))+ .when(machine, |d| d.child(self.servers_rows(theme, &view, cx))).child(div().flex()@@ -192,20 +390,7 @@ impl ShareDialog {let (secs, id) = (*secs, id3.clone());// The choice closest to what's left shows as picked.let picked = DURATIONS.iter().min_by_key(|(_, d)| (*d as i64 - left).abs()).is_some_and(|(l, _)| l == label);- div()- .id(("share-ttl", i))- .px(px(10.))- .h(px(26.))- .flex()- .items_center()- .rounded(px(6.))- .border_1()- .cursor_pointer()- .text_size(px(12.))- .border_color(if picked { theme.accent } else { theme.border_variant })- .bg(if picked { theme.accent.opacity(0.12) } else { theme.element })- .child(*label)- .on_click(move |_, _, _| host::set_ends_in(&id, Duration::from_secs(secs)))+ choice(theme, ("share-ttl", i), label, picked, true).on_click(move |_, _, _| host::set_ends_in(&id, Duration::from_secs(secs)))})),),)@@ -264,6 +449,8 @@ pub struct JoinedHandle {updates: Arc<Mutex<Option<mpsc::UnboundedReceiver<guest::Update>>>>,info: guest::Info,can_type: bool,+ can_control: bool,+ can_manage: bool,}enum Stage {@@ -314,7 +501,7 @@ impl JoinDialog {cx.emit(DialogEvent::Dismissed);}- fn join(&mut self, cx: &mut Context<Self>) {+ pub(super) fn join(&mut self, cx: &mut Context<Self>) {if !matches!(self.stage, Stage::Form) {return;}@@ -367,12 +554,12 @@ impl JoinDialog {*waiting = true;}}- guest::Update::Admitted { can_type } => {+ guest::Update::Admitted { can_type, can_control, can_manage } => {let info = match &this.stage {Stage::Joined { info, .. } => info.clone().unwrap_or_default(),_ => Default::default(),};- done = Some((info, can_type));+ done = Some((info, can_type, can_control, can_manage));}guest::Update::Denied => {this.stage = Stage::Form;@@ -392,8 +579,8 @@ impl JoinDialog {joined.leave();return;}- if let Some((info, can_type)) = done {- let handle = JoinedHandle { joined: joined.clone(), updates: Arc::new(Mutex::new(Some(rx))), info, can_type };+ if let Some((info, can_type, can_control, can_manage)) = done {+ let handle = JoinedHandle { joined: joined.clone(), updates: Arc::new(Mutex::new(Some(rx))), info, can_type, can_control, can_manage };let _ = this.update(cx, |this, cx| {this.joined = None;cx.emit(DialogEvent::JoinedShare(handle))@@ -404,6 +591,31 @@ impl JoinDialog {}).detach();}++ /// What the guest will get, before going in.+ fn facts(theme: &Theme, i: &guest::Info) -> impl IntoElement {+ let mut facts = div().flex().flex_col().gap(px(8.));+ if i.whole_machine {+ facts = facts.child(fact(theme, if i.can_type { "keyboard" } else { "square-terminal" }, match (i.can_type, i.can_manage) {+ (_, true) => "Its sessions: you can watch, type, start and end them",+ (true, false) => "Its sessions: you can watch and type",+ _ => "Its sessions: you can watch",+ }));+ match i.desktop {+ Desktop::None => {}+ Desktop::View => facts = facts.child(fact(theme, "monitor", "Its screen: you can watch")),+ Desktop::Control if i.can_control => facts = facts.child(fact(theme, "monitor", "Its screen: you can watch and use it")),+ Desktop::Control => facts = facts.child(fact(theme, "monitor", "Its screen: you can watch, and use it when they let you")),+ }+ if !i.ports.is_empty() {+ let n = i.ports.len();+ facts = facts.child(fact(theme, "network", format!("{n} server{} to open here", if n == 1 { "" } else { "s" })));+ }+ } else {+ facts = facts.child(fact(theme, if i.can_type { "keyboard" } else { "eye" }, if i.can_type { "You can watch and type" } else { "You can watch" }));+ }+ facts.child(fact(theme, "clock", format!("Ends in {}", time_left(i.ends_at))))+ }}impl Render for JoinDialog {@@ -412,7 +624,7 @@ impl Render for JoinDialog {match &self.stage {Stage::Form | Stage::Connecting => {let connecting = matches!(self.stage, Stage::Connecting);- frame(&theme, "Join a shared session", Some("Paste the link someone sent you.".into()))+ frame(&theme, "Join a share", Some("Paste the link someone sent you.".into())).child(field(&theme, "Link", self.link.clone(), None)).child(field(&theme, "Your name", self.name.clone(), Some("They see it when you ask to join."))).children(error_line(&theme, &self.error))@@ -429,18 +641,11 @@ impl Render for JoinDialog {}Stage::Joined { code, info, waiting } => {let by = info.as_ref().map(|i| i.by.clone()).unwrap_or_else(|| "them".into());- let title = info.as_ref().map(|i| if i.title.is_empty() { "a session".to_string() } else { i.title.clone() }).unwrap_or_else(|| "a session".into());- let sub = info.as_ref().map(|i| format!("{} on {} · shared by {}", agent_name(&i.agent), i.machine, i.by));+ let title = info.as_ref().map(|i| if i.title.is_empty() { "a session".to_string() } else { i.title.clone() }).unwrap_or_else(|| "a share".into());+ let sub = info.as_ref().map(|i| if i.whole_machine { format!("A machine · shared by {}", i.by) } else { format!("{} on {} · shared by {}", agent_name(&i.agent), i.machine, i.by) });let (a, b) = code.split_at(3.min(code.len()));frame(&theme, format!("Join {title}"), sub.map(SharedString::from))- .children(info.as_ref().map(|i| {- div()- .flex()- .flex_col()- .gap(px(8.))- .child(fact(&theme, if i.can_type { "keyboard" } else { "eye" }, if i.can_type { "You can watch and type" } else { "You can watch" }))- .child(fact(&theme, "clock", format!("Ends in {}", time_left(i.ends_at))))- }))+ .children(info.as_ref().map(|i| Self::facts(&theme, i))).child(div().flex()@@ -475,12 +680,19 @@ fn agent_name(agent: &str) -> &'static str {crate::fleet::sessions::agent(agent).map(|a| a.name).unwrap_or("A session")}-/// Keys for a joined session (dropped unless its host lets us type).-struct GuestIo(Arc<guest::Joined>);+/// Keys for a session open on a share (dropped unless its host lets us type).+struct GuestIo {+ joined: Arc<guest::Joined>,+ /// The session's channel, once open.+ channel: Arc<AtomicU32>,+}impl RemoteIo for GuestIo {fn write(&self, bytes: &[u8]) {- self.0.send_keys(bytes);+ let channel = self.channel.load(Ordering::Relaxed);+ if channel != 0 {+ self.joined.send_keys(channel, bytes);+ }}fn resize(&self, _: u16, _: u16) {}@@ -488,47 +700,105 @@ impl RemoteIo for GuestIo {fn close(&self) {}}-/// A session someone shared with you, open here.-pub struct JoinedSession {+/// A session open on a share.+struct OpenSession {+ /// Its name on the machine ("" for a shared session).+ name: String,+ terminal: Entity<TerminalView>,+ channel: Arc<AtomicU32>,+ /// Why it couldn't be shown.+ error: Option<String>,+}++/// What a share's page shows: a shared machine's own page, one of its+/// sessions (a shared session's is ""), or its desktop.+#[derive(Clone, Debug, PartialEq)]+pub enum Showing {+ Machine,+ Session(String),+ Desktop,+}++/// A share someone gave you, open here: one session, or a machine's.+pub struct JoinedShare {pub id: String,pub info: guest::Info,joined: Arc<guest::Joined>,- pub terminal: Entity<TerminalView>,pub can_type: bool,+ pub can_control: bool,+ /// May start, end and restart its sessions.+ pub can_manage: bool,+ /// A shared machine's sessions.+ sessions: Vec<guest::Session>,+ open: Vec<OpenSession>,+ showing: Showing,+ /// Its screen while it shows (closed when you look elsewhere, so it isn't+ /// streamed for nothing), and the quality picked for it.+ desktop: Option<Entity<DesktopView>>,+ quality: &'static str,+ /// Servers opened here: their port here, or why not.+ servers: HashMap<u16, Result<u16, String>>,/// Why it ended, once it has.pub ended: Option<String>,}impl Root {- /// The Share dialog for a session: its link when it's shared already.- pub(super) fn show_share(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {- let Some(info) = self.snapshot.sessions.iter().find(|x| x.id == session_id).cloned() else { return };- let machine_name = self.snapshot.machines.iter().find(|m| m.id == info.machine_id).map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone());+ /// The Share dialog for a session or (`machine:<id>`) a machine: its link+ /// when it's shared already.+ pub(super) fn show_share(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {let by = self.snapshot.github.login.clone().filter(|l| !l.is_empty()).or_else(|| std::env::var("USER").ok()).unwrap_or_else(|| "Someone".into());- let target = host::Target {- session_id: info.id.clone(),- machine_id: info.machine_id.clone(),- name: info.id.split_once('/').map(|(_, n)| n.to_string()).unwrap_or_default(),- title: info.title.clone(),- agent: info.agent.clone(),- machine_name,- by,+ let (target, has_desktop) = if let Some(mid) = key.strip_prefix("machine:") {+ let Some(m) = self.snapshot.machines.iter().find(|m| m.id == mid) else { return };+ let target = host::Target {+ session_id: String::new(),+ machine_id: m.id.clone(),+ name: String::new(),+ title: m.name.clone(),+ agent: String::new(),+ machine_name: m.name.clone(),+ platform: m.platform.clone(),+ by,+ };+ (target, super::format::has_desktop(m))+ } else {+ let Some(info) = self.snapshot.sessions.iter().find(|x| x.id == key).cloned() else { return };+ let machine = self.snapshot.machines.iter().find(|m| m.id == info.machine_id);+ let target = host::Target {+ session_id: info.id.clone(),+ machine_id: info.machine_id.clone(),+ name: info.id.split_once('/').map(|(_, n)| n.to_string()).unwrap_or_default(),+ title: info.title.clone(),+ agent: info.agent.clone(),+ machine_name: machine.map(|m| m.name.clone()).unwrap_or_else(|| info.machine_id.clone()),+ platform: machine.map(|m| m.platform.clone()).unwrap_or_default(),+ by,+ };+ (target, false)};- let existing = self.share_of(session_id).map(|s| s.id.clone());+ let existing = self.share_of(key).map(|s| s.id.clone());let engine = self.engine.clone();- let dialog = cx.new(|cx| ShareDialog::new(engine, target, existing, cx));+ let dialog = cx.new(|cx| ShareDialog::new(engine, target, has_desktop, existing, cx));self.show_modal(Modal::Share(dialog.clone()), window, cx);self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));}- pub(super) fn share_of(&self, session_id: &str) -> Option<&host::ShareView> {- self.shares.iter().find(|s| s.target.session_id == session_id)+ /// The share of a session, or (`machine:<id>`) of a machine.+ pub(super) fn share_of(&self, key: &str) -> Option<&host::ShareView> {+ self.shares.iter().find(|s| share_key(&s.target) == key)}/// Shares changed (a guest knocked, came in, left): show it, and say/// who's asking to join when they first do.pub(super) fn shares_changed(&mut self, cx: &mut Context<Self>) {- self.shares = host::list();+ let before = std::mem::replace(&mut self.shares, host::list());+ // The machine stopped being reachable for guests: say why, once.+ let news = self.shares.iter().find_map(|s| {+ let was = before.iter().find(|b| b.id == s.id).and_then(|b| b.problem.as_ref());+ s.problem.as_ref().filter(|p| was != Some(*p)).map(|p| format!("Guests can't reach {}: {p}", s.target.machine_name))+ });+ if let Some(news) = news {+ self.notify_user(news, true, cx);+ }let mut knocks = Vec::new();for s in &self.shares {for g in s.guests.iter().filter(|g| g.state == "waiting") {@@ -543,149 +813,195 @@ impl Root {cx.notify();}- /// The session header's Share button, or what's going on with its share.- pub(super) fn share_button(&self, info: &SessionInfo, cx: &mut Context<Self>) -> AnyElement {- let sid = info.id.clone();- let Some(share) = self.share_of(&info.id) else {- return Button::new("session-share", "Share")- .icon("link")- .tooltip("Share this session by link")- .on_click(cx.listener(move |this, _, window, cx| this.show_share(&sid, window, cx)))- .into_any_element();+ /// A Share button, or what's going on with the share: `key` is a+ /// session's id or `machine:<id>`.+ fn shared_button(&self, key: &str, id: &'static str, tooltip: &'static str, disabled: bool, cx: &mut Context<Self>) -> AnyElement {+ let key = key.to_string();+ let Some(share) = self.share_of(&key) else {+ return Button::new(id, "Share").icon("link").tooltip(tooltip).disabled(disabled).on_click(cx.listener(move |this, _, window, cx| this.show_share(&key, window, cx))).into_any_element();};let waiting = share.guests.iter().filter(|g| g.state == "waiting").count();let inside: Vec<&host::GuestView> = share.guests.iter().filter(|g| g.state == "in").collect();- let typing = inside.iter().any(|g| g.can_type);+ let typing = inside.iter().any(|g| g.can_type || g.can_control);let what = match (inside.len(), waiting) {(_, w) if w > 0 => format!("{w} waiting"),(0, _) => "no one yet".to_string(),- (1, _) => format!("{} {}", inside[0].name, if typing { "typing" } else { "watching" }),+ (1, _) => format!("{} {}", inside[0].name, if inside[0].can_control { "in control" } else if typing { "typing" } else { "watching" }),(n, _) => format!("{n} watching"),};- Button::new("session-shared", format!("Shared · {what}"))+ Button::new(SharedString::from(format!("{id}-on")), format!("Shared · {what}")).icon(if typing { "keyboard" } else { "eye" }).style(ButtonStyle::Outlined).tooltip("Who's here, the link, and stopping")- .on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.open_menu(super::menu::MenuTarget::Share(sid.clone()), e.position(), cx)))+ .on_click(cx.listener(move |this, e: &gpui::ClickEvent, _, cx| this.open_menu(super::menu::MenuTarget::Share(key.clone()), e.position(), cx))).into_any_element()}- /// Above a shared session's terminal: each guest waiting to be let in.- pub(super) fn knock_cards(&self, session_id: &str, cx: &mut Context<Self>) -> Vec<AnyElement> {+ /// The session header's Share button, or what's going on with its share.+ pub(super) fn share_button(&self, info: &SessionInfo, cx: &mut Context<Self>) -> AnyElement {+ self.shared_button(&info.id, "session-share", "Share this session by link", false, cx)+ }++ /// The machine page's Share button: its sessions, and its desktop and+ /// servers if you choose.+ pub(super) fn machine_share_button(&self, m: &Machine, disabled: bool, cx: &mut Context<Self>) -> AnyElement {+ self.shared_button(&format!("machine:{}", m.id), "m-share", "Share this machine by link", disabled, cx)+ }++ /// Over the page: each guest waiting to be let in, whatever is showing.+ pub(super) fn knock_cards(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {let theme = cx.theme();- let Some(share) = self.share_of(session_id) else { return Vec::new() };- share- .guests- .iter()- .filter(|g| g.state == "waiting")- .map(|g| {+ let mut cards = Vec::new();+ for share in &self.shares {+ for g in share.guests.iter().filter(|g| g.state == "waiting") {let (share_id, guest_id) = (share.id.clone(), g.id);let share_id2 = share_id.clone();let (a, b) = g.code.split_at(3.min(g.code.len()));let how = if g.client == "browser" { "In a browser" } else { "In Muxin" };- let wants = if share.can_type { "wants to join" } else { "wants to watch" };- div()- .mx(px(20.))- .mt(px(12.))- .flex()- .items_center()- .gap(px(14.))- .p(px(14.))- .rounded(px(10.))- .border_1()- .border_color(theme.accent)- .bg(theme.elevated)- .shadow_lg()- .child(- div()- .size(px(36.))- .flex_none()- .rounded_full()- .bg(theme.accent.opacity(0.25))- .flex()- .items_center()- .justify_center()- .text_size(px(15.))- .font_weight(FontWeight::SEMIBOLD)- .child(g.name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default()),- )- .child(- div()- .flex()- .flex_col()- .flex_1()- .min_w(px(0.))- .gap(px(2.))- .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).child(format!("{} {wants}", g.name)))- .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("{how} · ask {} to read their code", g.name))),- )- .child(- div()- .flex()- .flex_col()- .items_end()- .px(px(8.))- .child(div().text_size(px(11.5)).text_color(theme.text_muted).child("Their code"))- .child(div().font_family(mono_font()).text_size(px(22.)).font_weight(FontWeight::MEDIUM).child(format!("{a} {b}"))),- )- .child(Button::new(SharedString::from(format!("knock-deny-{guest_id}")), "Deny").style(ButtonStyle::Outlined).on_click(cx.listener(move |_, _, _, _| host::admit(&share_id, guest_id, false))))- .child(Button::new(SharedString::from(format!("knock-in-{guest_id}")), "Let in").style(ButtonStyle::Primary).on_click(cx.listener(move |_, _, _, _| host::admit(&share_id2, guest_id, true))))- .into_any_element()- })- .collect()+ let wants = match (share.target.is_machine(), share.can_type) {+ (true, _) => format!("wants to use {}", share.target.title),+ (false, true) => format!("wants to join {}", share.target.title),+ (false, false) => format!("wants to watch {}", share.target.title),+ };+ cards.push(+ div()+ .mx(px(20.))+ .mt(px(12.))+ .flex()+ .items_center()+ .gap(px(14.))+ .p(px(14.))+ .rounded(px(10.))+ .border_1()+ .border_color(theme.accent)+ .bg(theme.elevated)+ .shadow_lg()+ .child(+ div()+ .size(px(36.))+ .flex_none()+ .rounded_full()+ .bg(theme.accent.opacity(0.25))+ .flex()+ .items_center()+ .justify_center()+ .text_size(px(15.))+ .font_weight(FontWeight::SEMIBOLD)+ .child(g.name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default()),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(13.5)).font_weight(FontWeight::SEMIBOLD).child(format!("{} {wants}", g.name)))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("{how} · ask {} to read their code", g.name))),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .items_end()+ .px(px(8.))+ .child(div().text_size(px(11.5)).text_color(theme.text_muted).child("Their code"))+ .child(div().font_family(mono_font()).text_size(px(22.)).font_weight(FontWeight::MEDIUM).child(format!("{a} {b}"))),+ )+ .child(Button::new(SharedString::from(format!("knock-deny-{guest_id}")), "Deny").style(ButtonStyle::Outlined).on_click(cx.listener(move |_, _, _, _| host::admit(&share_id, guest_id, false))))+ .child(Button::new(SharedString::from(format!("knock-in-{guest_id}")), "Let in").style(ButtonStyle::Primary).on_click(cx.listener(move |_, _, _, _| host::admit(&share_id2, guest_id, true))))+ .into_any_element(),+ );+ }+ }+ cards}/// The Join dialog (from a link opened, or the command palette).- pub(super) fn show_join(&mut self, link: Option<String>, window: &mut Window, cx: &mut Context<Self>) {+ pub(super) fn show_join(&mut self, link: Option<String>, window: &mut Window, cx: &mut Context<Self>) -> Entity<JoinDialog> {let engine = self.engine.clone();let name = Some(self.engine.settings().share.name).filter(|n| !n.is_empty()).or_else(|| self.snapshot.github.login.clone()).unwrap_or_default();let dialog = cx.new(|cx| JoinDialog::new(engine, link, name, window, cx));self.show_modal(Modal::Join(dialog.clone()), window, cx);self._subscriptions.push(cx.subscribe_in(&dialog, window, Self::on_dialog_event));+ dialog}- /// A share joined and let in: its terminal, fed from now on, and its page.+ fn joined_mut(&mut self, id: &str) -> Option<&mut JoinedShare> {+ self.joined.iter_mut().find(|j| j.id == id)+ }++ /// A share joined and let in: its page, kept up to date from now on.pub(super) fn open_joined(&mut self, handle: &JoinedHandle, window: &mut Window, cx: &mut Context<Self>) {let Some(mut updates) = handle.updates.lock().unwrap().take() else { return };self.joined_count += 1;let id = format!("shared-{}", self.joined_count);- let (tx, output) = futures::channel::mpsc::unbounded();- let io: Arc<dyn RemoteIo> = Arc::new(GuestIo(handle.joined.clone()));- let terminal = cx.new(|cx| TerminalView::guest(io, output, (100, 30), window, cx));- self.joined.push(JoinedSession { id: id.clone(), info: handle.info.clone(), joined: handle.joined.clone(), terminal, can_type: handle.can_type, ended: None });+ self.joined.push(JoinedShare {+ id: id.clone(),+ info: handle.info.clone(),+ joined: handle.joined.clone(),+ can_type: handle.can_type,+ can_control: handle.can_control,+ can_manage: handle.can_manage,+ sessions: Vec::new(),+ open: Vec::new(),+ showing: if handle.info.whole_machine { Showing::Machine } else { Showing::Session(String::new()) },+ desktop: None,+ quality: "medium",+ servers: HashMap::new(),+ ended: None,+ });+ if !handle.info.whole_machine {+ self.open_shared_session(&id, String::new(), window, cx);+ }let sid = id.clone();- let task = cx.spawn(async move |this, cx| {+ let task = cx.spawn_in(window, async move |this, cx| {while let Some(u) = updates.recv().await {- let mut fed = true;- match u {- guest::Update::Output(b) => fed = tx.unbounded_send(RemoteOutput::Bytes(b)).is_ok(),- guest::Update::Size(c, r) => {- let _ = tx.unbounded_send(RemoteOutput::Resize(c, r));- let _ = this.update(cx, |_, cx| cx.notify());- }- guest::Update::Typing(allowed) => {- let _ = this.update(cx, |this, cx| {- if let Some(j) = this.joined.iter_mut().find(|j| j.id == sid) {- j.can_type = allowed;- }+ let alive = this.update_in(cx, |this, _window, cx| {+ let Some(j) = this.joined_mut(&sid) else { return false };+ match u {+ guest::Update::Typing(allowed) => {+ j.can_type = allowed;+ j.can_manage &= allowed;this.notify_user(if allowed { "You can type now." } else { "Typing is off. You're watching." }, false, cx);- });- }- guest::Update::Exited(code) => fed = tx.unbounded_send(RemoteOutput::Ended(code)).is_ok(),- guest::Update::Ended(why) => {- let _ = tx.unbounded_send(RemoteOutput::Ended(None));- let _ = this.update(cx, |this, cx| {- if let Some(j) = this.joined.iter_mut().find(|j| j.id == sid) {- j.ended = Some(why);+ }+ guest::Update::Control(allowed) => {+ j.can_control = allowed;+ if let Some(d) = j.desktop.clone() {+ d.update(cx, |d, cx| d.set_control(allowed, cx));+ }+ if j.info.desktop != Desktop::None {+ this.notify_user(if allowed { "You can use their desktop now." } else { "You're watching their desktop." }, false, cx);+ }+ }+ guest::Update::Manage(allowed) => {+ j.can_manage = allowed;+ this.notify_user(if allowed { "You can start and end sessions now." } else { "Starting and ending sessions is off." }, false, cx);+ }+ guest::Update::Access { desktop, ports } => {+ j.info.desktop = desktop;+ j.servers.retain(|port, _| ports.iter().any(|p| p.port == *port));+ j.info.ports = ports;+ if desktop == Desktop::None {+ j.desktop = None;+ if j.showing == Showing::Desktop {+ j.showing = Showing::Machine;+ }}+ }+ guest::Update::Sessions(list) => j.sessions = list,+ guest::Update::Ended(why) => {+ j.ended = Some(why);cx.notify();- });- return;+ return false;+ }+ _ => {}}- _ => {}- }- if !fed {- break;+ cx.notify();+ true+ });+ if !alive.unwrap_or(false) {+ return;}}});@@ -693,7 +1009,141 @@ impl Root {self.navigate(Route::Shared(id), window, cx);}- /// Lets go of a session shared with you.+ /// Shows a share's machine page, one of its sessions or its desktop.+ pub(super) fn show_shared(&mut self, id: &str, showing: Showing, window: &mut Window, cx: &mut Context<Self>) {+ // Leaving the screen stops its stream (it starts again when shown).+ if showing != Showing::Desktop+ && let Some(j) = self.joined_mut(id)+ {+ j.desktop = None;+ }+ match showing {+ Showing::Session(name) => self.open_shared_session(id, name, window, cx),+ Showing::Desktop => self.show_shared_desktop(id, window, cx),+ Showing::Machine => {+ if let Some(j) = self.joined_mut(id) {+ j.showing = Showing::Machine;+ }+ }+ }+ if self.route != Route::Shared(id.to_string()) {+ self.navigate(Route::Shared(id.to_string()), window, cx);+ }+ cx.notify();+ }++ /// Shows one of the share's sessions, opening it when it isn't yet.+ fn open_shared_session(&mut self, id: &str, name: String, window: &mut Window, cx: &mut Context<Self>) {+ let runtime = self.engine.runtime().clone();+ let Some(j) = self.joined_mut(id) else { return };+ j.showing = Showing::Session(name.clone());+ if j.open.iter().any(|o| o.name == name) {+ cx.notify();+ return;+ }+ // The one looked at longest ago makes room.+ if j.open.len() >= OPEN_SESSIONS {+ let old = j.open.remove(0);+ j.joined.close(old.channel.load(Ordering::Relaxed));+ }+ let channel = Arc::new(AtomicU32::new(0));+ let (tx, output) = futures::channel::mpsc::unbounded();+ let io: Arc<dyn RemoteIo> = Arc::new(GuestIo { joined: j.joined.clone(), channel: channel.clone() });+ let terminal = cx.new(|cx| TerminalView::guest(io, output, (100, 30), window, cx));+ j.open.push(OpenSession { name: name.clone(), terminal, channel: channel.clone(), error: None });+ let joined = j.joined.clone();+ let session = name.clone();+ let opening = runtime.spawn(async move { joined.open(json!({ "op": "watch", "session": session })).await });+ let sid = id.to_string();+ let task = cx.spawn(async move |this, cx| {+ let mut frames = match opening.await.unwrap_or_else(|e| Err(e.to_string())) {+ Ok((ch, _, frames)) => {+ channel.store(ch, Ordering::Relaxed);+ frames+ }+ Err(e) => {+ let _ = this.update(cx, |this, cx| {+ if let Some(o) = this.joined_mut(&sid).and_then(|j| j.open.iter_mut().find(|o| o.name == name)) {+ o.error = Some(e);+ }+ cx.notify()+ });+ return;+ }+ };+ while let Some((kind, bytes)) = frames.recv().await {+ match kind {+ crate::share::DATA => {+ if tx.unbounded_send(RemoteOutput::Bytes(bytes)).is_err() {+ return;+ }+ }+ crate::share::SIZE if bytes.len() == 4 => {+ let _ = tx.unbounded_send(RemoteOutput::Resize(u16::from_be_bytes([bytes[0], bytes[1]]), u16::from_be_bytes([bytes[2], bytes[3]])));+ let _ = this.update(cx, |_, cx| cx.notify());+ }+ crate::share::EXIT => {+ let code = (bytes.len() == 4).then(|| i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]));+ let _ = tx.unbounded_send(RemoteOutput::Ended(code));+ }+ crate::share::CLOSE => break,+ _ => {}+ }+ }+ let _ = tx.unbounded_send(RemoteOutput::Ended(None));+ });+ self.track(task);+ cx.notify();+ }++ /// Shows the shared machine's desktop.+ fn show_shared_desktop(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {+ let engine = self.engine.clone();+ let Some(j) = self.joined_mut(id) else { return };+ if j.desktop.is_none() {+ let (joined, mac, quality) = (j.joined.clone(), j.info.mac, j.quality);+ j.desktop = Some(cx.new(|cx| DesktopView::shared(engine, joined, mac, quality, window, cx)));+ }+ j.showing = Showing::Desktop;+ cx.notify();+ }++ /// The quality of a shared desktop shown here.+ pub(super) fn set_shared_quality(&mut self, id: &str, quality: &'static str, window: &mut Window, cx: &mut Context<Self>) {+ let Some(j) = self.joined_mut(id) else { return };+ j.quality = quality;+ if let Some(d) = j.desktop.clone() {+ d.update(cx, |d, cx| d.set_quality(quality, window, cx));+ }+ }++ /// Opens one of the shared servers here, in the browser.+ pub(super) fn open_shared_server(&mut self, id: &str, port: u16, cx: &mut Context<Self>) {+ let runtime = self.engine.runtime().clone();+ let Some(j) = self.joined_mut(id) else { return };+ if let Some(Ok(local)) = j.servers.get(&port) {+ cx.open_url(&format!("http://localhost:{local}"));+ return;+ }+ let joined = j.joined.clone();+ let job = runtime.spawn(async move { joined.forward(port).await });+ let sid = id.to_string();+ let task = cx.spawn(async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update(cx, |this, cx| {+ if let Ok(local) = &result {+ cx.open_url(&format!("http://localhost:{local}"));+ }+ if let Some(j) = this.joined_mut(&sid) {+ j.servers.insert(port, result);+ }+ cx.notify();+ });+ });+ self.track(task);+ }++ /// Lets go of a share someone gave you.pub(super) fn leave_joined(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {if let Some(i) = self.joined.iter().position(|j| j.id == id) {let j = self.joined.remove(i);@@ -705,15 +1155,79 @@ impl Root {cx.notify();}- /// A session someone shared with you.- pub(super) fn render_joined(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {++ /// A share someone gave you, drawn like your own: a machine's page, a+ /// session's, a desktop's.+ pub(super) fn render_joined(&mut self, id: &str, cx: &mut Context<Self>) -> AnyElement {let theme = cx.theme();let Some(j) = self.joined.iter().find(|j| j.id == id) else {return div().size_full().flex().items_center().justify_center().text_color(theme.text_muted).child("That share is closed.").into_any_element();};- let (icon_name, (from, to)) = kit::agent_look(&j.info.agent);- let title = if j.info.title.is_empty() { agent_name(&j.info.agent).to_string() } else { j.info.title.clone() };- let leave = j.id.clone();+ if let Some(why) = j.ended.clone() {+ let leave = j.id.clone();+ return div()+ .size_full()+ .flex()+ .items_center()+ .justify_center()+ .child(+ card(&theme)+ .items_center()+ .gap(px(10.))+ .p(px(22.))+ .max_w(px(420.))+ .child(kit::color_tile("eye", 36.))+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(why))+ .child(Button::new("joined-close", "Close").icon("x").on_click(cx.listener(move |this, _, window, cx| this.leave_joined(&leave, window, cx)))),+ )+ .into_any_element();+ }+ match j.showing.clone() {+ Showing::Machine => self.joined_machine_page(id, cx),+ Showing::Session(name) => self.joined_session_page(id, &name, cx),+ Showing::Desktop => self.joined_desktop_page(id, cx),+ }+ }++ /// What this guest may do, in a few words ("Watching", "Typing").+ fn joined_mode(j: &JoinedShare) -> &'static str {+ if j.can_type { "Typing" } else { "Watching" }+ }++ /// One of a shared machine's sessions, or the session shared: like a+ /// session of your own, its terminal filling the page.+ fn joined_session_page(&mut self, id: &str, name: &str, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let Some(j) = self.joined.iter().find(|j| j.id == id) else { return div().into_any_element() };+ let session = j.sessions.iter().find(|s| s.name == name).cloned();+ let agent = session.as_ref().map(|s| s.agent.clone()).unwrap_or_else(|| j.info.agent.clone());+ let title = match &session {+ Some(s) if !s.title.is_empty() => s.title.clone(),+ Some(s) => agent_name(&s.agent).to_string(),+ None if !j.info.title.is_empty() && !j.info.whole_machine => j.info.title.clone(),+ None => agent_name(&agent).to_string(),+ };+ let machine = if j.info.whole_machine { j.info.title.clone() } else { j.info.machine.clone() };+ let (icon_name, (from, to)) = kit::agent_look(&agent);+ let status = match &session {+ Some(s) if s.status == "exited" => kit::pill("Exited", theme.text_placeholder).into_any_element(),+ Some(s) if s.busy => div()+ .flex()+ .items_center()+ .gap(px(6.))+ .text_size(px(12.))+ .text_color(theme.text_accent)+ .child(kit::spinner("joined-busy", 12., theme.accent))+ .child("Working")+ .into_any_element(),+ Some(s) => div().text_size(px(12.)).text_color(theme.text_placeholder).child(if s.agent == "shell" { "Idle" } else { "Waiting for you" }).into_any_element(),+ None => div().into_any_element(),+ };+ let can_type = j.can_type;+ let by = j.info.by.clone();+ let whole = j.info.whole_machine;+ let desktop = j.info.desktop != Desktop::None;+ let (sid, sid2) = (j.id.clone(), j.id.clone());let header = div().flex().flex_none()@@ -731,106 +1245,540 @@ impl Root {.flex_1().min_w(px(0.)).gap(px(2.))- .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(title))- .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("{} · {} · shared by {}", agent_name(&j.info.agent), j.info.machine, j.info.by))),+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child(title))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("{} · {machine} · shared by {by}", agent_name(&agent)))),+ )+ .child(status)+ .child(+ div()+ .id("joined-mode")+ .child(kit::pill(Self::joined_mode(j), theme.accent))+ .tooltip(move |window, cx| kit::Tooltip::view(if can_type { "Your keys go to their session, as them.".into() } else { format!("You're watching. Only {by} can type.").into() }, window, cx)),)- .when(j.ended.is_none(), |d| {- d.child(kit::pill(if j.can_type { "Typing" } else { "Watching" }, theme.accent))- .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("{} left", time_left(j.info.ends_at))))+ .when(whole && desktop, |d| {+ d.child(Button::new("joined-desktop", "Desktop").icon("monitor").style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, window, cx| this.show_shared(&sid, Showing::Desktop, window, cx))))+ })+ .when(whole && j.can_manage && session.is_some(), |d| {+ let (sid, name) = (j.id.clone(), name.to_string());+ let exited = session.as_ref().is_some_and(|s| s.status == "exited");+ let (label, glyph, action) = if exited { ("Restart", "rotate-ccw", JoinedAction::Restart(name)) } else { ("End", "power", JoinedAction::End(name)) };+ d.child(Button::new("joined-end", label).icon(glyph).style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, window, cx| this.run_joined(&sid, action.clone(), window, cx))))})- .child(Button::new("joined-leave", if j.ended.is_some() { "Close" } else { "Leave" }).icon("x").style(ButtonStyle::Outlined).on_click(cx.listener(move |this, _, window, cx| this.leave_joined(&leave, window, cx))));- let body = match &j.ended {- Some(why) => div()+ .when(!whole, |d| d.child(Button::new("joined-leave", "Leave").icon("x").style(ButtonStyle::Ghost).on_click(cx.listener(move |this, _, window, cx| this.leave_joined(&sid2, window, cx)))));+ let body = match j.open.iter().find(|o| o.name == name) {+ Some(o) if o.error.is_some() => div().flex_1().flex().items_center().justify_center()- .child(- card(&theme)- .items_center()- .gap(px(10.))- .p(px(22.))- .max_w(px(420.))- .child(kit::color_tile("eye", 36.))- .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).child(why.clone())),- )+ .text_size(px(13.))+ .text_color(theme.text_muted)+ .child(o.error.clone().unwrap_or_default()).into_any_element(),- None => {- let (cols, rows) = j.terminal.read(cx).fixed_size().unwrap_or((100, 30));- let (w, h) = TerminalView::pixel_size(cols, rows, window, cx);- let note = if j.can_type { "You can type. Keys go to their session.".to_string() } else { format!("You're watching. Only {} can type.", j.info.by) };+ Some(o) => div().relative().flex_1().min_h(px(0.)).flex().child(o.terminal.clone()).into_any_element(),+ None => div().flex_1().into_any_element(),+ };+ div().size_full().flex().flex_col().child(header).child(body).into_any_element()+ }++ /// A shared machine's desktop, like your own machines' Desktop page.+ fn joined_desktop_page(&mut self, id: &str, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let Some(j) = self.joined.iter().find(|j| j.id == id) else { return div().into_any_element() };+ let Some(d) = j.desktop.clone() else {+ return div().size_full().flex().items_center().justify_center().text_color(theme.text_muted).child("The desktop isn't shared anymore.").into_any_element();+ };+ let current = d.read(cx).quality();+ let qualities = host::QUALITIES.iter().enumerate().map(|(i, q)| {+ let (sid, q) = (j.id.clone(), *q);+ choice(&theme, ("desktop-quality", i), quality_label(q), current == q, true).on_click(cx.listener(move |this, _, window, cx| this.set_shared_quality(&sid, q, window, cx)))+ });+ let can_control = j.can_control;+ let by = j.info.by.clone();+ let header = div()+ .flex()+ .flex_none()+ .items_center()+ .gap(px(12.))+ .px(px(20.))+ .py(px(12.))+ .border_b_1()+ .border_color(theme.border_variant)+ .child(kit::color_tile("monitor", 32.))+ .child(div()- .flex_1()- .min_h(px(0.)).flex().flex_col()- .gap(px(10.))- .p(px(16.))- .child(- div()- .flex_1()- .min_h(px(0.))- .overflow_hidden()- .child(div().w(px(w)).h(px(h)).rounded(px(8.)).overflow_hidden().border_1().border_color(theme.border_variant).child(j.terminal.clone())),- )+ .flex_1()+ .min_w(px(0.))+ .gap(px(2.))+ .child(div().text_size(px(14.)).font_weight(FontWeight::SEMIBOLD).text_color(theme.text).child("Desktop"))+ .child(div().text_size(px(12.)).text_color(theme.text_placeholder).child(format!("{} · shared by {} · {}", j.info.title, j.info.by, d.read(cx).status()))),+ )+ .child(div().flex().items_center().gap(px(6.)).text_size(px(12.)).text_color(theme.text_muted).child("Quality").children(qualities))+ .child(+ div()+ .id("joined-control")+ .child(kit::pill(if can_control { "In control" } else { "View only" }, theme.accent))+ .tooltip(move |window, cx| kit::Tooltip::view(if can_control { "Your mouse and keys work on their screen.".into() } else { format!("You're watching. Only {by} can use it.").into() }, window, cx)),+ );+ div().size_full().flex().flex_col().child(header).child(div().flex_1().min_h(px(0.)).child(d)).into_any_element()+ }++ /// A shared machine's page, like your own machines': what's shared and+ /// what you can do with it.+ fn joined_machine_page(&mut self, id: &str, cx: &mut Context<Self>) -> AnyElement {+ let theme = cx.theme();+ let Some(j) = self.joined.iter().find(|j| j.id == id) else { return div().into_any_element() };+ let sid = j.id.clone();+ let mut buttons: Vec<AnyElement> = Vec::new();+ if j.can_manage {+ let sid = sid.clone();+ buttons.push(Button::new("jm-terminal", "New terminal").icon("square-terminal").style(ButtonStyle::Primary).on_click(cx.listener(move |this, _, window, cx| this.run_joined(&sid, JoinedAction::Start("shell"), window, cx))).into_any_element());+ }+ if j.info.desktop != Desktop::None {+ let sid = sid.clone();+ buttons.push(Button::new("jm-desktop", "Show desktop").icon("monitor").style(if j.can_manage { ButtonStyle::Outlined } else { ButtonStyle::Primary }).on_click(cx.listener(move |this, _, window, cx| this.show_shared(&sid, Showing::Desktop, window, cx))).into_any_element());+ }+ {+ let sid = sid.clone();+ buttons.push(Button::new("jm-leave", "Leave").icon("x").on_click(cx.listener(move |this, _, window, cx| this.leave_joined(&sid, window, cx))).into_any_element());+ }+ let header = div()+ .flex()+ .flex_wrap()+ .items_start()+ .justify_between()+ .gap(px(12.))+ .child(+ div()+ .flex()+ .items_start()+ .gap(px(12.))+ .child(kit::color_tile("monitor", 40.)).child(div().flex()- .items_center()- .gap(px(8.))- .px(px(12.))- .py(px(8.))- .rounded(px(8.))- .bg(theme.surface)- .text_size(px(12.))- .text_color(theme.text_muted)- .child(icon(if j.can_type { "keyboard" } else { "lock" }, 13., theme.text_muted))- .child(div().flex_1().child(note))- .child(format!("Shown at {}'s size", j.info.by)),- )+ .flex_col()+ .gap(px(4.))+ .child(div().flex().items_center().gap(px(10.)).child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(j.info.title.clone())).child(kit::pill("Shared with you", theme.accent)))+ .child(div().text_size(px(12.)).text_color(theme.text_muted).child(format!("Shared by {} · ends in {}", j.info.by, time_left(j.info.ends_at)))),+ ),+ )+ .child(div().flex().gap(px(6.)).children(buttons));++ // What you can do here, as the sharer set it.+ let can = |glyph: &'static str, text: String| div().flex().items_center().gap(px(8.)).text_size(px(12.5)).text_color(theme.text).child(icon(glyph, 14., theme.text_muted)).child(text);+ let mut allowed = div().flex().flex_col().gap(px(8.)).p(px(14.));+ allowed = allowed.child(can(if j.can_type { "keyboard" } else { "eye" }, if j.can_type { "Watch and type in its sessions".into() } else { format!("Watch its sessions (only {} types)", j.info.by) }));+ if j.can_manage {+ allowed = allowed.child(can("square-terminal", "Start, end and restart its sessions".into()));+ }+ match j.info.desktop {+ Desktop::None => {}+ Desktop::View => allowed = allowed.child(can("monitor", "Watch its screen".into())),+ Desktop::Control if j.can_control => allowed = allowed.child(can("monitor", "Watch and use its screen".into())),+ Desktop::Control => allowed = allowed.child(can("monitor", format!("Watch its screen, and use it when {} lets you", j.info.by))),+ }+ if !j.info.ports.is_empty() {+ let n = j.info.ports.len();+ allowed = allowed.child(can("network", format!("Open {n} of its servers here")));+ }++ // Its sessions, like a machine's.+ let sessions: Vec<AnyElement> = j+ .sessions+ .iter()+ .enumerate()+ .map(|(i, x)| {+ let (icon_name, (from, to)) = kit::agent_look(&x.agent);+ let title = if x.title.is_empty() { agent_name(&x.agent).to_string() } else { x.title.clone() };+ let state = if x.status == "exited" {+ div().text_size(px(12.)).text_color(theme.text_placeholder).child("Exited").into_any_element()+ } else if x.busy {+ div().flex().items_center().gap(px(6.)).text_size(px(12.)).text_color(theme.text_accent).child(kit::spinner(("jm-spin", i), 12., theme.accent)).child("Working").into_any_element()+ } else {+ div().text_size(px(12.)).text_color(theme.text_placeholder).child(if x.agent == "shell" { "Idle" } else { "Waiting for you" }).into_any_element()+ };+ let (sid, name) = (sid.clone(), x.name.clone());+ div()+ .id(("jm-session", i))+ .flex()+ .items_center()+ .gap(px(12.))+ .px(px(14.))+ .py(px(10.))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .cursor_pointer()+ .hover(|st| st.bg(theme.ghost_hover))+ .child(kit::tile(icon_name, from, to, 26.))+ .child(div().flex().flex_col().flex_1().min_w(px(0.)).gap(px(1.)).child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(title)).child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(agent_name(&x.agent))))+ .child(state)+ .on_click(cx.listener(move |this, _, window, cx| this.show_shared(&sid, Showing::Session(name.clone()), window, cx))).into_any_element()- }+ })+ .collect();+ let sessions = if sessions.is_empty() {+ card(&theme).p(px(16.)).flex_row().items_center().gap(px(12.)).child(kit::color_tile("square-terminal", 28.)).child(div().text_size(px(12.5)).text_color(theme.text_muted).child(format!("No sessions are running on {} right now. New ones show up here.", j.info.title))).into_any_element()+ } else {+ card(&theme).children(sessions).into_any_element()};- div().size_full().flex().flex_col().child(header).child(body).into_any_element()- }- /// The sidebar's "Shared with you" rows.- pub(super) fn joined_rows(&self, theme: &Theme, cx: &mut Context<Self>) -> Vec<AnyElement> {- self.joined+ // Its servers, to open here.+ let servers: Vec<AnyElement> = j+ .info+ .ports.iter()- .map(|j| {- let id = j.id.clone();- let selected = self.route == Route::Shared(j.id.clone());- let (icon_name, (from, to)) = kit::agent_look(&j.info.agent);- let title = if j.info.title.is_empty() { agent_name(&j.info.agent).to_string() } else { j.info.title.clone() };- let text_w = (self.sidebar_width - 20. - 22. - 8. - 16. - 8. - 24.).max(40.);+ .enumerate()+ .map(|(i, p)| {+ let state = match j.servers.get(&p.port) {+ Some(Ok(local)) => format!("Open here at localhost:{local}"),+ Some(Err(e)) => e.clone(),+ None => format!("Port {} on {}", p.port, j.info.title),+ };+ let (sid, port) = (sid.clone(), p.port);div()- .id(SharedString::from(format!("side-j-{}", j.id))).flex().items_center()- .gap(px(8.))- .h(px(30.))- .mx(px(10.))- .pl(px(10.))- .pr(px(8.))- .rounded(px(7.))- .cursor_pointer()- .when(selected, |d| d.bg(theme.element_selected))- .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))- .child(kit::tile(icon_name, from, to, 16.))- .child(- div()- .w(px(text_w))- .flex()- .flex_col()- .child(div().w(px(text_w)).truncate().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child(title))- .child(div().w(px(text_w)).truncate().text_size(px(11.)).text_color(theme.text_placeholder).child(format!("from {}", j.info.by))),- )- .child(div().flex_1())- .child(icon(if j.ended.is_some() { "x" } else { "eye" }, 12., theme.text_accent))- .on_click(cx.listener(move |this, _, window, cx| this.navigate(Route::Shared(id.clone()), window, cx)))+ .gap(px(12.))+ .px(px(14.))+ .py(px(10.))+ .when(i > 0, |d| d.border_t_1().border_color(theme.border_variant))+ .child(kit::color_tile("network", 26.))+ .child(div().flex().flex_col().flex_1().min_w(px(0.)).gap(px(1.)).child(div().text_size(px(13.)).font_weight(FontWeight::MEDIUM).child(if p.name.is_empty() { format!("Port {}", p.port) } else { p.name.clone() })).child(div().text_size(px(11.5)).text_color(theme.text_placeholder).child(state)))+ .child(Button::new(("jm-open", i), "Open").icon("external-link").on_click(cx.listener(move |this, _, _, cx| this.open_shared_server(&sid, port, cx)))).into_any_element()})- .collect()+ .collect();++ super::overview::page("shared-page", &self.page_scroll)+ .child(header)+ .child(div().flex().flex_col().gap(px(10.)).child(section_title(&theme, "What you can do", None)).child(card(&theme).child(allowed)))+ .child(div().flex().flex_col().gap(px(10.)).child(section_title(&theme, "Agent sessions", Some(j.sessions.len()))).child(sessions))+ .when(!servers.is_empty(), |d| d.child(div().flex().flex_col().gap(px(10.)).child(section_title(&theme, "Servers", Some(servers.len()))).child(card(&theme).children(servers))))+ .into_any_element()+ }++ /// The sidebar's "Shared with you": each share like one of your machines+ /// (or sessions), a shared machine's sessions, desktop and servers under it.+ pub(super) fn joined_rows(&self, theme: &Theme, cx: &mut Context<Self>) -> Vec<AnyElement> {+ let mut rows = Vec::new();+ for j in &self.joined {+ let here = self.route == Route::Shared(j.id.clone());+ let key = format!("shared:{}", j.id);+ let open = !self.collapsed.contains(&key);+ rows.push(self.joined_row(theme, j, here && (j.showing == Showing::Machine || !j.info.whole_machine), open, cx));+ if !j.info.whole_machine || !open || j.ended.is_some() {+ continue;+ }+ for s in &j.sessions {+ let selected = here && j.showing == Showing::Session(s.name.clone());+ let (icon_name, (from, to)) = kit::agent_look(&s.agent);+ let title = if s.title.is_empty() { agent_name(&s.agent).to_string() } else { s.title.clone() };+ let exited = s.status == "exited";+ let (sid, name) = (j.id.clone(), s.name.clone());+ let (msid, mname) = (j.id.clone(), s.name.clone());+ rows.push(+ nested_row(theme, SharedString::from(format!("side-js-{}-{}", j.id, s.name)), selected)+ .child(kit::tile(icon_name, from, to, 16.))+ .child(div().w(px((self.row_width() - 110.).max(40.))).truncate().text_size(px(12.5)).text_color(if exited { theme.text_placeholder } else if selected { theme.text } else { theme.text_muted }).child(title))+ .child(div().flex_1())+ .when(s.busy && !exited, |d| d.child(kit::spinner(SharedString::from(format!("side-js-spin-{}-{}", j.id, s.name)), 11., theme.accent)))+ .when(exited, |d| d.child(div().text_size(px(11.)).text_color(theme.text_placeholder).child("exited")))+ .on_mouse_down(gpui::MouseButton::Right, super::menu::on_right_click(move || super::menu::MenuTarget::JoinedSession(msid.clone(), mname.clone()), cx))+ .on_click(cx.listener(move |this, _, window, cx| this.show_shared(&sid, Showing::Session(name.clone()), window, cx)))+ .into_any_element(),+ );+ }+ if j.info.desktop != Desktop::None {+ let selected = here && j.showing == Showing::Desktop;+ let (sid, msid) = (j.id.clone(), j.id.clone());+ rows.push(+ nested_row(theme, SharedString::from(format!("side-jd-{}", j.id)), selected)+ .child(kit::color_tile("monitor", 16.))+ .child(div().flex_1().text_size(px(12.5)).text_color(if selected { theme.text } else { theme.text_muted }).child("Desktop"))+ .child(div().text_size(px(10.5)).text_color(theme.text_placeholder).child(if j.can_control { "control" } else { "view" }))+ .on_mouse_down(gpui::MouseButton::Right, super::menu::on_right_click(move || super::menu::MenuTarget::JoinedDesktop(msid.clone()), cx))+ .on_click(cx.listener(move |this, _, window, cx| this.show_shared(&sid, Showing::Desktop, window, cx)))+ .into_any_element(),+ );+ }+ for p in &j.info.ports {+ let (sid, port) = (j.id.clone(), p.port);+ let local = j.servers.get(&p.port).and_then(|r| r.as_ref().ok()).copied();+ rows.push(+ nested_row(theme, SharedString::from(format!("side-jp-{}-{}", j.id, p.port)), false)+ .child(icon("network", 14., theme.text_muted))+ .child(div().w(px((self.row_width() - 130.).max(40.))).truncate().text_size(px(12.5)).text_color(theme.text_muted).child(if p.name.is_empty() { format!("Port {}", p.port) } else { p.name.clone() }))+ .child(div().flex_1())+ .child(div().font_family(mono_font()).text_size(px(10.5)).text_color(theme.text_placeholder).child(match local {+ Some(l) => format!(":{l}"),+ None => format!(":{}", p.port),+ }))+ .tooltip(|window, cx| kit::Tooltip::view("Open it here, in your browser".into(), window, cx))+ .on_click(cx.listener(move |this, _, _, cx| this.open_shared_server(&sid, port, cx)))+ .into_any_element(),+ );+ }+ }+ rows+ }++ /// A share in the sidebar, shaped like a machine row: its tile with an eye+ /// in the corner, who shared it and what you can do; a machine's opens and+ /// closes what's under it.+ fn joined_row(&self, theme: &Theme, j: &JoinedShare, selected: bool, open: bool, cx: &mut Context<Self>) -> AnyElement {+ let id = j.id.clone();+ let (tile, title) = if j.info.whole_machine {+ (kit::color_tile("monitor", 30.), j.info.title.clone())+ } else {+ let (icon_name, (from, to)) = kit::agent_look(&j.info.agent);+ (kit::tile(icon_name, from, to, 30.), if j.info.title.is_empty() { agent_name(&j.info.agent).to_string() } else { j.info.title.clone() })+ };+ let doing = if j.ended.is_some() {+ "ended"+ } else if j.can_control && j.info.desktop == Desktop::Control {+ "in control"+ } else if j.can_type {+ "typing"+ } else {+ "watching"+ };+ let toggle = j.info.whole_machine && j.ended.is_none();+ // Row chrome: margins, padding, tile, gap, and the toggle.+ let text_w = (self.row_width() - 20. - 16. - 30. - 10. - if toggle { 32. } else { 0. }).max(40.);+ let (menu_id, key) = (j.id.clone(), format!("shared:{}", j.id));+ div()+ .id(SharedString::from(format!("side-j-{}", j.id)))+ .group("joined-row")+ .flex()+ .items_center()+ .gap(px(10.))+ .h(px(44.))+ .mx(px(10.))+ .px(px(8.))+ .rounded(px(9.))+ .cursor_pointer()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))+ .child(+ div().relative().flex_none().child(tile).child(+ div()+ .absolute()+ .right(px(-4.))+ .bottom(px(-4.))+ .size(px(15.))+ .rounded_full()+ .bg(theme.sidebar)+ .flex()+ .items_center()+ .justify_center()+ .child(icon(if j.ended.is_some() { "x" } else { "eye" }, 10., if j.ended.is_some() { theme.text_placeholder } else { theme.text_accent })),+ ),+ )+ .child(+ div()+ .flex()+ .flex_col()+ .flex_1()+ .min_w(px(0.))+ .overflow_hidden()+ .gap(px(1.))+ .child(div().w(px(text_w)).truncate().text_size(px(13.)).font_weight(FontWeight::MEDIUM).text_color(theme.text).child(title))+ .child(div().w(px(text_w)).truncate().text_size(px(11.5)).text_color(theme.text_placeholder).child(format!("from {} · {doing}", j.info.by))),+ )+ .when(toggle, |d| {+ d.child(+ div()+ .id(SharedString::from(format!("side-j-toggle-{}", j.id)))+ .flex_none()+ .p(px(3.))+ .rounded(px(5.))+ .invisible()+ .group_hover("joined-row", |st| st.visible())+ .hover(|st| st.bg(theme.ghost_hover))+ .child(icon(if open { "chevron-down" } else { "chevron-right" }, 13., theme.text_placeholder))+ .on_click(cx.listener(move |this, _, _, cx| {+ cx.stop_propagation();+ if !this.collapsed.remove(&key) {+ this.collapsed.insert(key.clone());+ }+ cx.notify();+ })),+ )+ })+ .on_mouse_down(gpui::MouseButton::Right, super::menu::on_right_click(move || super::menu::MenuTarget::Joined(menu_id.clone()), cx))+ .on_click(cx.listener(move |this, _, window, cx| {+ let showing = match this.joined.iter().find(|j| j.id == id) {+ Some(j) if j.info.whole_machine => Showing::Machine,+ _ => Showing::Session(String::new()),+ };+ this.show_shared(&id, showing, window, cx)+ }))+ .into_any_element()+ }++ /// A share's right-click menu: like your own machine's and sessions',+ /// with what this guest isn't let do dimmed.+ pub(super) fn joined_menu(&self, target: &super::menu::MenuTarget) -> Vec<JoinedItem> {+ use super::menu::MenuTarget;+ let id = match target {+ MenuTarget::Joined(id) | MenuTarget::JoinedSession(id, _) | MenuTarget::JoinedDesktop(id) => id,+ _ => return Vec::new(),+ };+ let Some(j) = self.joined.iter().find(|j| &j.id == id) else { return Vec::new() };+ let live = j.ended.is_none();+ let item = |label: String, glyph: &'static str, action: JoinedAction| JoinedItem::Do { label, glyph, action, danger: false, picked: false };+ // Starting and ending sessions: dimmed unless let.+ let managed = |label: String, glyph: &'static str, action: JoinedAction| if j.can_manage && live { item(label, glyph, action) } else { JoinedItem::Off { label, glyph } };+ let mut items = Vec::new();+ match target {+ MenuTarget::JoinedSession(_, name) => {+ let exited = j.sessions.iter().any(|s| &s.name == name && s.status == "exited");+ items.push(item("Open".into(), "square-terminal", JoinedAction::Show(Showing::Session(name.clone()))));+ items.push(JoinedItem::Separator);+ if exited {+ items.push(managed("Restart".into(), "rotate-ccw", JoinedAction::Restart(name.clone())));+ }+ items.push(managed("End session".into(), "power", JoinedAction::End(name.clone())));+ }+ MenuTarget::JoinedDesktop(_) => {+ items.push(item("Open".into(), "monitor", JoinedAction::Show(Showing::Desktop)));+ items.push(JoinedItem::Separator);+ items.push(JoinedItem::Note("Quality".into()));+ let current = j.quality;+ for q in host::QUALITIES {+ items.push(JoinedItem::Do { label: quality_label(q).into(), glyph: "", action: JoinedAction::Quality(q), danger: false, picked: q == current });+ }+ }+ _ if j.info.whole_machine => {+ items.push(managed("New terminal".into(), "square-terminal", JoinedAction::Start("shell")));+ for a in crate::fleet::sessions::AGENTS.iter().filter(|a| a.id != "shell" && j.info.agents.iter().any(|i| i == a.id)) {+ items.push(match managed(format!("New {} session", a.name), "", JoinedAction::Start(a.id)) {+ JoinedItem::Do { label, action, .. } => JoinedItem::Agent { label, agent: a.id, action: Some(action) },+ _ => JoinedItem::Agent { label: format!("New {} session", a.name), agent: a.id, action: None },+ });+ }+ if j.info.desktop != Desktop::None {+ items.push(item("Show desktop".into(), "monitor", JoinedAction::Show(Showing::Desktop)));+ }+ for p in &j.info.ports {+ let name = if p.name.is_empty() { format!("port {}", p.port) } else { p.name.clone() };+ items.push(item(format!("Open {name} here"), "external-link", JoinedAction::Server(p.port)));+ }+ items.push(JoinedItem::Separator);+ items.push(item("Open".into(), "monitor", JoinedAction::Show(Showing::Machine)));+ items.push(item("Refresh".into(), "refresh-cw", JoinedAction::Refresh));+ if live && !j.can_manage {+ items.push(JoinedItem::Note(format!("Ask {} to let you start sessions.", j.info.by)));+ }+ }+ _ => items.push(item("Open".into(), "square-terminal", JoinedAction::Show(Showing::Session(String::new())))),+ }+ items.push(JoinedItem::Separator);+ items.push(JoinedItem::Do { label: if live { "Leave share".into() } else { "Close".into() }, glyph: "x", action: JoinedAction::Leave, danger: true, picked: false });+ items}++ /// Asks the sharing computer to start, end or restart a session; a+ /// session started opens.+ fn shared_call(&mut self, id: &str, req: serde_json::Value, open: bool, window: &mut Window, cx: &mut Context<Self>) {+ let Some(joined) = self.joined.iter().find(|j| j.id == id).map(|j| j.joined.clone()) else { return };+ let job = self.engine.runtime().spawn(async move { joined.call(req).await });+ let sid = id.to_string();+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = job.await.unwrap_or_else(|e| Err(e.to_string()));+ let _ = this.update_in(cx, |this, window, cx| match result {+ Ok(name) if open => this.show_shared(&sid, Showing::Session(name), window, cx),+ Ok(_) => {+ if let Some(j) = this.joined.iter().find(|j| j.id == sid) {+ j.joined.refresh_sessions();+ }+ }+ Err(e) => this.notify_user(e, true, cx),+ });+ });+ self.track(task);+ }++ /// Runs one of a share's menu items.+ pub(super) fn run_joined(&mut self, id: &str, action: JoinedAction, window: &mut Window, cx: &mut Context<Self>) {+ match action {+ JoinedAction::Show(showing) => self.show_shared(id, showing, window, cx),+ JoinedAction::Quality(q) => {+ self.show_shared(id, Showing::Desktop, window, cx);+ self.set_shared_quality(id, q, window, cx);+ }+ JoinedAction::Server(port) => self.open_shared_server(id, port, cx),+ JoinedAction::Start(agent) => self.shared_call(id, json!({ "op": "start", "agent": agent }), true, window, cx),+ JoinedAction::End(name) => {+ // Not showing a session that's gone.+ if let Some(j) = self.joined_mut(id)+ && j.showing == Showing::Session(name.clone())+ {+ j.showing = Showing::Machine;+ }+ self.shared_call(id, json!({ "op": "end", "session": name }), false, window, cx)+ }+ JoinedAction::Restart(name) => self.shared_call(id, json!({ "op": "restart", "session": name }), true, window, cx),+ JoinedAction::Refresh => {+ if let Some(j) = self.joined.iter().find(|j| j.id == id) {+ j.joined.refresh_sessions();+ }+ }+ JoinedAction::Leave => self.leave_joined(id, window, cx),+ }+ }+}++/// A line of a share's right-click menu.+pub enum JoinedItem {+ Do { label: String, glyph: &'static str, action: JoinedAction, danger: bool, picked: bool },+ /// Starting one of the machine's agent CLIs (dimmed without an action).+ Agent { label: String, agent: &'static str, action: Option<JoinedAction> },+ /// Not let: shown dimmed.+ Off { label: String, glyph: &'static str },+ Note(String),+ Separator,+}++/// What a share's menu item does.+#[derive(Clone, Debug)]+pub enum JoinedAction {+ Show(Showing),+ Quality(&'static str),+ Server(u16),+ /// Start a session with this agent CLI ("shell" for a terminal).+ Start(&'static str),+ End(String),+ Restart(String),+ Refresh,+ Leave,+}++/// "Low", "Medium", "High", "Max".+fn quality_label(q: &str) -> &'static str {+ match q {+ "low" => "Low",+ "high" => "High",+ "max" => "Max",+ _ => "Medium",+ }+}++/// A row under a share in the sidebar, like a machine's sessions.+fn nested_row(theme: &Theme, id: SharedString, selected: bool) -> gpui::Stateful<gpui::Div> {+ div()+ .id(id)+ .flex()+ .items_center()+ .gap(px(8.))+ .h(px(26.))+ .mx(px(10.))+ .pl(px(22.))+ .pr(px(8.))+ .rounded(px(7.))+ .cursor_pointer()+ .when(selected, |d| d.bg(theme.element_selected))+ .when(!selected, |d| d.hover(|st| st.bg(theme.ghost_hover)))}diff --git a/src/ui/terminal/mod.rs b/src/ui/terminal/mod.rsindex 706e98f..e462e12 100644--- a/src/ui/terminal/mod.rs+++ b/src/ui/terminal/mod.rs@@ -328,17 +328,6 @@ impl TerminalView {view}- /// The size it's drawn at when set from elsewhere.- pub fn fixed_size(&self) -> Option<(usize, usize)> {- *self.shared.fixed.lock().unwrap()- }-- /// Pixels a grid of `cols`×`rows` takes, padding included.- pub fn pixel_size(cols: usize, rows: usize, window: &Window, cx: &App) -> (f32, f32) {- let (w, h) = render::cell_size(window, Metrics::current(cx));- (cols as f32 * w + 2. * PAD_X, rows as f32 * h + 2. * PAD_Y)- }-/// A terminal showing fixed output (the demo), with no program behind it.pub fn replay(bytes: &[u8], window: &mut Window, cx: &mut Context<Self>) -> Self {let (term, _listener, rx) = new_term(110, 34);