Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Merge upstream main into fix/sharing-pause-save-failure

Sebastian B603924e1a0b1
diff --cc electron/computer-sharing.d.mts
index c33259c63a,99717b1e4c..c4056d02c9
--- a/electron/computer-sharing.d.mts
+++ b/electron/computer-sharing.d.mts
@@@ -47,9 -66,10 +66,12 @@@ export interface LendingSummary
clouds: string[];
using: string[];
paused: boolean;
+ /** A pause needs a save retry or review after an unclean exit; sharing stays stopped. */
+ pauseError?: string;
+ terminal?: boolean;
busy: { env: string; action: string } | null;
+ /** Computer control's latest state, null until it is first read. */
+ screen: ScreenStatus | null;
}
export interface AutomaticGrant { folders: SharedFolder[]; screen: boolean; internet: true; chrome: true; terminal: false }
export type CloudLendingVerdict = { allow: true } | { pause: string } | { stop: "signed-out" | "account-changed" | "machine-changed" };
@@@ -121,9 -149,9 +151,9 @@@ export function createComputerSharing(o
busy(): boolean;
saveCloud(env: Workspace, input: { folders: unknown; screen?: boolean; internet?: boolean; chrome?: boolean; terminal?: boolean }, version?: number): Promise<CloudLendingState>;
/** The move's project folders, lent to My Cloud with editing; rejects while that can't happen yet. */
- lendProjects(paths: string[]): Promise<void>;
+ lendProjects(paths: string[], place?: { id: string; origin: string; name: string } | null): Promise<void>;
paused(): boolean;
- /** Every Cloud stops using this computer, across restarts too, until resume(). */
+ /** Stops every Cloud; pauseError reports when the pause could not be saved. */
pause(): void;
resume(): Promise<void> | undefined;
screenChanged(): Promise<void>;
diff --cc electron/computer-sharing.mjs
index 0eabe9372f,a1c7971487..90c5df1a0c
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@@ -233,19 -225,26 +241,28 @@@ export function createComputerSharing(
const changed = () => { if (!closed) try { onChange(summary()); } catch {} };
const summary = () => {
const browsing = [...inUse.keys()].find(id => linked.has(id));
- const lent = paused ? [] : environments().filter(env => records[env.id]?.cloud && records[env.id]?.enabled === true);
- const using = lent.filter(env => executing?.env === env.id || (inUse.has(env.id) && linked.has(env.id)));
+ const lent = environments().filter(env => records[env.id]?.cloud && records[env.id]?.enabled === true);
+ const clouds = paused ? new Map([...ownClouds(), ...lent].map(env => [env.id, env])).values() : lent;
+ const using = paused ? [] : lent.filter(env => executing?.env === env.id || (inUse.has(env.id) && linked.has(env.id)));
return {
- lending: lent.map(env => env.id),
- clouds: (paused ? ownClouds() : lent).map(env => env.name),
+ lending: paused ? [] : lent.map(env => env.id),
+ clouds: [...clouds].map(env => env.name),
using: using.map(env => env.name),
paused,
+ ...(pauseError ? { pauseError } : {}),
terminal: terminalAccount !== null && terminalAccount === signedInAccount(),
busy: executing ?? (browsing ? { env: browsing, action: "internet" } : null),
+ screen: screenNow,
};
};
+ /** Whether apps and screen are lent now; the icon's menu follows any change in why not. */
+ const readScreen = () => Promise.resolve().then(screen).then(status => status, () => null).then(status => {
+ const next = status && typeof status === "object" ? status : null;
+ const before = JSON.stringify(screenNow);
+ screenNow = next;
+ if (JSON.stringify(next) !== before) changed();
+ return status === true || next?.lent === true;
+ });
/** Each site My Cloud's browsers opened through this computer, or that its check refused, as activity. */
const noted = new Map();
const browsed = env => (target, result) => {
@@@ -620,6 -625,80 +643,89 @@@
else if (!running.has(env.id) && validRecord(kept) && cloudLendingVerdict(kept.cloud, cloud(env), env).allow) run(env, kept);
}
};
+ /** This computer as the person's own Clouds hear it: paused, and why apps and screen or commands aren't lent. */
+ const thisComputer = async () => {
+ const status = await Promise.resolve().then(screen).then(value => value && typeof value === "object" ? value : null, () => null);
+ return { name: os.hostname().slice(0, 120) || "This computer", platform: LENT_PLATFORMS.has(process.platform) ? process.platform : null, paused,
+ screen: { ready: status?.ready === true, reason: status && !status.ready ? status.reason ?? null : null }, terminal: terminalAccount !== null && terminalAccount === signedInAccount() };
+ };
+ /** Every Cloud of the person's own may use this computer again. */
+ const resumeLending = () => {
+ if (!paused || closed) return;
- paused = false;
- try { store(records); } catch {}
++ try {
++ guardSession();
++ paused = false;
++ store(records);
++ pauseError = undefined;
++ } catch {
++ paused = true;
++ pauseError = "Resume could not be saved. Sharing stays paused. Retry Resume.";
++ changed();
++ return;
++ }
+ const automatic = lentAutomatically();
+ for (const env of environments()) {
+ const grant = records[env.id];
+ if (grant?.cloud && !automatic.has(env.id) && validRecord(grant) && !running.has(env.id) && cloudLendingVerdict(grant.cloud, cloud(env), env).allow) run(env, grant);
+ }
+ changed();
+ wakeAsking();
+ return lendAutomatically();
+ };
+ /** Turn on, from this app's prompt or the card: what the ask needs, done here. */
+ const turnOn = async (env, ask) => {
+ if (paused) await resumeLending();
+ if (ask.need === "screen") {
+ let status = await Promise.resolve().then(screen).catch(() => null);
+ if (status && typeof status === "object" && !status.ready) status = await startScreen();
+ if (status && typeof status === "object" && !status.ready) return { ok: false, reason: status.reason ?? "not-running" };
+ }
+ if (ask.need === "terminal" && terminalAccount !== signedInAccount() && !(await confirmTerminal())) return { declined: true };
+ return { ok: true };
+ };
+ /** Per Cloud that takes asks: what stops its poll for good, and what ends its current poll early. */
+ const asking = new Map();
+ /** A Cloud too old to take asks is asked again only after this long. */
+ const olderClouds = new Map();
+ const asks = createComputerAsks({ prompt: (env, ask, signal) => prompt(env, ask, signal), turnOn, log, answered: id => asking.get(id)?.wake() });
+ const keepAsking = async (env, entry) => {
+ const { signal } = entry.stop;
+ let heard = -1, failures = 0, supported = null;
+ while (!signal.aborted && !closed) {
+ if (sleepsHere(env) && sleepGate(env).asleep()) { await sleepGate(env).wait(signal); continue; }
+ const early = new AbortController();
+ entry.wake = () => early.abort();
+ const answers = [...asks.pending(env.id)];
+ try {
+ supported ??= (await describe(env)).asks;
+ if (!supported) { olderClouds.set(env.id, now()); return; }
+ const news = await request(env, "/api/shared-computers/asks", { ...await thisComputer(), heard, answers }, AbortSignal.any([signal, early.signal, sleepGate(env).signal()]));
+ asks.sent(env.id, answers);
+ failures = 0;
+ if (Number.isSafeInteger(news?.version)) heard = news.version;
+ asks.heard(env, Array.isArray(news?.asks) ? news.asks : []);
+ } catch (error) {
+ if (signal.aborted) return;
+ if (early.signal.aborted || error instanceof CloudAsleepError) continue;
+ if (error?.status === 404) { olderClouds.set(env.id, now()); return; }
+ failures++;
+ try { await delay(LINK_RETRY_MS[Math.min(failures, LINK_RETRY_MS.length - 1)], undefined, { signal }); } catch { return; }
+ }
+ }
+ };
+ /** Each verified own Cloud hears this computer while this app is open; the others don't. */
+ const syncAsking = () => {
+ const wanted = closed ? new Set() : new Set(ownClouds().filter(verifiedCloud).map(env => env.id));
+ for (const [id, entry] of asking) if (!wanted.has(id)) { entry.stop.abort(); asking.delete(id); }
+ for (const env of ownClouds()) {
+ if (!wanted.has(env.id) || asking.has(env.id) || now() - (olderClouds.get(env.id) ?? -Infinity) < 30 * 60_000) continue;
+ const entry = { stop: new AbortController(), wake: () => {} };
+ asking.set(env.id, entry);
+ void keepAsking(env, entry).catch(() => {}).finally(() => { if (asking.get(env.id) === entry) asking.delete(env.id); });
+ }
+ };
+ /** This computer changed: each Cloud hears it now, not at its next poll. */
+ const wakeAsking = () => { for (const entry of asking.values()) entry.wake(); };
/** The Clouds whose grant the automatic pass runs: it runs a kept grant only once it lends what it should. */
const lentAutomatically = () => new Set(ownClouds().map(env => env.id));
/** One pass at a time: a change while one runs asks for one more after it. */
@@@ -688,35 -769,10 +795,16 @@@
if (running.has(env.id)) disconnect(env, records[env.id]);
status.set(env.id, { connected: false, problem: "paused" });
}
+ try { store(records); pauseError = undefined; }
+ catch {
+ pauseError = sessionGuarded
+ ? "Pause is not saved. Sharing is stopped now. Retry saving pause before quitting; the next start will stay paused for review."
+ : "Pause is not saved. Sharing is stopped now. A restart can resume lending. Retry saving pause before quitting.";
+ }
changed();
+ wakeAsking();
},
- resume() {
- if (!paused || closed) return;
- try {
- guardSession();
- paused = false;
- store(records);
- pauseError = undefined;
- } catch {
- paused = true;
- pauseError = "Resume could not be saved. Sharing stays paused. Retry Resume.";
- changed();
- return;
- }
- const automatic = lentAutomatically();
- for (const env of environments()) {
- const grant = records[env.id];
- if (grant?.cloud && !automatic.has(env.id) && validRecord(grant) && !running.has(env.id) && cloudLendingVerdict(grant.cloud, cloud(env), env).allow) run(env, grant);
- }
- changed();
- return lendAutomatically();
- },
+ resume: () => resumeLending(),
/** Whether every Cloud of the signed-in account's own may run commands here as this user, across restarts too. */
lendTerminal(on) {
const account = on === true ? signedInAccount() : null;
@@@ -764,14 -821,8 +853,16 @@@
else if (verdict.pause) { if (running.has(env.id)) { disconnect(env, grant, true); status.set(env.id, { connected: false, problem: "paused" }); changed(); } }
else if (!running.has(env.id) && !automatic.has(env.id) && validRecord(grant)) run(env, grant);
}
+ changed();
void lendAutomatically();
},
- close() { closed = true; for (const id of running.keys()) stop(id); syncAsking(); asks.close(); },
+ close() {
+ if (closed) return;
+ closed = true;
+ for (const id of running.keys()) stop(id);
++ syncAsking();
++ asks.close();
+ if (sessionGuarded && !pauseError) try { fs.rmdirSync(sessionMarker); } catch {}
+ },
};
}
diff --cc electron/lending-indicator.mjs
index fbc8a604c6,04ad07df72..2306064977
--- a/electron/lending-indicator.mjs
+++ b/electron/lending-indicator.mjs
@@@ -5,15 -7,17 +7,18 @@@ const listed = names => names.length <
/** Beside the icon there is room for two names at most. */
const short = names => names.length < 3 ? listed(names) : `${names.length} Clouds`;
- export function indicatorText({ clouds, using, paused, pauseError }, device) {
+ /** `screen`: computer control's state; while it isn't ready the line says what the Clouds
+ * can't use, and `screen` why. */
-export function indicatorText({ clouds, using, paused, screen = null }, device) {
++export function indicatorText({ clouds, using, paused, pauseError, screen = null }, device) {
const it = `this ${device}`;
- if (pauseError) return { line: pauseError, title: "Paused: save needs attention" };
- if (paused) return { line: `Paused: ${listed(clouds)} can't use ${it}`, title: "Paused" };
- if (using.length) return { line: `${listed(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, title: `${short(using)} ${using.length > 1 ? "are" : "is"} using ${it}` };
- return { line: `${listed(clouds)} can use ${it}`, title: "" };
++ if (pauseError) return { line: pauseError, title: "Paused: save needs attention", screen: null };
+ if (paused) return { line: `Paused: ${listed(clouds)} can't use ${it}`, title: "Paused", screen: null };
+ const why = screenLine(screen, device);
+ if (using.length) return { line: `${listed(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, title: `${short(using)} ${using.length > 1 ? "are" : "is"} using ${it}`, screen: why };
+ return { line: why ? `${listed(clouds)} can use ${it}, but not its apps and screen` : `${listed(clouds)} can use ${it}`, title: "", screen: why };
}
- export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPause, onResume, onActivity, onTerminal, device = deviceWord() }) {
+ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPause, onResume, onActivity, onTerminal, onStartScreen = () => {}, device = deviceWord() }) {
let tray = null;
let shown = null;
const draw = view => {
@@@ -24,8 -29,9 +30,10 @@@
tray.setTitle?.(title);
tray.setContextMenu(Menu.buildFromTemplate([
{ label: line, enabled: false },
+ ...screen ? [{ label: screen, enabled: false }] : [],
+ ...fix ? [{ label: fix, click: () => onStartScreen() }] : [],
{ type: "separator" },
+ ...(view.pauseError ? [{ label: "Retry saving pause", click: () => onPause() }] : []),
view.paused ? { label: "Resume", click: () => onResume() } : { label: "Pause", click: () => onPause() },
...view.paused ? [] : [{ label: `Let Clouds run commands on this ${device}`, type: "checkbox", checked: view.terminal,
// Electron 43 ticks a checkbox on click by itself: the menu keeps the saved choice until the person confirms one.
@@@ -34,8 -40,9 +42,9 @@@
]));
};
return {
- update({ clouds = [], using = [], paused = false, terminal = false, pauseError }) {
- const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true, terminal: terminal === true, ...(pauseError ? { pauseError } : {}) };
- update({ clouds = [], using = [], paused = false, terminal = false, screen = null }) {
- const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true, terminal: terminal === true,
++ update({ clouds = [], using = [], paused = false, terminal = false, pauseError, screen = null }) {
++ const next = { clouds: [...clouds], using: paused ? [] : [...using], paused: paused === true, terminal: terminal === true, ...(pauseError ? { pauseError } : {}),
+ screen: screen ? { ready: screen.ready === true, reason: screen.reason ?? null, fix: screen.fix ?? null, ...(screen.message ? { message: screen.message } : {}) } : null };
if (shown && JSON.stringify(next) === JSON.stringify(shown)) return;
shown = next;
if (!next.clouds.length) { if (tray && !tray.isDestroyed()) tray.destroy(); tray = null; return; }