From 7150b4a13142159a7386d608db9bd1bc5f3838b7 Mon Sep 17 00:00:00 2001 From: glwhappen <40719048+glwhappen@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:05:49 +0800 Subject: [PATCH] Keep team session status scoped to the active workspace --- e2e/team-session-states.spec.ts | 86 +++++++++++++++++++++- src/entities/profile/lib/useProfile.tsx | 14 +++- src/entities/space/model/keys.ts | 12 ++- src/features/team-sessions/model/saving.ts | 34 +++++---- 4 files changed, 127 insertions(+), 19 deletions(-) diff --git a/e2e/team-session-states.spec.ts b/e2e/team-session-states.spec.ts index d877737b6..fb43b55dc 100644 --- a/e2e/team-session-states.spec.ts +++ b/e2e/team-session-states.spec.ts @@ -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 @@ -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) => Promise }; + __releaseTeamSessions?: () => void; + __releaseProcessList?: () => void; + __TAURI_INTERNALS__: { invoke: (cmd: string, args?: Record, options?: unknown) => Promise }; }; const BUSY = "It’s still opening or being saved here. Start it again in a moment."; @@ -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((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(() => 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((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"]); diff --git a/src/entities/profile/lib/useProfile.tsx b/src/entities/profile/lib/useProfile.tsx index eeb3fd056..166e32937 100644 --- a/src/entities/profile/lib/useProfile.tsx +++ b/src/entities/profile/lib/useProfile.tsx @@ -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 { @@ -727,10 +728,19 @@ export const useProfile = create((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; @@ -768,7 +778,7 @@ export const useProfile = create((set, get) => ({ }; tick(); const handle = setInterval(tick, 2000); - return () => { cancelled = true; clearInterval(handle); }; + return () => { cancelled = true; offWorkspace(); clearInterval(handle); }; }, rememberFolder: (f) => { diff --git a/src/entities/space/model/keys.ts b/src/entities/space/model/keys.ts index 54b6dc1a9..a55010aed 100644 --- a/src/entities/space/model/keys.ts +++ b/src/entities/space/model/keys.ts @@ -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}` : ""); @@ -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); + }); +} diff --git a/src/features/team-sessions/model/saving.ts b/src/features/team-sessions/model/saving.ts index efaa14258..e52df1991 100644 --- a/src/features/team-sessions/model/saving.ts +++ b/src/features/team-sessions/model/saving.ts @@ -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. */ @@ -21,6 +20,8 @@ let settling = false; let settle: ReturnType | undefined; /** Seen running here, then closed: listed after that, it is being saved. */ const closed = new Set(); +// Completion events prompt a read because the same profile may already be open again. +const ended = new Set(); let again: ReturnType | undefined; /** A session of the space in use: the team's own in a team, the synced ones in the personal space. @@ -37,7 +38,9 @@ async function look(): Promise { 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; @@ -46,18 +49,12 @@ async function look(): Promise { 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. */ @@ -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(TEAM_SESSION, (e) => { if (e.payload?.profile_id) drop(e.payload.profile_id); })); + keep(listen(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("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); @@ -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);