Skip to content

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

Reopen the last place on start, and let a workspace's line be closed (#4727)

Milind Soni516ca7598190
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index e6f7b22e70..094965cf74 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -97,14 +97,19 @@ would be more folders there), on the same address, one server at a time, as a
local environment switch does. Nothing moves either way, the frozen copy keeps
its marker and its bots, and the move's code never reaches the profile. A line
on its page says the bots from before are on My Cloud and that an older copy
-comes in from Settings → Backups. My Cloud on the rail goes back; the profile
-keeps running, so This Mac is one click again. Every launch opens My Cloud.
+comes in from Settings → Backups, until its ✕ closes it for good in that
+workspace, or by itself once it was shown on three days or a week went by. My
+Cloud on the rail goes back; the profile keeps running, so This Mac is one
+click again. A launch opens the place open when the app last closed (My Cloud,
+another Cloud, This Mac or another workspace, a server saved by hand); one that
+can't open now (removed, ended, not answering in a few seconds) is My Cloud
+instead, with no dialog, and This Mac when My Cloud doesn't run either.
This computer stays lent to My Cloud throughout: lending follows the sign-in,
and only the clean workspace for nobody who can reach the bots stops it. People
with no Cloud see no change.
```sh
-node --test electron/clean-workspace.node-test.mjs electron/home-window-profile.node-test.mjs electron/home-window-clean.node-test.mjs electron/cloud-rail.node-test.mjs electron/lending-target.node-test.mjs
+node --test electron/clean-workspace.node-test.mjs electron/home-window-profile.node-test.mjs electron/home-window-clean.node-test.mjs electron/cloud-rail.node-test.mjs electron/lending-target.node-test.mjs electron/start-place.node-test.mjs electron/home-places.node-test.mjs
pnpm exec vitest run src/components/PlacesRail.test.ts src/components/HomeLine.test.ts
OMB_UI_E2E=1 pnpm exec vitest run scripts/testing/rail-profile-ui.e2e.test.ts
```
diff --git a/electron/cloud-entry.node-test.mjs b/electron/cloud-entry.node-test.mjs
index aeca1cbfe9..61f11c33ff 100644
--- a/electron/cloud-entry.node-test.mjs
+++ b/electron/cloud-entry.node-test.mjs
@@ -135,7 +135,7 @@ test("startup delivers a pending Cloud link before default navigation", () => {
const startup = between(" let restoredOrganizationEntry = false;", " // Reconcile incomplete setup");
const delivered = startup.indexOf("const deliveredCloudEntry = await cloudEntry.ready();");
assert.ok(delivered > startup.indexOf("await deliverOrganizationEntry()"));
- assert.ok(delivered < startup.indexOf("await showHome()"));
+ assert.ok(delivered < startup.indexOf("await showStartPlace()"));
assert.ok(main.indexOf("cloudAccountStarted = ensureCloudAccount().start()") < main.indexOf(" let restoredOrganizationEntry = false;"),
"the saved sign-in starts restoring before the link is delivered");
});
diff --git a/electron/home-places.mjs b/electron/home-places.mjs
index 6ae8c1aacc..2a9b152eed 100644
--- a/electron/home-places.mjs
+++ b/electron/home-places.mjs
@@ -8,6 +8,9 @@ import environments from "./environments.cjs";
import { listedColors, ownCloudPlaces } from "./cloud-list.mjs";
const idOf = (value) => (typeof value === "string" && value ? value : null);
+/** What home-place.json may name: a team's Cloud, another Cloud of the person's own, a workspace of this computer's own
+ * (by its profile id) or a server saved by hand (by its saved place's id). */
+const KINDS = Object.freeze(["team", "cloud", "profile", "server"]);
/**
* @param {{
@@ -23,31 +26,38 @@ const idOf = (value) => (typeof value === "string" && value ? value : null);
export function createHomePlaces({ store, environments: read, persist, makeId, homeOrigin, log = () => {} }) {
let cached = null;
const pending = [];
+ /** One kind of place at most: the first of KINDS the record names. */
+ function only(record) {
+ const kind = KINDS.find((key) => idOf(record?.[key]));
+ return Object.fromEntries(KINDS.map((key) => [key, key === kind ? record[key] : null]));
+ }
function load() {
- try {
- const record = store.read();
- const team = idOf(record?.team);
- return { team, cloud: team ? null : idOf(record?.cloud) };
- } catch { return { team: null, cloud: null }; }
+ try { return only(store.read()); } catch { return only(null); }
}
const current = () => (cached ??= load());
function save(next) {
cached = next;
- try { store.write(next.cloud ? { cloud: next.cloud } : { team: next.team }); } catch (error) { log(`home places: could not save (${error?.message ?? error})`); }
+ const kind = KINDS.find((key) => next[key]) ?? "team";
+ try { store.write({ [kind]: next[kind] }); } catch (error) { log(`home places: could not save (${error?.message ?? error})`); }
}
const entryOf = (key, id) => read().environments.find((entry) => entry[key]?.id === id) ?? null;
const places = {
- /** The team or Cloud shown last time, as saved: its id, and its name and address while it is still a saved place. */
+ /** The place shown last time, as saved: its id, and for a team or Cloud its name and address while it is still a
+ * saved place. */
remembered() {
- const { team, cloud } = current(), key = team ? "team" : cloud ? "cloud" : null;
+ const saved = current(), key = KINDS.find((kind) => saved[kind]);
if (!key) return null;
- const id = team ?? cloud, entry = entryOf(key, id);
+ const id = saved[key];
+ if (key === "profile") return { profile: id };
+ if (key === "server") return { server: id };
+ const entry = entryOf(key, id);
return entry ? { [key]: id, name: entry.name, origin: entry.origin } : { [key]: id };
},
- /** What the window opens next time: a team (`{ team }`), another Cloud (`{ cloud }`), or My Cloud (null). */
+ /** What the window opens next time: a team (`{ team }`), another Cloud (`{ cloud }`), a workspace of this computer's
+ * own (`{ profile }`), a server saved by hand (`{ server }`), or My Cloud (null). */
remember(place) {
- const team = idOf(place?.team), cloud = team ? null : idOf(place?.cloud);
- if (team !== current().team || cloud !== current().cloud) save({ team, cloud });
+ const next = only(place);
+ if (KINDS.some((key) => next[key] !== current()[key])) save(next);
},
/** The team shown is no longer this person's: said once, on the next page that asks. */
left(name) {
diff --git a/electron/home-places.node-test.mjs b/electron/home-places.node-test.mjs
index d2d03d554f..94ac78f406 100644
--- a/electron/home-places.node-test.mjs
+++ b/electron/home-places.node-test.mjs
@@ -76,3 +76,20 @@ test("a remembered team whose place is gone from the file is still remembered by
assert.deepEqual(bad.places.remembered(), { team: "team-acme" }, "kept in memory for this run");
assert.equal(environments.reconcileTeams({ environments: [], activeId: "local" }, [], () => "x", HOME).state.activeId, "local");
});
+
+test("a workspace of this computer's own or a server saved by hand is remembered as one place: the latest kept, My Cloud forgets it, and a team dropped or synced away leaves it alone", () => {
+ const w = world();
+ w.places.remember({ profile: "work" });
+ assert.deepEqual(w.places.remembered(), { profile: "work" });
+ assert.deepEqual(w.saved, { profile: "work" });
+ w.places.remember({ server: "env-1" });
+ assert.deepEqual([w.places.remembered(), w.saved], [{ server: "env-1" }, { server: "env-1" }], "one place at a time");
+ w.places.remember({ profile: "default" });
+ w.places.sync(connected([beta]));
+ w.places.drop({ id: "team-acme", name: "Acme" });
+ assert.deepEqual(w.places.remembered(), { profile: "default" }, "teams coming and going never touch it");
+ w.places.remember(null);
+ assert.equal(w.places.remembered(), null);
+ assert.deepEqual(world({ saved: { profile: "work", team: "team-acme" } }).places.remembered(), { team: "team-acme" }, "a file naming two: the first kind wins");
+ assert.equal(world({ saved: { profile: 7 } }).places.remembered(), null, "an id that isn't one: nothing");
+});
diff --git a/electron/home-window-states.node-test.mjs b/electron/home-window-states.node-test.mjs
index 2e41c52f38..6f99d6ab16 100644
--- a/electron/home-window-states.node-test.mjs
+++ b/electron/home-window-states.node-test.mjs
@@ -5,7 +5,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import { cloudScreen, HOME_SCREEN_PATH, installHomeWindowIpc, OPEN_MS } from "./home-window.mjs";
-import { CLIENT, CLIENT_A, CLOUD, connected, LOCAL, world } from "./fixtures/home-window-world.mjs";
+import { ACME, CLIENT, CLIENT_A, CLOUD, connected, LOCAL, TEAM, world } from "./fixtures/home-window-world.mjs";
const ENDED_HOME = { ...CLIENT_A, id: "c-home", name: "My Cloud", color: null, origin: CLOUD, primary: true, status: "ended", deleteAfter: 1_900_000_000_000, removable: true };
test("My Cloud that ended, asked for before the move: its own screen with the day its files go and Remove from list; its address is never looked up", async () => {
@@ -160,3 +160,23 @@ test("Sign in never dead-ends: another account's sign-in ends first, then the br
await opening.home.signIn();
assert.deepEqual(opening.signIns, ["reopen"]);
});
+
+test("what a launch may open now, by the session's word alone: a running Cloud or team yes; one ended, set up, held, gone or without an address no; nothing while signed out", async () => {
+ const w = world({ state: { ...connected(), teams: [ACME], clouds: [CLIENT_A, { ...CLIENT_A, id: "c-ended", status: "ended" }, { ...CLIENT_A, id: "c-setup", status: "setting_up", origin: null, setup: { step: "starting" } }] } });
+ await w.home.refresh();
+ assert.equal(w.home.opensNow("cloud"), true);
+ assert.equal(w.home.opensNow({ cloud: "c-a" }), true);
+ assert.equal(w.home.opensNow({ team: ACME.id }), true);
+ for (const ask of [{ cloud: "c-ended" }, { cloud: "c-setup" }, { cloud: "c-gone" }, { team: "team-gone" }]) assert.equal(w.home.opensNow(ask), false, JSON.stringify(ask));
+ assert.deepEqual([w.fetched, w.pairs], [[], 0], "nothing looked up");
+ const held = world({ state: { ...connected(), teams: [{ ...ACME, machine: { status: "stopped", origin: TEAM } }] } });
+ await held.home.refresh();
+ assert.equal(held.home.opensNow({ team: ACME.id }), false, "a team's stopped Cloud");
+ const ended = world({ state: { ...connected({ status: "stopped" }), clouds: [{ ...CLIENT_A, id: "c-home", origin: CLOUD, primary: true, status: "ended" }] } });
+ await ended.home.refresh();
+ assert.equal(ended.home.opensNow("cloud"), false, "My Cloud ended");
+ const out = world({ state: { status: "signed-out" } });
+ await out.home.refresh();
+ assert.equal(out.home.opensNow("cloud"), null);
+ assert.equal(out.home.opensNow({ team: ACME.id }), null);
+});
diff --git a/electron/home-window.d.mts b/electron/home-window.d.mts
index 37d10df3f4..22fb0dfc2e 100644
--- a/electron/home-window.d.mts
+++ b/electron/home-window.d.mts
@@ -40,7 +40,9 @@ export type Home = ({ kind: "computer" } | { kind: "cloud"; origin: string } | {
export type HomePlace = { kind: "cloud"; origin: string } | { kind: "team" | "own"; id: string; name: string; role: string | null; origin: string };
/** What to open: My Cloud, a team's Cloud, another Cloud of the person's own, or (null) the place remembered from last time. */
export type HomeAsk = "cloud" | { team: string; name?: string } | { cloud: string; name?: string } | null;
-export type RememberedPlace = (({ team: string } | { cloud: string }) & { name?: string; origin?: string }) | null;
+/** The place the window showed last, as home-places.mjs keeps it: a team's Cloud or another of the person's own (with its
+ * name and address as saved), a workspace of this computer's own, or a server saved by hand. */
+export type RememberedPlace = (({ team: string } | { cloud: string }) & { name?: string; origin?: string }) | { profile: string } | { server: string } | null;
export declare function otherPlace(place: unknown): boolean;
/** This computer's screen for a listed Cloud that isn't running (or its setup's step); null for one that opens. */
export declare function cloudScreen(cloud: import("./cloud-list.mjs").CloudListEntry | null | undefined): HomeView | null;
@@ -76,6 +78,7 @@ export interface HomeWindow {
show(options?: { open?: "phone" | null; place?: HomeAsk }): Promise<unknown>;
openProfile(id: string): Promise<boolean>;
profile(): string | null;
+ opensNow(ask: "cloud" | { team: string } | { cloud: string }): boolean | null;
cancel(): void;
openCloud(open?: "phone" | null): Promise<unknown>;
/** Remove from list from this computer's screen: the Cloud it shows leaves the person's list. */
@@ -121,7 +124,7 @@ export function createHomeWindow(deps: {
showLocal(leaving: boolean): unknown;
clean?: import("./clean-workspace.mjs").CleanWorkspace | null;
remembered?(): RememberedPlace;
- remember?(place: { team: string } | { cloud: string } | null): void;
+ remember?(place: { team: string } | { cloud: string } | { profile: string } | { server: string } | null): void;
left?(name: string): void;
drop?(place: { kind: "team" | "own"; id: string; name: string }): void;
splash?(): { status(text: string): void } | null;
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index a63561019e..aac2865a91 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -238,8 +238,7 @@ export function createHomeWindow(deps) {
now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, ownMove = () => null, log = () => {}, t = nativeText.englishText.t } = deps;
let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;
let recovering = null;
- /** The profile (clean-workspace.mjs) the person opened from the rail while My Cloud is home, until they pick a place. Never
- * remembered: each launch opens My Cloud. */
+ /** The profile (clean-workspace.mjs) the person opened from the rail while My Cloud is home, until they pick a place. */
let profileShown = null;
/** My Cloud asked for before the move made it home (`{ open }`), until its page loads or the person goes elsewhere;
* `naming`: since when, and how often, a brand-new My Cloud's name was not found. */
@@ -663,6 +662,17 @@ export function createHomeWindow(deps) {
},
/** The profile on screen, opened from the rail, else null. */
profile: () => profileShown,
+ /** Whether `ask` ("cloud" for My Cloud, or a team or another Cloud of the person's own as remembered) would open now, by
+ * the session's word and nothing looked up: false for one gone from its list, not running, being set up or without an
+ * address, and for My Cloud while it isn't home or isn't running; null while nobody is signed in. As of the last
+ * refresh(). */
+ opensNow(ask) {
+ if (signedOut()) return null;
+ if (ask === "cloud") return home.kind === "cloud" && !notRunning();
+ const target = placeOf({ ask, remembered: remembered(), state: state() });
+ if (!otherPlace(target) || !target.origin || machineSetup(target.machine)) return false;
+ return !target.machine || !(PLAN_PROBLEMS.has(target.machine.status) || (target.kind === "team" && target.machine.hold));
+ },
/** The person asked for My Cloud (the Server menu, the welcome, Settings, the ready notice). Before the move made it
* home it opens as a saved server, and while the Admin sets it up the setup screen shows until it opens by itself. */
async openCloud(open = null) {
diff --git a/electron/local-profiles.d.mts b/electron/local-profiles.d.mts
index 3de49b9eed..14de844364 100644
--- a/electron/local-profiles.d.mts
+++ b/electron/local-profiles.d.mts
@@ -51,6 +51,7 @@ export function createLocalProfiles(deps: {
trash(dir: string): Promise<void>;
reserved?(): string | null;
allowed?(): boolean;
+ remember?(place: { profile: string } | null): void;
changed?(): void;
log?(line: string): void;
fs?: typeof import("node:fs");
diff --git a/electron/local-profiles.mjs b/electron/local-profiles.mjs
index ebc3e55ec7..0c90e554e0 100644
--- a/electron/local-profiles.mjs
+++ b/electron/local-profiles.mjs
@@ -125,6 +125,7 @@ export function createProfileRegistry({ dataDir, fs = nodeFs, now = Date.now, ra
* trash(dir: string): Promise<void>,
* reserved?(): string | null,
* allowed?(): boolean,
+ * remember?(place: { profile: string } | null): void,
* changed?(): void,
* log?(line: string): void,
* fs?: typeof nodeFs,
@@ -135,10 +136,11 @@ export function createProfileRegistry({ dataDir, fs = nodeFs, now = Date.now, ra
* home window's profile on screen (home-window.mjs), and My Cloud shown again. `showLocal()`: the window onto this
* computer's page, LOCAL_ID active. `onLocal()`: this computer's page is on screen. `busy()`: what the server that runs now
* still does (GET /api/move/freeze), null when nothing. `trash(dir)`: moves a folder to the computer's Trash. `reserved()`:
- * what This Mac is called here (This Mac or This PC).
+ * what This Mac is called here (This Mac or This PC). `remember(place)`: the place the next launch opens:
+ * the workspace that opened, or null once This computer's own copy is back.
*/
export function createLocalProfiles({ registry, clean, dataDir, home, window: shown, showLocal, onLocal, busy, trash, reserved = () => null, allowed = () => true,
- changed = () => {}, log = () => {}, fs = nodeFs, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now, settleMs = SETTLE_MS }) {
+ remember = () => {}, changed = () => {}, log = () => {}, fs = nodeFs, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = Date.now, settleMs = SETTLE_MS }) {
/** Each switch asked for; a newer one (another tile, My Cloud) ends the wait of the one before. */
let turn = 0;
/** The workspace a switch waits to open (null: This computer's own copy), and for whom. */
@@ -174,6 +176,7 @@ export function createLocalProfiles({ registry, clean, dataDir, home, window: sh
const stops = running() !== id && (home() === "local" || running() !== null);
if (!(await settle(mine, id, stops))) return null;
const opened = home() === "cloud" ? await shown.openProfile(id) : running() === id ? (await showLocal(), true) : await clean.open(id);
+ if (opened) remember({ profile: id });
return opened || mine === turn ? opened : null;
}
@@ -194,9 +197,11 @@ export function createLocalProfiles({ registry, clean, dataDir, home, window: sh
/** Back to This computer's own copy from a workspace (no home but this computer). */
async computer() {
const mine = ++turn;
- if (running() === null) { await showLocal(); return true; }
+ if (running() === null) { await showLocal(); remember(null); return true; }
if (!(await settle(mine, null, true))) return null;
- return clean.leave();
+ const left = await clean.leave();
+ if (left && mine === turn) remember(null);
+ return left;
},
/** Another place was chosen: a switch still waiting ends. */
cancel() { turn++; if (settling) { settling = null; tell(); } },
diff --git a/electron/local-profiles.node-test.mjs b/electron/local-profiles.node-test.mjs
index a5efe1d30c..92f0abf160 100644
--- a/electron/local-profiles.node-test.mjs
+++ b/electron/local-profiles.node-test.mjs
@@ -16,7 +16,7 @@ function computer(t, { home = "cloud", frozen = home === "cloud" } = {}) {
mkdirSync(dataDir, { recursive: true });
if (frozen) writeFileSync(join(dataDir, "moved.json"), JSON.stringify({ v: 1, at: 1, cloud: "https://omb-t-1.fly.dev" }));
let clock = 1_000;
- const w = { dataDir, running: dataDir, swaps: [], home, shown: null, onScreen: "cloud", busy: [], trashed: [], trashFails: false, changes: 0, logs: [], waits: 0 };
+ const w = { dataDir, running: dataDir, swaps: [], home, shown: null, onScreen: "cloud", busy: [], trashed: [], trashFails: false, changes: 0, logs: [], waits: 0, remembered: [] };
w.now = () => clock;
w.clean = createCleanWorkspace({ dataDir: () => dataDir, running: () => w.running,
swap: async (dir) => { w.swaps.push(dir); await new Promise((resolve) => setImmediate(resolve)); w.running = dir; w.onScreen = "local"; return { ok: true }; } });
@@ -30,7 +30,7 @@ function computer(t, { home = "cloud", frozen = home === "cloud" } = {}) {
showLocal: () => { w.onScreen = "local"; }, onLocal: () => w.onScreen === "local",
busy: async () => w.busy[0] ?? null,
trash: async (dir) => { if (w.trashFails) throw new Error("no Trash here"); w.trashed.push(dir); rmSync(dir, { recursive: true, force: true }); },
- reserved: () => "This Mac", changed: () => { w.changes++; }, log: (line) => w.logs.push(line), now: w.now,
+ reserved: () => "This Mac", remember: (place) => w.remembered.push(place), changed: () => { w.changes++; }, log: (line) => w.logs.push(line), now: w.now,
sleep: async (ms) => { clock += ms; w.waits++; w.onWait?.(); } });
w.file = () => join(profilesDir(dataDir), PROFILES_FILE);
w.saved = () => JSON.parse(readFileSync(w.file(), "utf8"));
@@ -257,3 +257,22 @@ test("a switch a newer click took over while its workspace started says so (null
w.beforeOpen = () => false;
assert.equal(await w.profiles.open("work"), false, "with no newer click it didn't open: main says so");
});
+
+test("the workspace that opened is the place the next launch opens; one that didn't, or lost to a newer switch, isn't; This computer again forgets it", async (t) => {
+ const w = computer(t);
+ w.registry.create({ name: "Work" });
+ assert.equal(await w.profiles.open("work"), true);
+ assert.equal(await w.profiles.open("gone"), false);
+ assert.deepEqual(w.remembered, [{ profile: "work" }]);
+ w.busy = [{ name: "Scout" }];
+ let newer = null;
+ w.onWait = () => { w.onWait = null; w.busy = []; newer = w.profiles.open("work"); };
+ assert.equal(await w.profiles.open(DEFAULT_PROFILE), null, "a newer switch took over");
+ assert.equal(await newer, true);
+ assert.deepEqual(w.remembered, [{ profile: "work" }, { profile: "work" }], "only the switch that won");
+ const local = computer(t, { home: "local" });
+ local.registry.create({ name: "Work" });
+ assert.equal(await local.profiles.open("work"), true);
+ assert.equal(await local.profiles.computer(), true);
+ assert.deepEqual(local.remembered, [{ profile: "work" }, null]);
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index d313cad892..e8622dbd0f 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -108,7 +108,7 @@ import { cleanWorkspaceDir, createCleanWorkspace, profilesDir } from "./clean-wo
import { askForMicrophone, openPrivacySettings } from "./privacy-settings.mjs";
import { createHomeWindow, installHomeWindowIpc } from "./home-window.mjs";
import { createTeamProfileSeeds } from "./team-profile-seed.mjs";
-import { createHomePlaces } from "./home-places.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";
+import { createHomePlaces } from "./home-places.mjs"; import { openStartPlace } from "./start-place.mjs"; import { createDesktopRing, installAccounts } from "./accounts-main.mjs"; import { createAddedCloudNotice, installCloudRail, railPlaces } from "./cloud-rail.mjs"; import { createPlaceInboxWatch } from "./place-inbox-watch.mjs"; import { homeLook, otherOwnClouds, withoutOldCloudHome } from "./cloud-list.mjs"; import { installPlaceLook } from "./place-look.mjs"; import { CHROME_RAIL_PATH, createChromeRail } from "./chrome-rail.mjs";
import { createWindowStateFile } from "./window-state-file.mjs";
import { createEnvironmentsFile, ENVIRONMENTS_SAVE_FAILED } from "./environments-file.mjs";
import { createOrgLibrary } from "./org-library.mjs";
@@ -1691,7 +1691,7 @@ async function switchEnvironment(id) {
}
}
if (entry && handSaved(entry) && !(await serverOpens(entry, { t: nativeT, fetch: (...args) => session.defaultSession.fetch(...args), dialog, forget: (gone) => forgetEnvironment(gone, false, true) }))) return;
- persistEnvironments(withActive(environmentsState, id)); navigateMainWindow(activeOrigin());
+ persistEnvironments(withActive(environmentsState, id)); navigateMainWindow(activeOrigin()); if (entry && handSaved(entry) && homeWindow.cloudOrigin()) homePlaces.remember({ server: id });
}
function createLocalEnvironment(name, dataDir) {
@@ -2665,9 +2665,9 @@ installHomeWindowIpc({ ipcMain, homeWindow, cloudPage: cloudPageAsking });
function showHome(options) {
return homeWindow.show(options).catch(error => slog(`home: ${error?.message ?? error}`));
}
-const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };
+const showStartPlace = () => openStartPlace({ home: homeWindow, places: homePlaces, profiles: localProfiles, log: slog, server: id => { const entry = environmentsState.environments.find(candidate => candidate.id === id && handSaved(candidate)); return entry ? reopenSavedServer(entry, { saved: () => environmentsState.environments.filter(handSaved), fetch: (...args) => session.defaultSession.fetch(...args), opened: async (found) => { if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: true }); persistEnvironments(withActive(environmentsState, found.id)); return navigateMainWindow(activeOrigin()); } }) : Promise.resolve(false); } }).catch(error => slog(`start: ${error?.message ?? error}`)); const openOwnCloud = id => { homeWindow.cancel(); return showHome({ place: { cloud: id, name: environmentsState.environments.find(entry => entry.cloud?.id === id)?.name } }); };
const placeInbox = createPlaceInboxWatch({ places: () => [{ id: LOCAL_ID, local: true }, ...environmentsState.environments.filter(entry => entry.kind !== "local" && entry.origin)], activeId: () => environmentsState.activeId, local: localServerRequest, cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), shown: () => !desktopRemoteAccess && serverReady && Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isVisible()), changed: () => railChanged() });
-const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };
+const localProfiles = createLocalProfiles({ registry: createProfileRegistry({ dataDir: desktopDataDir }), clean: cleanWorkspace, dataDir: desktopDataDir, allowed: () => app.isPackaged && !desktopRemoteAccess, home: () => (homeWindow.cloudOrigin() ? "cloud" : ownHome?.origin() || cleanWorkspace.marker().frozen ? null : "local"), window: { openProfile: id => homeWindow.openProfile(id), profile: () => homeWindow.profile(), showCloud: () => showHome({ place: "cloud" }) }, showLocal: () => { homeWindow.cancel(); persistEnvironments(withActive(environmentsState, LOCAL_ID)); return navigateMainWindow(rendererOrigin()); }, onLocal: () => Boolean(mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })), busy: async () => { const said = await (await localServerRequest("/api/move/freeze", { signal: AbortSignal.timeout(5_000) })).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; }, trash: dir => shell.trashItem(dir), reserved: () => nativeT(process.platform === "darwin" ? "rail.thisMac" : "rail.thisPc"), remember: homePlaces.remember, changed: () => railChanged(), log: slog }); const railList = () => { ownHome?.refresh(); const settling = localProfiles.settling(); return railPlaces({ saved: environmentsState, waiting: placeInbox.waiting, home: homeWindow.cloudOrigin() ?? ownHome?.origin() ?? null, mine: myCloud(), state: desktopRemoteAccess ? null : cloudAccount?.state(), offers: entry => !desktopRemoteAccess && ownHome?.offers(entry) === true, accounts: accountRing.waiting(), profiles: localProfiles.places({ activeLocal: environmentsState.activeId === LOCAL_ID }), computerSettling: settling && settling.id === null ? settling.name : null }); };
// The rail as the window's own chrome (chrome-rail.mjs): this app's page beside every place's page, the one that lists.
const chromeRail = createChromeRail({ createView: options => new WebContentsView(options), preload: path.join(__dirname, "preload.cjs"), log: slog, prefs: () => desktopPrefs, changed: () => rail.changed(),
args: () => [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`],
@@ -3124,7 +3124,7 @@ app.whenReady().then(async () => {
// A cold-start action owns its first navigation; a default load started first would be aborted by it.
const deliveredOrganizationEntry = await deliverOrganizationEntry();
const deliveredCloudEntry = await cloudEntry.ready();
- if (!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry) await showHome();
+ if (!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry) await showStartPlace();
// Reconcile incomplete setup and resume interrupted sign-out only once the local app is usable.
if (hostedAccount) void hostedAccount.restore().catch(() => {});
// Registering from an unreadable store would mint a second installation identity.
diff --git a/electron/organization-entry.node-test.mjs b/electron/organization-entry.node-test.mjs
index 7a6d418ae8..88230fb7e0 100644
--- a/electron/organization-entry.node-test.mjs
+++ b/electron/organization-entry.node-test.mjs
@@ -214,9 +214,9 @@ test("native entry checks owned server readiness before creating, sending to, or
test("startup delivers a pending organisation action before default navigation and falls back after cancellation", () => {
const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8");
const startup = main.slice(main.indexOf(" let restoredOrganizationEntry = false;"), main.indexOf(" // Reconcile incomplete setup"));
- assert.ok(startup.indexOf("await deliverOrganizationEntry()") < startup.indexOf("await showHome()"));
+ assert.ok(startup.indexOf("await deliverOrganizationEntry()") < startup.indexOf("await showStartPlace()"));
// A launch from the login item lending added opens no window: lending runs out of sight until the person opens it.
- assert.match(startup, /if \(!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry\) await showHome\(\);/);
+ assert.match(startup, /if \(!hiddenStart && !restoredOrganizationEntry && !deliveredOrganizationEntry && !deliveredCloudEntry\) await showStartPlace\(\);/);
});
test("concurrent links share one confirmation and stale confirmations cannot change a new selection", async () => {
diff --git a/electron/save-file.node-test.mjs b/electron/save-file.node-test.mjs
index 6a20ac8d99..2ae1fb3e90 100644
--- a/electron/save-file.node-test.mjs
+++ b/electron/save-file.node-test.mjs
@@ -149,7 +149,7 @@ describe("attachment download destination", () => {
assert.notEqual(handler, -1);
assert.match(main.slice(handler), /item\.setSavePath\(collisionFreeDownloadPath\(/);
assert.match(main.slice(handler), /revealDownloadWhenDone\(item, /);
- assert.ok(handler < main.indexOf("!deliveredCloudEntry) await showHome();"));
+ assert.ok(handler < main.indexOf("!deliveredCloudEntry) await showStartPlace();"));
});
it("reveals only a completed download at its actual save path", () => {
diff --git a/electron/server-session.node-test.mjs b/electron/server-session.node-test.mjs
index 985a5c2b00..caf656fba7 100644
--- a/electron/server-session.node-test.mjs
+++ b/electron/server-session.node-test.mjs
@@ -66,7 +66,7 @@ test("every session main creates gets the guard before it loads anything", () =>
const install = main.indexOf("installServerSessions({");
assert.ok(install > 0);
assert.equal(main.indexOf("installServerSessions({", install + 1), -1);
- assert.ok(main.indexOf("await showHome();", install) > install, "installed before the first window");
+ assert.ok(main.indexOf("await showStartPlace();", install) > install, "installed before the first window");
assert.doesNotMatch(main, /onBeforeSendHeaders/, "the owner header is added in one place");
assert.equal(targetsServer(`http://2130706433:${SERVER_PORT}/`, SERVER_PORT), true);
});
diff --git a/electron/start-place.mjs b/electron/start-place.mjs
new file mode 100644
index 0000000000..6ec64a4d68
--- /dev/null
+++ b/electron/start-place.mjs
@@ -0,0 +1,38 @@
+// The place a launch opens: the one on screen when the app last closed. One that can't open now falls back without a
+// dialog: to My Cloud, and when My Cloud doesn't run either, to This Mac. A workspace of this computer's own opens only
+// through `profiles`, so one runs at a time and the frozen copy is never one of them.
+import { DEFAULT_PROFILE } from "./clean-workspace.mjs";
+
+/**
+ * @param {{
+ * home: { refresh(): Promise<{ kind: string }>, show(options?: object): Promise<unknown>, opensNow(ask: unknown): boolean | null },
+ * places: { remembered(): any, remember(place: null): void },
+ * profiles: { open(id: string): Promise<boolean | null> } | null,
+ * server(id: string): Promise<boolean>,
+ * log?(line: string): void,
+ * }} deps `home`: the home window. `profiles`: the workspaces of this computer's own, null where there are
+ * none. `server(id)`: opens the server saved by hand under that id without a dialog, false when it isn't saved or doesn't
+ * answer in a short wait.
+ * @returns {Promise<"remembered" | "cloud" | "this-mac" | "home">} where the window went: the remembered place, My Cloud
+ * instead of it, This Mac instead of both, or home as worked out with nothing remembered (or nobody signed in).
+ */
+export async function openStartPlace({ home, places, profiles, server, log = () => {} }) {
+ const { kind } = await home.refresh();
+ const last = places.remembered();
+ // Signed out, nothing of the account's opens: home shows as ever, and the place waits for the person to be back.
+ if (!last || home.opensNow("cloud") === null) { await home.show(); return "home"; }
+ if (await reopens(last)) return "remembered";
+ log(`start: the place open last time can't open now (${Object.keys(last)[0]}); My Cloud instead`);
+ places.remember(null);
+ if (kind === "cloud" && home.opensNow("cloud") === false && profiles && (await profiles.open(DEFAULT_PROFILE)) === true) return "this-mac";
+ await home.show();
+ return "cloud";
+
+ async function reopens(place) {
+ if (typeof place.profile === "string") return Boolean(profiles) && (await profiles.open(place.profile)) === true;
+ if (typeof place.server === "string") return kind === "cloud" && (await server(place.server).catch(() => false)) === true;
+ if (!home.opensNow(place)) return false;
+ await home.show();
+ return true;
+ }
+}
diff --git a/electron/start-place.node-test.mjs b/electron/start-place.node-test.mjs
new file mode 100644
index 0000000000..b393b38c23
--- /dev/null
+++ b/electron/start-place.node-test.mjs
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { openStartPlace } from "./start-place.mjs";
+
+/** A launch: the home window's word on each place (`opens`), the workspaces that open (`workspaces`), the servers that answer. */
+function launch({ remembered = null, kind = "cloud", opens = {}, workspaces = ["default", "work"], servers = [], profiles = true } = {}) {
+ const w = { remembered, steps: [], forgot: 0 };
+ const args = {
+ home: {
+ refresh: async () => { w.steps.push("refresh"); return { kind }; },
+ show: async () => { w.steps.push("show"); },
+ opensNow: (ask) => { const key = ask === "cloud" ? "cloud" : ask.team ?? ask.cloud; return key in opens ? opens[key] : true; },
+ },
+ places: { remembered: () => w.remembered, remember: (place) => { w.remembered = place; w.forgot++; } },
+ profiles: profiles ? { open: async (id) => { w.steps.push(`profile:${id}`); return workspaces.includes(id); } } : null,
+ server: async (id) => { w.steps.push(`server:${id}`); if (id === "throws") throw new Error("boom"); return servers.includes(id); },
+ };
+ w.run = () => openStartPlace(args);
+ return w;
+}
+
+test("a launch reopens the place open when the app closed: This Mac, a named workspace, a server, a team or another Cloud", async () => {
+ for (const [remembered, step] of [[{ profile: "default" }, "profile:default"], [{ profile: "work" }, "profile:work"], [{ server: "env-1" }, "server:env-1"]]) {
+ const w = launch({ remembered, servers: ["env-1"] });
+ assert.equal(await w.run(), "remembered", step);
+ assert.deepEqual(w.steps, ["refresh", step], "nothing else opens first");
+ assert.equal(w.forgot, 0);
+ }
+ for (const remembered of [{ team: "team-acme" }, { cloud: "c-b" }]) {
+ const w = launch({ remembered });
+ assert.equal(await w.run(), "remembered");
+ assert.deepEqual(w.steps, ["refresh", "show"], "the window opens the remembered Cloud itself");
+ }
+ const none = launch();
+ assert.equal(await none.run(), "home");
+ assert.deepEqual(none.steps, ["refresh", "show"]);
+});
+
+test("one that can't open now falls back to My Cloud and is forgotten: a removed workspace, a server that doesn't answer, an ended Cloud", async () => {
+ for (const [remembered, extra] of [[{ profile: "gone" }, {}], [{ server: "env-9" }, {}], [{ server: "throws" }, {}], [{ cloud: "c-ended" }, { opens: { "c-ended": false } }], [{ team: "team-x" }, { opens: { "team-x": false } }]]) {
+ const w = launch({ remembered, ...extra });
+ assert.equal(await w.run(), "cloud", JSON.stringify(remembered));
+ assert.equal(w.steps.at(-1), "show", "My Cloud, as ever");
+ assert.equal(w.remembered, null, "the next launch doesn't try it again");
+ }
+ const local = launch({ remembered: { server: "env-1" }, kind: "computer", servers: ["env-1"] });
+ assert.equal(await local.run(), "cloud", "with this computer as home, a saved server is the Server menu's own as ever");
+ assert.deepEqual(local.steps, ["refresh", "show"]);
+});
+
+test("then This Mac, when My Cloud doesn't run either; neither when This Mac can't open, nor when this computer is home", async () => {
+ const w = launch({ remembered: { profile: "gone" }, opens: { cloud: false } });
+ assert.equal(await w.run(), "this-mac");
+ assert.deepEqual(w.steps, ["refresh", "profile:gone", "profile:default"]);
+ const none = launch({ remembered: { profile: "gone" }, opens: { cloud: false }, workspaces: [] });
+ assert.equal(await none.run(), "cloud");
+ assert.deepEqual(none.steps.at(-1), "show");
+ const computer = launch({ remembered: { profile: "gone" }, kind: "computer", opens: { cloud: false } });
+ assert.equal(await computer.run(), "cloud");
+ assert.deepEqual(computer.steps, ["refresh", "profile:gone", "show"]);
+ const noProfiles = launch({ remembered: { profile: "default" }, profiles: false });
+ assert.equal(await noProfiles.run(), "cloud");
+});
+
+test("nobody signed in: home as ever, and the place stays remembered for when they're back", async () => {
+ const w = launch({ remembered: { profile: "work" }, opens: { cloud: null } });
+ assert.equal(await w.run(), "home");
+ assert.deepEqual(w.steps, ["refresh", "show"]);
+ assert.deepEqual(w.remembered, { profile: "work" });
+});
diff --git a/scripts/testing/one-workspace-fixture.ts b/scripts/testing/one-workspace-fixture.ts
index 6c8526221b..430cf39bbb 100644
--- a/scripts/testing/one-workspace-fixture.ts
+++ b/scripts/testing/one-workspace-fixture.ts
@@ -32,6 +32,7 @@ import { createLendingTarget } from "../../electron/lending-target.mjs";
import { createCloudPowerGate } from "../../electron/cloud-power.mjs";
import environments from "../../electron/environments.cjs";
import { createHomePlaces } from "../../electron/home-places.mjs";
+import { openStartPlace } from "../../electron/start-place.mjs";
import { createHomeWindow, installHomeWindowIpc, HOME_SCREEN_PATH } from "../../electron/home-window.mjs";
import { createStartupScreen } from "../../electron/startup-screen.mjs";
import { packageUrlFromDeepLink } from "../../electron/package-link.mjs";
@@ -270,9 +271,10 @@ export interface HomeWorld {
setSize(width: number, height: number): Promise<void>;
/** The OS's light or dark look, which both pages follow. */
theme(dark: boolean): Promise<void>;
- /** The app quits and opens again: this computer's server stopped as a quit stops it and started on the data folder, and a
- * new home window that knows nothing of the last run shows home. */
- restartApp(): Promise<void>;
+ /** The app quits and opens again: this computer's server stopped as a quit stops it and started on the data folder, then
+ * `whileClosed` (what changes while the app is closed), and a new home window that knows nothing of the last run opens the
+ * place remembered from it, as a launch does. */
+ restartApp(whileClosed?: () => unknown): Promise<void>;
/** Each request My Cloud's edge passed on, in order. */
cloudRequests: Array<{ path: string; at: number }>;
/** main.mjs's own chat-link delivery, as a link from the OS reaches it. */
@@ -632,7 +634,7 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
onLocal: () => /^https?:/.test(win.url) && new URL(win.url).origin === localOrigin,
busy: async () => { const said = await (await ownCopy("/api/move/freeze")).json(); return typeof said?.busy === "string" ? { name: said.busy, what: said.what } : null; },
trash: async (dir: string) => { mkdirSync(trashDir, { recursive: true }); renameSync(dir, join(trashDir, `${Date.now()}-${dir.split(/[\\/]/).pop()}`)); },
- reserved: () => "This Mac", changed: () => railHandlers?.changed() }) : null);
+ reserved: () => "This Mac", remember: homePlaces.remember, changed: () => railHandlers?.changed() }) : null);
let localProfiles = makeLocal();
const railList = () => {
const settling = localProfiles?.settling() ?? null;
@@ -701,14 +703,15 @@ export async function launchHomeWorld(fx: CloudSendFixture, { chrome, ports, ver
}
await new Promise((resolve) => setTimeout(resolve, 3_000));
},
- async restartApp() {
+ async restartApp(whileClosed?: () => unknown) {
homeRef!.close();
// A quit stops this computer's server as main's before-quit does, and the next launch starts it on the data folder.
await fx.relaunch({ kill: false });
running = fx.desktopDataDir;
+ await whileClosed?.();
home = launchHome();
localProfiles = makeLocal();
- await home.show();
+ await openStartPlace({ home, places: homePlaces, profiles: localProfiles, server: async () => false });
if (railRef) await railRef.loadURL(`${localOrigin}/rail`);
},
cloudOrigin, localOrigin, teamOrigin, otherOrigin, window: win, get home() { return homeRef!; }, account, network, admin, cloudRequests, notifications, hostCache,
diff --git a/scripts/testing/rail-profile-ui.e2e.test.ts b/scripts/testing/rail-profile-ui.e2e.test.ts
index 3b2ca02501..6eed74838a 100644
--- a/scripts/testing/rail-profile-ui.e2e.test.ts
+++ b/scripts/testing/rail-profile-ui.e2e.test.ts
@@ -318,27 +318,58 @@ function harness(get: () => { world: HomeWorld; shots: string }) {
await picture("09-removed-open-one");
}, hostTimeout(240_000));
- it("an app restart while a workspace is open: My Cloud opens, the frozen copy's server is back without a workspace stranded, and the workspace opens again as it was", async () => {
+ it("an app restart reopens the place open when it closed: Work, then This Mac, each as it was; a workspace removed meanwhile opens My Cloud", async () => {
await click("[data-rail-add]");
await until(() => rail("Boolean(document.querySelector('[data-place-add-choice=\"local\"]'))"), Boolean, 15_000, "+'s choices");
await click('[data-place-add-choice="local"]');
await until(() => rail("Boolean(document.querySelector('[data-local-name]'))"), Boolean, 15_000);
- await fill("[data-local-name]", "Personal");
+ await fill("[data-local-name]", "Work");
await click("[data-local-create]");
- const personal = world.registry!.list().find((entry) => entry.name === "Personal")!.id;
- await shown(`profile:${personal}`);
+ const work = workId();
+ await shown(`profile:${work}`);
await page("fetch('/api/bots', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'Diary' }) })");
await world.restartApp();
- await onCloud();
- expect(world.running(), "a launch starts the data folder's server, as ever").toBe(fx.desktopDataDir);
- expect(world.clean!.active()).toBe(false);
+ await shown(`profile:${work}`, "Diary");
+ expect(world.running(), "Work's server, not the frozen copy's").toBe(profileDir(fx.desktopDataDir, work));
+ expect(JSON.parse(readFileSync(join(fx.desktopDataDir, "moved.json"), "utf8")).cloud, "the frozen copy stays frozen").toBe(world.cloudOrigin);
const after = await until(() => tiles(), (seen) => seen.length === 3, 30_000, "the rail after the restart");
- expect(after.map((tile) => [tile.id, tile.current])).toEqual([["profile:default", false], [`profile:${personal}`, false], [cloudEntry, true]]);
- await picture("10-after-restart");
- await click(`[data-rail-place="profile:${personal}"]`);
- await shown(`profile:${personal}`, "Diary");
+ expect(after.map((tile) => [tile.id, tile.current])).toEqual([["profile:default", false], [`profile:${work}`, true], [cloudEntry, false]]);
+ await picture("10-after-restart-work");
await until(async () => lent(), Boolean, 30_000, "this computer lent again after the restart");
- }, hostTimeout(240_000));
+ await click(MAC);
+ await shown("profile:default", "Scout");
+ await world.restartApp();
+ await shown("profile:default", "Scout");
+ expect(world.running()).toBe(profileDir(fx.desktopDataDir, "default"));
+ expect((await tiles()).map((tile) => [tile.id, tile.current])).toEqual([["profile:default", true], [`profile:${work}`, false], [cloudEntry, false]]);
+ await picture("10-after-restart-this-mac");
+ // Its line's ✕ closes it for good in This Mac's own config: a reload doesn't bring it back, and Work's still shows.
+ await until(() => page<boolean>("(() => { const close = document.querySelector('[data-home-line-close]'); close?.click(); return Boolean(close); })()"), Boolean, 15_000, "the line's ✕");
+ await until(lineOf, (text) => text === null, 10_000, "the line closed");
+ await world.window.loadURL(`${world.localOrigin}/`);
+ await until(() => page<string>("document.body.innerText"), (text) => text.includes("Scout"), 60_000, "This Mac reloaded");
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ expect(await lineOf(), "closed for good").toBeNull();
+ await click(`[data-rail-place="profile:${work}"]`);
+ await until(lineOf, (text) => Boolean(text?.startsWith("Work starts fresh")), 60_000, "Work's own line, still there");
+ await click(MAC);
+ await shown("profile:default", "Scout");
+ // A workspace removed while the app was closed: My Cloud opens instead, with no dialog, and the next launch doesn't try it again.
+ expect(world.profiles!.create({ name: "Spare" }).outcome).toBe("made");
+ const spare = world.registry!.list().find((entry) => entry.name === "Spare")!.id;
+ await click(`[data-rail-place="profile:${spare}"]`);
+ await shown(`profile:${spare}`);
+ await world.restartApp(() => { world.registry!.remove(spare); rmSync(profileDir(fx.desktopDataDir, spare), { recursive: true, force: true }); });
+ await onCloud();
+ expect(world.running(), "the data folder's server, as a launch starts it").toBe(fx.desktopDataDir);
+ expect(world.clean!.active()).toBe(false);
+ expect(world.places.remembered(), "forgotten").toBeNull();
+ expect((await until(() => tiles(), (seen) => seen.length === 3, 30_000, "the rail without Spare")).map((tile) => [tile.id, tile.current]))
+ .toEqual([["profile:default", false], [`profile:${work}`, false], [cloudEntry, true]]);
+ await picture("10-after-restart-removed");
+ await click(`[data-rail-place="profile:${work}"]`);
+ await shown(`profile:${work}`, "Diary");
+ }, hostTimeout(360_000));
it("past eight tiles: ⋯ lists every place, a row opens its place and its right-click opens its menu", async () => {
for (const name of ["Lab", "Studio", "Garden", "Kitchen", "Travel", "Music"]) expect(world.profiles!.create({ name }).outcome).toBe("made");
diff --git a/src/components/HomeLine.test.ts b/src/components/HomeLine.test.ts
index 594a397383..0af64a5d6f 100644
--- a/src/components/HomeLine.test.ts
+++ b/src/components/HomeLine.test.ts
@@ -4,14 +4,18 @@ import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { setLocale } from "@/lib/i18n";
+import { HOME_LINE_NOTICE, homeLineShown, homeLineStage, localDay } from "@/lib/notices";
import { HomeLine, homeLineText } from "./HomeLine";
let host: HTMLDivElement;
let root: Root;
const place = vi.hoisted(() => ({ set: [] as Array<string | null> }));
-const ais = vi.hoisted(() => ({ instances: [] as unknown[] }));
+const ais = vi.hoisted(() => ({ instances: [] as unknown[], config: undefined as { onboarding: { hintsSeen: string[] } } | undefined, saved: [] as unknown[] }));
vi.mock("@/lib/notify", () => ({ setNotificationPlace: (name: string | null) => place.set.push(name) }));
-vi.mock("@/state/store", () => ({ useStore: () => ({ state: { instances: ais.instances } }) }));
+vi.mock("@/state/store", () => ({
+ useStore: () => ({ state: { instances: ais.instances, config: ais.config }, dispatch: () => {} }),
+ api: async (_path: string, init: { body: string }) => { ais.saved.push(JSON.parse(init.body)); return {}; },
+}));
vi.mock("@/components/onboarding/ConnectAi", () => ({ ConnectAiDialog: () => createElement("div", { "data-connect-ai": "" }) }));
vi.mock("@/components/EngineLibrary", () => ({ engineReady: (instance: { ready?: boolean }) => instance.ready === true }));
const mount = async (line: ReturnType<typeof vi.fn>, remote = false, state: Record<string, unknown> = { local: false, name: "My Cloud" }) => {
@@ -20,7 +24,7 @@ const mount = async (line: ReturnType<typeof vi.fn>, remote = false, state: Reco
await new Promise((resolve) => setTimeout(resolve, 0));
};
-beforeEach(() => { setLocale("en"); host = document.createElement("div"); document.body.append(host); root = createRoot(host); });
+beforeEach(() => { setLocale("en"); ais.config = { onboarding: { hintsSeen: [] } }; ais.saved.length = 0; host = document.createElement("div"); document.body.append(host); root = createRoot(host); });
afterEach(() => { flushSync(() => root.unmount()); host.remove(); delete window.ogb; });
it("says the one line main has for the next page, in plain words, and nothing when there is none", async () => {
@@ -100,3 +104,51 @@ it("in This Mac's own place, the line says it is separate from My Cloud, where t
it("in a workspace added from +, the line names it and says it is separate, with its own bots, chats and files", () => {
expect(homeLineText({ kind: "profile", name: "Work" }, "darwin")).toBe("Work starts fresh: a separate place on this computer, with its own bots, chats and files.");
});
+
+it("a workspace's line closes for good with its ✕, saved in that workspace's own config; connecting an AI stays offered while none is ready", async () => {
+ ais.instances = [{ ready: true, instanceId: "claude", driver: "claudeCode" }];
+ await mount(vi.fn().mockResolvedValue({ kind: "profile", name: "Work" }));
+ await vi.waitFor(() => expect(host.querySelector("[data-home-line='profile']")?.textContent).toContain("Work starts fresh"));
+ await vi.waitFor(() => expect(ais.saved).toEqual([{ onboarding: { hintsSeen: [`${HOME_LINE_NOTICE}:day-${localDay(Date.now())}`] } }]));
+ const close = host.querySelector<HTMLButtonElement>("[data-home-line-close]")!;
+ expect(close.getAttribute("aria-label")).toBe("Close");
+ flushSync(() => close.click());
+ expect(host.querySelector("[data-home-line]"), "gone at once").toBeNull();
+ expect(ais.saved.at(-1)).toEqual({ onboarding: { hintsSeen: [HOME_LINE_NOTICE] } });
+ flushSync(() => root.unmount()); root = createRoot(host);
+ ais.config = { onboarding: { hintsSeen: [HOME_LINE_NOTICE] } };
+ ais.instances = [{ ready: false, instanceId: "claude", driver: "claudeCode" }];
+ await mount(vi.fn().mockResolvedValue({ kind: "profile" }));
+ await vi.waitFor(() => expect(host.querySelector("[data-home-line-ai]")).not.toBeNull());
+ expect(host.querySelector("[data-home-line]")?.textContent, "closed: only the action is left").toBe("Connect an AI");
+ expect(host.querySelector("[data-home-line-close]")).toBeNull();
+});
+
+it("a workspace's line waits for its config, so one already closed never flashes; the clean workspace's line and a team's have no ✕", async () => {
+ ais.instances = [{ ready: true, instanceId: "claude", driver: "claudeCode" }];
+ ais.config = undefined;
+ await mount(vi.fn().mockResolvedValue({ kind: "profile" }));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(host.innerHTML).toBe("");
+ expect(ais.saved).toEqual([]);
+ for (const line of [{ kind: "clean" }, { kind: "left", name: "Acme" }]) {
+ flushSync(() => root.unmount()); root = createRoot(host);
+ await mount(vi.fn().mockResolvedValue(line));
+ await vi.waitFor(() => expect(host.querySelector("[data-home-line]")).not.toBeNull());
+ expect(host.querySelector("[data-home-line-close]"), line.kind).toBeNull();
+ }
+});
+
+it("a workspace's line goes by itself after it was shown on three days, or a week after the first, whichever comes first", () => {
+ const at = (day: string) => new Date(`${day}T10:00:00`).getTime();
+ const seen = (...days: string[]) => ({ completedAt: "", version: 1, reelSeen: false, hintsSeen: days.map((day) => `${HOME_LINE_NOTICE}:day-${day}`) });
+ expect(homeLineStage(seen(), at("2026-11-07"))).toBe("due");
+ expect(homeLineShown(seen(), at("2026-11-07"))).toEqual({ onboarding: { hintsSeen: [`${HOME_LINE_NOTICE}:day-2026-11-07`] } });
+ expect(homeLineShown(seen("2026-11-07"), at("2026-11-07")), "today counted already").toBeNull();
+ expect(homeLineStage(seen("2026-11-07", "2026-11-08", "2026-11-09"), at("2026-11-09")), "the third day itself").toBe("due");
+ expect(homeLineStage(seen("2026-11-07", "2026-11-08", "2026-11-09"), at("2026-11-10")), "a fourth day").toBe("done");
+ expect(homeLineShown(seen("2026-11-07", "2026-11-08", "2026-11-09"), at("2026-11-10"))).toBeNull();
+ expect(homeLineStage(seen("2026-11-07"), at("2026-11-13"))).toBe("due");
+ expect(homeLineStage(seen("2026-11-07"), at("2026-11-14")), "a week after the first").toBe("done");
+ expect(homeLineStage({ ...seen("2026-11-07"), hintsSeen: [HOME_LINE_NOTICE] }, at("2026-11-07")), "closed").toBe("done");
+});
diff --git a/src/components/HomeLine.tsx b/src/components/HomeLine.tsx
index c99a1f281b..34d2f47341 100644
--- a/src/components/HomeLine.tsx
+++ b/src/components/HomeLine.tsx
@@ -1,12 +1,14 @@
import { useEffect, useState } from "react";
-import { Cloud, Laptop, Users } from "lucide-react";
+import { Cloud, Laptop, Users, X } from "lucide-react";
import { freeFallback } from "../../shared/ai-ranking";
import { engineReady } from "@/components/EngineLibrary";
import { ConnectAiDialog } from "@/components/onboarding/ConnectAi";
import { t } from "@/lib/i18n";
+import { HOME_LINE_NOTICE, homeLineShown, homeLineStage } from "@/lib/notices";
+import { hintSeenPatch } from "@/lib/onboarding";
import { computerName } from "@/lib/places";
import { setNotificationPlace } from "@/lib/notify";
-import { useStore } from "@/state/store";
+import { api, useStore } from "@/state/store";
type Line = { kind: "left"; name: string } | { kind: "clean"; saved?: boolean } | { kind: "profile"; name?: string };
@@ -20,9 +22,7 @@ export function homeLineText(line: Line, platform?: string): string {
/** The clean workspace and a profile skip the new-user setup, so connecting an AI is offered here while none is ready. Nothing
* is sent to test one: nothing starts by itself in this workspace. */
function ConnectAiLink() {
- const { state } = useStore();
const [open, setOpen] = useState(false);
- if (state.instances.some((instance) => engineReady(instance) && !freeFallback(instance))) return null;
return <>
<button type="button" data-home-line-ai className="underline underline-offset-2 hover:text-ink" onClick={() => setOpen(true)}>{t("onboarding.meet.connectAi")}</button>
{open && <ConnectAiDialog tested={null} onClose={() => setOpen(false)} />}
@@ -33,10 +33,20 @@ function ConnectAiLink() {
* after a team dropped this person, that they are no longer in it. Nothing to press; it goes with the page. (Who can
* see a team's private chats is said in the chat itself, by the team's own page.) Or, for as long as the clean workspace
* runs (clean-workspace.mjs), that the person's bots are safe in their Cloud; Sign in stays in the You menu. In a profile, that
- * it is separate from My Cloud. */
+ * it is separate from My Cloud: words only, so its ✕ closes them for good in that workspace, and they go by themselves after
+ * a few days (homeLineStage); connecting an AI stays offered while none is ready. */
export function HomeLine() {
const bridge = !window.ogb?.remoteClient?.active ? window.ogb?.workspaces : undefined;
+ const { state, dispatch } = useStore();
const [line, setLine] = useState<Line | null>(null);
+ const [closed, setClosed] = useState(false);
+ const record = state.config?.onboarding;
+ const informational = line?.kind === "profile";
+ const stage = informational && record ? homeLineStage(record, Date.now()) : null;
+ const save = (patch: ReturnType<typeof homeLineShown>) => {
+ if (patch) void api("/api/config", { method: "PUT", body: JSON.stringify(patch) }).then((config) => dispatch({ type: "configStatus", config })).catch(() => {});
+ };
+ useEffect(() => { if (stage === "due") save(homeLineShown(record, Date.now())); }, [stage]);
useEffect(() => {
if (!bridge?.line) return;
// Served once: the first ask gets the line even when a strict-mode remount asks again (and gets null, which must
@@ -46,9 +56,17 @@ export function HomeLine() {
void bridge.state().then((place) => setNotificationPlace(place.role ? place.name : null)).catch(() => {});
}, [bridge]);
if (!line) return null;
- return <div role="status" data-home-line={line.kind} className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-hairline/40 bg-panel px-3 py-1.5 text-[13px] text-ink-secondary">
+ // Until this workspace's config says how often the words were shown, they wait, so a line already closed never flashes.
+ const words = !informational || (stage === "due" && !closed);
+ const aiMissing = line.kind !== "left" && !state.instances.some((instance) => engineReady(instance) && !freeFallback(instance));
+ if (!words && !aiMissing) return null;
+ return <div role="status" data-home-line={line.kind} className={`relative flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-hairline/40 bg-panel ${informational ? "px-8" : "px-3"} py-1.5 text-[13px] text-ink-secondary`}>
{line.kind === "clean" ? <Cloud size={14} aria-hidden="true" /> : line.kind === "profile" ? <Laptop size={14} aria-hidden="true" /> : <Users size={14} aria-hidden="true" />}
- <span dir="auto">{homeLineText(line, window.ogb?.platform)}</span>
- {line.kind !== "left" && <ConnectAiLink />}
+ {words && <span dir="auto">{homeLineText(line, window.ogb?.platform)}</span>}
+ {aiMissing && <ConnectAiLink />}
+ {informational && words && <button type="button" data-home-line-close aria-label={t("common.close")} title={t("common.close")}
+ className="absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 hover:bg-hairline/40 hover:text-ink" onClick={() => { setClosed(true); save(hintSeenPatch(record, HOME_LINE_NOTICE)); }}>
+ <X size={14} aria-hidden="true" />
+ </button>}
</div>;
}
diff --git a/src/lib/notices.ts b/src/lib/notices.ts
index 6a4325bfc5..e9278dd94d 100644
--- a/src/lib/notices.ts
+++ b/src/lib/notices.ts
@@ -124,6 +124,29 @@ export function introShown(record: OnboardingStatus | undefined, now: number): {
return hintSeenPatch(record, introDayHint(Math.min(Math.max(recordedDays(record) + 1, next.length), MAX_INTRO_DAYS)));
}
+/** The line atop a workspace of this computer's own: closed for good with its ✕, else shown on HOME_LINE_DAYS days at most
+ * and for HOME_LINE_SPAN_DAYS from the first. Kept in the workspace's own config, so each workspace has its own. */
+export const HOME_LINE_NOTICE = "home-line-profile";
+const HOME_LINE_DAYS = 3, HOME_LINE_SPAN_DAYS = 7;
+const homeLineDayHint = (day: string) => `${HOME_LINE_NOTICE}:day-${day}`;
+const homeLineDays = (record: OnboardingStatus | undefined) => (record?.hintsSeen ?? [])
+ .filter(id => id.startsWith(`${HOME_LINE_NOTICE}:day-`)).map(id => id.slice(`${HOME_LINE_NOTICE}:day-`.length))
+ .filter(day => /^\d{4}-\d{2}-\d{2}$/.test(day)).sort();
+const dayNumber = (day: string) => { const [year, month, date] = day.split("-").map(Number); return Math.round(new Date(year!, month! - 1, date!).getTime() / 86_400_000); };
+
+export function homeLineStage(record: OnboardingStatus | undefined, now: number): "due" | "done" {
+ if (hintSeen(record, HOME_LINE_NOTICE)) return "done";
+ const days = homeLineDays(record), today = localDay(now);
+ if (days.includes(today)) return "due";
+ if (days.length >= HOME_LINE_DAYS) return "done";
+ return days.length && dayNumber(today) - dayNumber(days[0]!) >= HOME_LINE_SPAN_DAYS ? "done" : "due";
+}
+
+/** Today counted among the line's days: the patch to save, or null when today is counted already or the line is done. */
+export function homeLineShown(record: OnboardingStatus | undefined, now: number): { onboarding: { hintsSeen: string[] } } | null {
+ return homeLineStage(record, now) === "due" ? hintSeenPatch(record, homeLineDayHint(localDay(now))) : null;
+}
+
export const LAUNCHED_AT = Date.now();
export function usedBefore(