Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 84 additions & 2 deletions e2e/team-session-states.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { expect, test, type Page } from "@playwright/test";
import { openApp, row, waitForIdle } from "./support/app";
import { ADMIN_INVITE, MEMBER_INVITE, joinTeam, menu, space, toast } from "./support/team";
import { ADMIN_INVITE, ADMIN_TEAM, MEMBER_INVITE, joinTeam, menu, space, toast } from "./support/team";

// A team profile's session after its browser closes (open.rs send_back): sent again until the
// server takes it, "Saving…" meanwhile with Start refused BUSY, kept here for the next start
Expand All @@ -24,7 +24,9 @@ type M = {
teamSessionResends: (id: string, why?: string) => void;
};
__shardxMockStartPayloads?: { id: string; extensions: string[]; bookmarks: string[] }[];
__TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record<string, unknown>) => Promise<unknown> };
__releaseTeamSessions?: () => void;
__releaseProcessList?: () => void;
__TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record<string, unknown>, options?: unknown) => Promise<unknown> };
};

const BUSY = "It’s still opening or being saved here. Start it again in a moment.";
Expand Down Expand Up @@ -83,6 +85,86 @@ test("a closed profile whose session is sent again says Saving…, waits to star
await expect(fb.getByRole("button", { name: "Start" })).not.toHaveAttribute("aria-disabled", "true");
});

test("a save from another team leaves the active team's matching profile saving", async ({ page }) => {
await inAdsTeam(page);
await joinTeam(page, ADMIN_INVITE.replace("ads.example.net", "growth.example.org"));
await expect(space(page)).toHaveText("Growth team");

// Both seed teams use this profile id. Only Growth is saving on this page.
const id = "tp-ads-1";
expect(await call(page, "launch", { profileId: id })).toBe("done");
await expect(status(page, "FB Ads 01")).toContainText("Running");
await resends(page, id);
await expect(status(page, "FB Ads 01")).toContainText("Saving…");

await page.evaluate(([team_id, profile_id]) => {
(window as unknown as M).__shardxMock.emit("team-session", {
team_id, profile_id, name: "Ads background profile", outcome: "saved",
});
}, [ADMIN_TEAM, id]);
await expect(toast(page, "“Ads background profile” saved to the team")).toBeVisible();
await expect(status(page, "FB Ads 01")).toContainText("Saving…");

await ends(page, id, "saved");
await expect(status(page, "FB Ads 01")).not.toContainText("Saving…");
});

test("a late open-session list does not carry Saving… into a same-team member rejoin", async ({ page }) => {
await inAdsTeam(page);
await page.evaluate((team_id) => {
const w = window as unknown as M;
const original = w.__TAURI_INTERNALS__.invoke.bind(w.__TAURI_INTERNALS__);
w.__TAURI_INTERNALS__.invoke = (cmd, args, options) => {
if (cmd !== "team_sessions" || w.__releaseTeamSessions) return original(cmd, args, options);
return new Promise((resolve) => {
w.__releaseTeamSessions = () => resolve([
{ team_id, profile_id: "tp-ads-1", name: "FB Ads 01", mine: false },
]);
});
};
w.__shardxMock.emit("launcher-warning", "FB Ads 01 closed, but the team server did not take its session: it is kept here and sent again until the server takes it (offline).");
}, ADMIN_TEAM);
await expect.poll(() => page.evaluate(() => Boolean((window as unknown as M).__releaseTeamSessions))).toBe(true);

const epoch = await page.evaluate(() => (window as unknown as M).__shardxMock.epoch);
await joinTeam(page, ADMIN_INVITE.replace(/#.*$/, "#stm_mock_dana"));
// The same team's edition does not change when this launcher joins as Dana.
expect(await page.evaluate(() => (window as unknown as M).__shardxMock.epoch)).toBe(epoch);
await expect(row(page, "FB Ads 01")).toBeVisible();
await page.evaluate(async () => {
(window as unknown as M).__releaseTeamSessions?.();
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
});
await expect(status(page, "FB Ads 01")).not.toContainText("Saving…");
});

test("rejoining as another member clears Running and ignores the old process list", async ({ page }) => {
await inAdsTeam(page, ["tp-ads-1"]);
await expect(status(page, "FB Ads 01")).toContainText("Running");
await page.evaluate(() => {
const w = window as unknown as M;
const original = w.__TAURI_INTERNALS__.invoke.bind(w.__TAURI_INTERNALS__);
const pending = new Promise<never>(() => undefined);
w.__TAURI_INTERNALS__.invoke = (cmd, args, options) => {
if (cmd !== "process_list") return original(cmd, args, options);
// Hold every fresh reply, so only a scope reset can clear the old row.
if (w.__releaseProcessList) return pending;
return new Promise((resolve) => {
w.__releaseProcessList = () => resolve([{ profile_id: "tp-ads-1", pid: 1234, uptime_ms: 100 }]);
});
};
});
await expect.poll(() => page.evaluate(() => Boolean((window as unknown as M).__releaseProcessList))).toBe(true);

await joinTeam(page, ADMIN_INVITE.replace(/#.*$/, "#stm_mock_dana"));
await expect(status(page, "FB Ads 01")).not.toContainText("Running");
await page.evaluate(async () => {
(window as unknown as M).__releaseProcessList?.();
await new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
});
await expect(status(page, "FB Ads 01")).not.toContainText("Running");
});

test("a Stop whose save takes a while shows Saving… until it is in", async ({ page }) => {
await page.addInitScript(() => { (window as unknown as { __shardxMockSessionSaveMs?: number }).__shardxMockSessionSaveMs = 2500; });
await inAdsTeam(page, ["tp-ads-2"]);
Expand Down
14 changes: 12 additions & 2 deletions src/entities/profile/lib/useProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { eachReporting, type EachResult } from "../../../shared/lib/eachReportin
import { t } from "../../../shared/i18n";
import { pendingProxyIds, proxyList, type ProxyEntry } from "../../proxy";
import { fingerprintList, type FingerprintEntry } from "../../fingerprint";
import { onWorkspaceChange } from "../../space";
import { trashRestore } from "../../trash/model/api";
import type { ProfileMeta, ProfileForm } from "../model/types";
import {
Expand Down Expand Up @@ -727,10 +728,19 @@ export const useProfile = create<ProfileStore>((set, get) => ({
// persisted total_runtime_ms — re-fetch so totals are current.
startProcessPolling: () => {
let cancelled = false;
let workspace = 0;
const offWorkspace = onWorkspaceChange((state, previous) => {
workspace++;
// A same-team rejoin can change members without the ordinary space reset.
if (previous && state?.epoch === previous.epoch) {
set({ running: {}, pending: {}, arrived: {}, startFailed: {}, failReasons: {} });
}
});
const tick = async () => {
const asked = workspace;
try {
const list = await processList();
if (cancelled) return;
if (cancelled || asked !== workspace) return;
const now = Date.now();
const prev = get().running;
const prevPending = get().pending;
Expand Down Expand Up @@ -768,7 +778,7 @@ export const useProfile = create<ProfileStore>((set, get) => ({
};
tick();
const handle = setInterval(tick, 2000);
return () => { cancelled = true; clearInterval(handle); };
return () => { cancelled = true; offWorkspace(); clearInterval(handle); };
},

rememberFolder: (f) => {
Expand Down
12 changes: 11 additions & 1 deletion src/entities/space/model/keys.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useSpace } from "./store";
import type { Space } from "./types";
import { activeTeam, type Space, type SpaceState } from "./types";

const suffix = (space: Space | undefined) => (space?.kind === "team" ? `@${space.team_id}` : "");

Expand All @@ -15,3 +15,13 @@ export function onSpaceChange(fn: () => void): () => void {
if (suffix(s.state?.space) !== suffix(prev.state?.space)) fn();
});
}

/** A new edition or a rejoin as another member of the same team. */
export function onWorkspaceChange(fn: (state: SpaceState | null, previous: SpaceState | null) => void): () => void {
return useSpace.subscribe(({ state }, previous) => {
const team = activeTeam(state);
const was = activeTeam(previous.state);
if (state?.epoch !== previous.state?.epoch || suffix(state?.space) !== suffix(previous.state?.space)
|| team?.member_id !== was?.member_id || team?.perm_key !== was?.perm_key) fn(state, previous.state);
});
}
34 changes: 20 additions & 14 deletions src/features/team-sessions/model/saving.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { listen } from "@tauri-apps/api/event";
import { onSpaceMoved } from "../../../shared/api/invoke";
import { TEAM_WARNINGS, warningRe } from "../../../shared/api/backendWarnings";
import { TEAM_REFUSALS } from "../../../shared/api/teamRefusals";
import { TEAM_SESSION, activeTeam, teamSessions, useSpace, type OpenSession, type SessionEnded } from "../../../entities/space";
import { TEAM_SESSION, activeTeam, onWorkspaceChange, teamSessions, useSpace, type OpenSession, type SessionEnded } from "../../../entities/space";
import { useProfile, useSaving } from "../../../entities/profile";

/** While any is saving, `team_sessions` is read again this often. */
Expand All @@ -21,6 +20,8 @@ let settling = false;
let settle: ReturnType<typeof setTimeout> | undefined;
/** Seen running here, then closed: listed after that, it is being saved. */
const closed = new Set<string>();
// Completion events prompt a read because the same profile may already be open again.
const ended = new Set<string>();
let again: ReturnType<typeof setTimeout> | undefined;

/** A session of the space in use: the team's own in a team, the synced ones in the personal space.
Expand All @@ -37,7 +38,9 @@ async function look(): Promise<void> {
if (mine !== seq) return;
const p = useProfile.getState();
const listed = new Set(open.filter(ofSpaceInUse).map((s) => s.profile_id));
for (const id of [...closed]) if (!listed.has(id)) closed.delete(id);
for (const id of closed) if (!listed.has(id)) closed.delete(id);
for (const id of ended) if (!listed.has(id)) clearBusyFailure(id);
ended.clear();
const ids = new Set([...listed].filter((id) =>
!p.running[id] && !p.startBusy.has(id) && p.pending[id]?.kind !== "start" && (first || closed.has(id))));
first = false;
Expand All @@ -46,18 +49,12 @@ async function look(): Promise<void> {
if (ids.size > 0) again = setTimeout(() => void look(), AGAIN_MS);
}

function drop(id: string) {
closed.delete(id);
// A start refused only because this send was under way did not fail: it may start now.
function clearBusyFailure(id: string) {
// A start refused only because this send was under way may start now.
const p = useProfile.getState();
if (p.startFailed[id] !== undefined && p.failReasons[id]?.includes(TEAM_REFUSALS.busy)) {
useProfile.setState({ startFailed: Object.fromEntries(Object.entries(p.startFailed).filter(([k]) => k !== id)) });
}
const ids = useSaving.getState().ids;
if (!ids.has(id)) return;
const next = new Set(ids);
next.delete(id);
useSaving.setState({ ids: next });
}

/** Follows closes, resends and their ends; returns the way to stop. */
Expand All @@ -78,13 +75,17 @@ export function watchSaving(): () => void {
for (const id of [...left, ...busy]) closed.add(id);
void look();
}));
// Every end of a team profile's session, saved or not, takes it off the list.
keep(listen<SessionEnded>(TEAM_SESSION, (e) => { if (e.payload?.profile_id) drop(e.payload.profile_id); }));
keep(listen<SessionEnded>(TEAM_SESSION, ({ payload }) => {
if (!payload?.profile_id || payload.team_id !== activeTeam(useSpace.getState().state)?.id) return;
ended.add(payload.profile_id);
void look();
}));
keep(listen<string>("launcher-warning", (e) => { if (typeof e.payload === "string" && RESENDING.test(e.payload)) void look(); }));
// Another space: read afresh once the running list is that space's.
offs.push(onSpaceMoved(() => {
offs.push(onWorkspaceChange(() => {
settling = true;
closed.clear();
ended.clear();
first = true;
seq++;
clearTimeout(again);
Expand All @@ -95,6 +96,11 @@ export function watchSaving(): () => void {
return () => {
gone = true;
wired = false;
seq++;
closed.clear();
ended.clear();
first = true;
settling = false;
clearTimeout(timer);
clearTimeout(again);
clearTimeout(settle);
Expand Down