A local-first multi-agent app development platform, built on PenguinHarness
fix(web): turning company mode on offers the mode, it does not switch to it (#781)
Yaowei Zheng5f165d5baa67
diff --git a/changelog/unreleased/2026-09-17-company-enable-stays-in-dev.md b/changelog/unreleased/2026-09-17-company-enable-stays-in-dev.mdnew file mode 100644index 00000000..6238c193--- /dev/null+++ b/changelog/unreleased/2026-09-17-company-enable-stays-in-dev.md@@ -0,0 +1,33 @@+# Turning company mode on offers the mode instead of switching to it++- **Date:** 2026-09-17+- **Type:** fix+- **Scope:** `web`+- **PR:** [#781](https://github.com/Prism-Shadow/penguin-harness/pull/781)++[中文版](2026-09-17-company-enable-stays-in-dev.zh.md)++Turning company mode on — the admin's **System settings → Server → Company mode** switch, or the+user's own switch under **System settings → General** — could put the shell straight into company+mode: the sidebar became the company sidebar while the main area stayed on the page it was showing,+often the new-chat page rather than the company landing. It happened whenever a company choice was+still stored from before the mode became unavailable, and a reload or another tab did the same.+Turning either switch on now only adds **Company** to the work-mode switch. The shell stays in+development mode on the current page, and the user enters company mode from the switch, which+opens the company landing as before.++## Details++- While company mode is unavailable — either switch off — the chosen work mode is development, in+ the Web App's store, the `penguin.workMode` localStorage mirror and the `workMode` preference+ alike. A company choice is written back as development when a switch is turned off in the app,+ when the app loads with a switch already off, and when preferences that hold it arrive while a+ switch is off. The organization last opened is kept, so a later switch to company mode still+ lands on it.+- The work mode becomes company only through the work-mode switch, the collapsed rail's+ company-mode button or an `/org` route, and only while company mode is available.+- Signing in on the login page adopted the user before `/api/me` had been read again, so the shell+ mounted for a moment on the flags from before the sign-in. The user is now adopted together with+ that answer, or on its own when the read fails — except on a 401, which says the session cookie+ never took, and the login page stays put instead of flashing a shell that has no session behind+ it. Signing in keeps a stored company choice.diff --git a/changelog/unreleased/2026-09-17-company-enable-stays-in-dev.zh.md b/changelog/unreleased/2026-09-17-company-enable-stays-in-dev.zh.mdnew file mode 100644index 00000000..2726700e--- /dev/null+++ b/changelog/unreleased/2026-09-17-company-enable-stays-in-dev.zh.md@@ -0,0 +1,26 @@+# 打开公司模式只提供该模式,不再直接切换过去++- **Date:** 2026-09-17+- **Type:** fix+- **Scope:** `web`+- **PR:** [#781](https://github.com/Prism-Shadow/penguin-harness/pull/781)++[English](2026-09-17-company-enable-stays-in-dev.md)++打开公司模式——管理员的**系统设置 → 服务器 → 公司模式**开关,或用户本人在**系统设置 → 通用**下的开关——+此前可能让界面直接进入公司模式:侧栏换成了公司模式的侧栏,主区域却停在原来的页面,常常是新建对话页,+而不是公司模式的落地页。只要该模式变为不可用之前存下的选择仍是公司模式,就会如此;刷新页面或另一个标签页+也一样。现在打开任一开关只会让工作模式切换中出现**公司**;界面停留在开发模式与当前页面,由用户从切换中+进入公司模式,并照旧打开公司模式的落地页。++## 细节++- 公司模式不可用(任一开关关闭)期间,所选工作模式一律为开发模式——Web App 的状态、localStorage 镜像+ `penguin.workMode` 与偏好 `workMode` 皆如此。在应用内关闭开关时、应用在开关已关闭的情况下加载时,以及+ 开关关闭期间载入的偏好中存有公司模式时,都会把该选择写回为开发模式。上次打开的组织保持不变,之后切到+ 公司模式仍会落在该组织。+- 工作模式只经由工作模式切换、收起栏中的公司模式按钮或 `/org` 路由变为公司模式,且只在公司模式可用时+ 生效。+- 在登录页登录时,此前会在重新读取 `/api/me` 之前就采用用户,界面因此先以登录前的标志挂载片刻。现在用户+ 与该响应一并采用,读取失败时单独采用;唯独 401 例外——它表示会话 Cookie 未能生效,此时停留在登录页,+ 而不会闪过一个背后并无会话的界面。登录后仍保留已存的公司模式选择。diff --git a/packages/web/src/features/settings/company-section.tsx b/packages/web/src/features/settings/company-section.tsxindex 46df0db8..8c40fa85 100644--- a/packages/web/src/features/settings/company-section.tsx+++ b/packages/web/src/features/settings/company-section.tsx@@ -5,10 +5,11 @@* rather than on; it stays disabled until the stored value arrives and again while a write is in* flight, so a second flip cannot race the first. Off stops the organization scheduler, 404s* every organization route and hides the mode switch for everyone; on again resumes without- * backfilling what was missed. A write that fails puts the switch back on the stored value and- * names the reason on a line under it (a toast would leave the switch and the message on- * separate surfaces). The auth context is refreshed afterwards because the shell reads the flag- * from /api/me, not from this page. The mode is a beta; the line under the switch says so+ * backfilling what was missed, and only brings the mode switch back — nobody's shell moves into+ * company mode by it (state/company.tsx). A write that fails puts the switch back on the stored+ * value and names the reason on a line under it (a toast would leave the switch and the message+ * on separate surfaces). The auth context is refreshed afterwards because the shell reads the+ * flag from /api/me, not from this page. The mode is a beta; the line under the switch says so* wherever the switch stands.*/import { useEffect, useState } from "react";diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsxindex 41ce92fb..483a9307 100644--- a/packages/web/src/state/auth.tsx+++ b/packages/web/src/state/auth.tsx@@ -26,6 +26,21 @@ const DEFAULT_UPLOAD_LIMITS: UploadLimits = {attachmentLimitMaxMb: 200,};+/**+ * A GET /api/me issued right after a successful login failed: does the session it was meant to+ * read still stand? A 401 is the one answer that says it does not — the login held, but the+ * session cookie never took (blocked cookies, a cross-site context, a proxy dropping+ * `Set-Cookie`), so there is no session to adopt a user onto, and the client's 401 handler has+ * already cleared the user. Any other failure (offline, a 5xx) leaves the session standing and+ * costs only the flags that read would have refreshed.+ *+ * Exported as a test seam: this package's vitest runs in node with no DOM, so the decision is+ * asserted by value rather than by mounting the Provider.+ */+export function loginSessionSurvives(error: unknown): boolean {+ return !(error instanceof ApiError && error.status === 401);+}+interface AuthContextValue {/** undefined = initializing; null = not logged in. */user: UserInfo | null | undefined;@@ -58,7 +73,7 @@ interface AuthContextValue {uploadLimits: UploadLimits;/*** Whether company mode is enabled server-wide (the admin master switch in server settings,- * default on). Off hides the work-mode switch for everyone and 404s every organization+ * default off). Off hides the work-mode switch for everyone and 404s every organization* route; the user's own preference (`UiPrefs.companyMode`) only hides the switch for them.*/companyMode: boolean;@@ -85,8 +100,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {const [desktopMode, setDesktopMode] = useState(false);const [sessionVia, setSessionVia] = useState<MeResponse["sessionVia"]>("password");const [uploadLimits, setUploadLimits] = useState<UploadLimits>(DEFAULT_UPLOAD_LIMITS);- // Off until /api/me says otherwise: the mode switch must not flash for a server that has- // turned company mode off, and the default on the server side is on anyway.+ // Off until /api/me says otherwise, as it is on a server nobody has turned it on: the mode+ // switch must not flash for a server that has company mode off.const [companyMode, setCompanyMode] = useState(false);// Any API returning 401 (session expired / database rebuilt) clears the current user, and@@ -143,7 +158,6 @@ export function AuthProvider({ children }: { children: ReactNode }) {const login = useCallback(async (userId: string, password: string) => {const res = await api.login({ userId, password });- setUser(res.user);// previewIsolated only rides on GET /api/me, and the mount-time fetch ran before// this session existed — without a refetch, a deployment with no separate preview// origin would keep the optimistic `true` after a UI login (navigation is@@ -151,6 +165,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {// preview path it can't actually serve. Never fail the login over it: the session// cookie is already set, so a transient /me error just leaves the default in place// until the next refresh.+ //+ // The user is adopted together with that answer, not before it: the shell mounts the+ // moment there is a user, and a shell mounted on the pre-login flags acts on them — the+ // company store reads an "off" master switch as its cue to put the chosen work mode+ // back to development, which would cost every UI login a company choice.try {const me = await api.getMe();setUser(me.user);@@ -159,8 +178,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {setSessionVia(me.sessionVia);setUploadLimits(me.uploadLimits);setCompanyMode(me.companyMode);- } catch {- // Login itself succeeded; keep the optimistic default.+ } catch (e) {+ // Login itself succeeded; adopt the user and keep the optimistic defaults — unless the+ // read came back 401, which says the session cookie never took. Adopting a user on a+ // session that does not exist would undo the 401 handler's setUser(null) in the same+ // continuation and mount the shell over a dead session.+ if (loginSessionSurvives(e)) setUser(res.user);}}, []);diff --git a/packages/web/src/state/company.tsx b/packages/web/src/state/company.tsxindex 7ebf7bd6..61acf98c 100644--- a/packages/web/src/state/company.tsx+++ b/packages/web/src/state/company.tsx@@ -9,6 +9,15 @@* Session's own page; organizations keep running regardless — the personal switch only hides the* user's own view of them.*+ * Turning a switch on only offers the mode: the mode switch appears, and the shell stays in+ * development on the page it is showing. The store holds that by keeping the chosen mode at+ * development while company mode is unavailable — a stored "company" is written back the moment+ * the store sees either switch off, whether the switch goes off in this tab, was already off at+ * load, or the preferences holding the choice arrive while it is. A choice kept through the off+ * spell would take effect when the switch comes back on, swapping in the company sidebar under+ * whatever page is open (the new-chat page, say) instead of the company landing. Company mode is+ * entered only by the user: the mode switch, or an `/org` route.+ ** Entering company mode is also where the shell says the mode is a beta: the first switch* into it in a browser raises the notice once (features/company/beta-badge.tsx keeps the* flag), which is why `setWorkMode` is the single handler both mode switches call.@@ -46,6 +55,7 @@ import type {OrgSessionsResponse,OrganizationSummary,ServerEvent,+ UiPrefs,} from "@prismshadow/penguin-server/api";import { useStore } from "zustand/react";import { createStore } from "zustand/vanilla";@@ -143,10 +153,11 @@ export interface CompanyVersions {}interface CompanyStoreState {+ /** The server's master switch (`MeResponse.companyMode`), as the auth context last read it. */+ serverEnabled: boolean;/** The user's own switch (`UiPrefs.companyMode`); on until the preferences say otherwise. */personalEnabled: boolean;- /** The preferences have been read once (before that the mirrors below stand in). */- prefsLoaded: boolean;+ /** The mode the user chose, held at development while company mode is unavailable (settleWorkMode). */workMode: WorkMode;/** `<projectId>/<orgId>` of the organization last opened, or null. */lastOrgKey: string | null;@@ -195,7 +206,9 @@ interface CompanyStoreState {versions: CompanyVersions;setWorkMode: (mode: WorkMode) => void;+ setServerEnabled: (enabled: boolean) => void;setPersonalEnabled: (enabled: boolean) => void;+ applyPrefs: (prefs: UiPrefs) => void;setCurrentOrg: (key: string | null) => void;reloadChannels: (projectId: string, orgId: string) => Promise<void>;markChannelRead: (channelId: string) => void;@@ -222,14 +235,48 @@ function counters(channels: readonly OrgChannelItem[]): {return { channelUnread: unread, channelMentions: mentions };}+/** Both switches on: the mode switch renders and `/org` routes resolve. */+export function companyModeAvailable(switches: {+ serverEnabled: boolean;+ personalEnabled: boolean;+}): boolean {+ return switches.serverEnabled && switches.personalEnabled;+}++/**+ * The mode the shell stands in: the chosen one while company mode is available, development+ * otherwise. The store writes the choice itself back to development as soon as it sees a switch+ * off (settleWorkMode); this covers the renders that come before it has, such as the first one+ * after a load that finds "company" in the localStorage mirror while the server's switch is off.+ */+export function effectiveWorkMode(state: {+ serverEnabled: boolean;+ personalEnabled: boolean;+ workMode: WorkMode;+}): WorkMode {+ return companyModeAvailable(state) ? state.workMode : "dev";+}++/**+ * Company mode is unavailable, so a company choice goes back to development in the store, the+ * localStorage mirror and the preference alike (setWorkMode writes all three). Level, not edge:+ * it runs whenever the store learns a switch's value, so a choice stored before the switch went+ * off, in a tab or a browser that never saw it go, is settled on the first load that sees it off.+ */+function settleWorkMode(state: CompanyStoreState): void {+ if (state.workMode === "company" && !companyModeAvailable(state)) state.setWorkMode("dev");+}+/*** Builds one Provider's store. Exported as a test seam: the package's vitest runs in Node* with no DOM, so the event routing below is exercised against the store directly.+ * `serverEnabled` seeds the server's master switch (the Provider passes the auth context's), so+ * the first render already knows whether company mode may be entered.*/-export function createCompanyStore() {+export function createCompanyStore(options: { serverEnabled?: boolean } = {}) {return createStore<CompanyStoreState>((set, get) => ({+ serverEnabled: options.serverEnabled ?? false,personalEnabled: true,- prefsLoaded: false,workMode: initialWorkMode(),lastOrgKey: initialLastOrgKey(),currentOrgKey: null,@@ -251,6 +298,9 @@ export function createCompanyStore() {setWorkMode: (mode) => {if (mode === get().workMode) return;+ // Company mode is entered only while it is available: a company choice written while a+ // switch is off would come into force the moment the switch comes back on.+ if (mode === "company" && !companyModeAvailable(get())) return;storeWorkMode(mode);set({ workMode: mode });// The mode is a beta, and this is the one place a person enters it: both switches and@@ -269,13 +319,45 @@ export function createCompanyStore() {void api.putPrefs({ workMode: mode }).catch(() => undefined);},+ /**+ * The server's master switch as /api/me last reported it. Seen off, the choice goes back+ * to development (settleWorkMode), so turning the switch on again offers company mode+ * instead of entering it.+ */+ setServerEnabled: (enabled) => {+ if (enabled !== get().serverEnabled) set({ serverEnabled: enabled });+ settleWorkMode(get());+ },+setPersonalEnabled: (enabled) => {set({ personalEnabled: enabled });- // Hiding company mode hides its shell with it (see setWorkMode).+ // Hiding company mode hides its shell with it (see setWorkMode), and takes it off the+ // user's choice: turning the switch back on offers the mode rather than entering it.if (!enabled) get().setCurrentOrg(null);+ settleWorkMode(get());void api.putPrefs({ companyMode: enabled }).catch(() => undefined);},+ /**+ * The stored preferences have arrived, and they win over the localStorage mirrors: the+ * user's switch, the mode and the organization last opened. A company choice among them+ * while company mode is unavailable is settled back to development (settleWorkMode) before+ * the mirror is written, so the mirror only ever holds the settled mode — a tab closed in+ * between must not leave the next load a choice this one has already refused.+ */+ applyPrefs: (prefs) => {+ const patch: Partial<CompanyStoreState> = {};+ if (prefs.companyMode === false) patch.personalEnabled = false;+ if (prefs.workMode === "company" || prefs.workMode === "dev") patch.workMode = prefs.workMode;+ if (typeof prefs.lastOrgKey === "string" && parseOrgKey(prefs.lastOrgKey) !== null) {+ patch.lastOrgKey = prefs.lastOrgKey;+ storeLastOrgKey(prefs.lastOrgKey);+ }+ set(patch);+ settleWorkMode(get());+ storeWorkMode(get().workMode);+ },+setCurrentOrg: (key) => {const prev = get();if (key === prev.currentOrgKey) return;@@ -602,14 +684,22 @@ interface CompanyContextValue {const CompanyContext = createContext<CompanyContextValue | null>(null);export function CompanyProvider({ children }: { children: ReactNode }) {- const { user, companyMode: serverEnabled } = useAuth();+ const { user, companyMode } = useAuth();const { projects, currentProject } = useProject();- const [store] = useState(createCompanyStore);+ const [store] = useState(() => createCompanyStore({ serverEnabled: companyMode }));const state = useStore(store);+ const { serverEnabled } = state;const userId = user?.userId ?? null;const currentProjectId = currentProject?.projectId ?? null;const projectIdsKey = projects.map((p) => p.projectId).join(",");+ // The server's master switch reaches the store on mount and on every later read of /api/me+ // (the admin's own flip refreshes it). Seen off, the store puts the chosen mode back to+ // development, which is what keeps turning the switch on from entering company mode.+ useEffect(() => {+ store.getState().setServerEnabled(companyMode);+ }, [store, companyMode]);+// Preferences: the stored switch, mode and last organization win over the localStorage// mirrors once they arrive. Read once per signed-in user.useEffect(() => {@@ -618,24 +708,10 @@ export function CompanyProvider({ children }: { children: ReactNode }) {void api.getPrefs().then((res) => {- if (cancelled) return;- const prefs = res.prefs;- const patch: Partial<CompanyStoreState> = { prefsLoaded: true };- if (prefs.companyMode === false) patch.personalEnabled = false;- if (prefs.workMode === "company" || prefs.workMode === "dev") {- patch.workMode = prefs.workMode;- storeWorkMode(prefs.workMode);- }- if (typeof prefs.lastOrgKey === "string" && parseOrgKey(prefs.lastOrgKey) !== null) {- patch.lastOrgKey = prefs.lastOrgKey;- storeLastOrgKey(prefs.lastOrgKey);- }- store.setState(patch);+ if (!cancelled) store.getState().applyPrefs(res.prefs);})- .catch(() => {- // Unreachable preferences leave the mirrors standing; nothing here is critical.- if (!cancelled) store.setState({ prefsLoaded: true });- });+ // Unreachable preferences leave the localStorage mirrors standing; nothing here is critical.+ .catch(() => undefined);return () => {cancelled = true;};@@ -716,7 +792,7 @@ export function CompanyProvider({ children }: { children: ReactNode }) {useEffect(() => subscribeCompanyResync(() => store.getState().resync()), [store]);const value = useMemo<CompanyContextValue>(() => {- const available = serverEnabled && state.personalEnabled;+ const available = companyModeAvailable(state);const shownKey = state.currentOrgKey ?? state.lastOrgKey;const shown = parseOrgKey(shownKey);const currentOrg =@@ -726,10 +802,10 @@ export function CompanyProvider({ children }: { children: ReactNode }) {(o) => o.projectId === shown.projectId && o.orgId === shown.orgId,) ?? null);return {- serverEnabled,+ serverEnabled: state.serverEnabled,personalEnabled: state.personalEnabled,available,- workMode: available ? state.workMode : "dev",+ workMode: effectiveWorkMode(state),setWorkMode: state.setWorkMode,setPersonalEnabled: state.setPersonalEnabled,organizations: state.organizations,@@ -768,7 +844,7 @@ export function CompanyProvider({ children }: { children: ReactNode }) {reloadOrgSessions: () =>currentProjectId === null ? Promise.resolve() : state.reloadOrgSessions(currentProjectId),};- }, [state, serverEnabled, projectIdsKey, currentProjectId]);+ }, [state, projectIdsKey, currentProjectId]);return <CompanyContext.Provider value={value}>{children}</CompanyContext.Provider>;}diff --git a/packages/web/test/company-work-mode.test.ts b/packages/web/test/company-work-mode.test.tsnew file mode 100644index 00000000..fe6c140b--- /dev/null+++ b/packages/web/test/company-work-mode.test.ts@@ -0,0 +1,194 @@+/**+ * The work mode the shell stands in across the two switches that make company mode available+ * (state/company.tsx). Turning a switch on offers company mode and never enters it — not even+ * when a company choice is still stored from before the switch went off, which is what used to+ * swap the company sidebar in under the new-chat page. Only the user's own move enters it.+ *+ * Driven against the store, with no React and no DOM: `setServerEnabled` is what the Provider+ * calls with every read of /api/me, and `applyPrefs` what it calls when the preferences arrive.+ * The localStorage mirror is an in-memory stand-in and the preference writes are recorded, so+ * each case says where the choice ends up as well as what the shell shows.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("../src/api/endpoints", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../src/api/endpoints")>()),+ putPrefs: vi.fn(() => Promise.resolve({ prefs: {} })),+}));++import * as api from "../src/api/endpoints";+import { BETA_NOTICE_KEY } from "../src/features/company/beta-badge";+import { WORK_MODE_KEY } from "../src/lib/work-mode";+import { companyModeAvailable, createCompanyStore, effectiveWorkMode } from "../src/state/company";++const putPrefs = vi.mocked(api.putPrefs);+let storage: Map<string, string>;+/**+ * Every value written to the work-mode mirror, in order. The end state is not the whole story:+ * a mode the mirror only passes through is a mode the next load finds if the tab closes in that+ * window, so a settled choice must never be written unsettled first.+ */+let modeWrites: string[];++beforeEach(() => {+ // The beta notice counts as shown, so entering company mode raises no toast here.+ storage = new Map([[BETA_NOTICE_KEY, "1"]]);+ modeWrites = [];+ vi.stubGlobal("localStorage", {+ getItem: (key: string) => storage.get(key) ?? null,+ setItem: (key: string, value: string) => {+ if (key === WORK_MODE_KEY) modeWrites.push(value);+ storage.set(key, value);+ },+ removeItem: (key: string) => void storage.delete(key),+ });+ putPrefs.mockClear();+});++afterEach(() => {+ vi.unstubAllGlobals();+});++type Store = ReturnType<typeof createCompanyStore>;++/** What the shell stands in: the mode switch's selection and the sidebar it draws. */+const shown = (store: Store) => effectiveWorkMode(store.getState());++/** Every work mode written to the user's preferences, in order. */+const writtenModes = () =>+ putPrefs.mock.calls.map(([body]) => body.workMode).filter((mode) => mode !== undefined);++describe("availability and the mode the shell stands in", () => {+ it("is available only with both switches on, and stands in development otherwise", () => {+ expect(companyModeAvailable({ serverEnabled: true, personalEnabled: true })).toBe(true);+ expect(companyModeAvailable({ serverEnabled: false, personalEnabled: true })).toBe(false);+ expect(companyModeAvailable({ serverEnabled: true, personalEnabled: false })).toBe(false);+ const company = { workMode: "company" as const };+ expect(effectiveWorkMode({ serverEnabled: true, personalEnabled: true, ...company })).toBe(+ "company",+ );+ expect(effectiveWorkMode({ serverEnabled: false, personalEnabled: true, ...company })).toBe(+ "dev",+ );+ expect(effectiveWorkMode({ serverEnabled: true, personalEnabled: false, ...company })).toBe(+ "dev",+ );+ });+});++describe("turning company mode on offers it and does not enter it", () => {+ it("stays in development when the server's switch comes on", () => {+ const store = createCompanyStore({ serverEnabled: false });+ store.getState().setServerEnabled(false);+ store.getState().setServerEnabled(true);+ expect(companyModeAvailable(store.getState())).toBe(true);+ expect(shown(store)).toBe("dev");+ expect(writtenModes()).toEqual([]);+ });++ it("writes a company choice found while the server's switch is off back as development, so the switch coming on does not apply it", () => {+ // The mirror still holds a choice made before the switch was turned off somewhere else.+ storage.set(WORK_MODE_KEY, "company");+ const store = createCompanyStore({ serverEnabled: false });+ // The first render, before the Provider's effect has reached the store.+ expect(shown(store)).toBe("dev");+ store.getState().setServerEnabled(false);+ expect(store.getState().workMode).toBe("dev");+ expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(writtenModes()).toEqual(["dev"]);++ store.getState().setServerEnabled(true);+ expect(shown(store)).toBe("dev");+ });++ it("puts the choice back to development when the server's switch goes off in a running app", () => {+ const store = createCompanyStore({ serverEnabled: true });+ store.getState().setWorkMode("company");+ store.getState().setCurrentOrg("p1/acme");+ store.getState().setServerEnabled(false);+ expect(store.getState().workMode).toBe("dev");+ expect(store.getState().currentOrgKey).toBeNull();+ // The organization last opened is not part of the choice: switching back still lands there.+ expect(store.getState().lastOrgKey).toBe("p1/acme");++ store.getState().setServerEnabled(true);+ expect(shown(store)).toBe("dev");+ expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(writtenModes()).toEqual(["company", "dev"]);+ });++ it("comes back in development when the user's own switch goes off and on again", () => {+ const store = createCompanyStore({ serverEnabled: true });+ store.getState().setWorkMode("company");+ store.getState().setPersonalEnabled(false);+ expect(shown(store)).toBe("dev");+ expect(store.getState().workMode).toBe("dev");++ store.getState().setPersonalEnabled(true);+ expect(shown(store)).toBe("dev");+ expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(putPrefs.mock.calls.map(([body]) => body)).toEqual([+ { workMode: "company" },+ { workMode: "dev" },+ { companyMode: false },+ { companyMode: true },+ ]);+ });+});++describe("the preferences as they arrive", () => {+ it("settle a company choice while the server's switch is off instead of adopting it", () => {+ const store = createCompanyStore({ serverEnabled: false });+ store.getState().setServerEnabled(false);+ store.getState().applyPrefs({ workMode: "company", lastOrgKey: "p1/acme" });+ expect(store.getState().workMode).toBe("dev");+ expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ // Never through "company" on the way: the mirror follows the settled mode, not the stored one.+ expect(modeWrites).not.toContain("company");+ expect(writtenModes()).toEqual(["dev"]);+ expect(store.getState().lastOrgKey).toBe("p1/acme");++ store.getState().setServerEnabled(true);+ expect(shown(store)).toBe("dev");+ });++ it("settle it too when they say the user's own switch is off", () => {+ const store = createCompanyStore({ serverEnabled: true });+ store.getState().applyPrefs({ workMode: "company", companyMode: false });+ expect(store.getState().personalEnabled).toBe(false);+ expect(store.getState().workMode).toBe("dev");+ expect(storage.get(WORK_MODE_KEY)).toBe("dev");+ expect(modeWrites).not.toContain("company");+ expect(writtenModes()).toEqual(["dev"]);++ store.getState().setPersonalEnabled(true);+ expect(shown(store)).toBe("dev");+ });++ it("keep a company choice while company mode stays available, so a reload stands where the user left it", () => {+ const store = createCompanyStore({ serverEnabled: true });+ store.getState().setServerEnabled(true);+ store.getState().applyPrefs({ workMode: "company" });+ expect(shown(store)).toBe("company");+ expect(storage.get(WORK_MODE_KEY)).toBe("company");+ // One write, and it is the choice itself: nothing was adopted and then taken back.+ expect(modeWrites).toEqual(["company"]);+ expect(writtenModes()).toEqual([]);+ });+});++describe("entering company mode", () => {+ it("is the user's own move, and only while company mode is available", () => {+ const store = createCompanyStore({ serverEnabled: false });+ store.getState().setWorkMode("company");+ expect(store.getState().workMode).toBe("dev");+ expect(writtenModes()).toEqual([]);++ store.getState().setServerEnabled(true);+ expect(shown(store)).toBe("dev");+ store.getState().setWorkMode("company");+ expect(shown(store)).toBe("company");+ expect(storage.get(WORK_MODE_KEY)).toBe("company");+ expect(writtenModes()).toEqual(["company"]);+ });+});diff --git a/packages/web/test/login-session.test.ts b/packages/web/test/login-session.test.tsnew file mode 100644index 00000000..093b6446--- /dev/null+++ b/packages/web/test/login-session.test.ts@@ -0,0 +1,36 @@+/**+ * Signing in on the login page reads GET /api/me before it adopts the user (state/auth.tsx), so+ * the shell never mounts on the flags from before the sign-in. That read can fail, and one+ * failure is unlike the others: a 401 says the session cookie never took — blocked cookies, a+ * cross-site context, a proxy dropping `Set-Cookie` — and api/client.ts has already cleared the+ * user over it. Adopting the login response's user there would put a dead session back in the+ * same continuation, navigate to /chat, let the shell write the work mode back locally, and only+ * bounce to /login on the next request.+ *+ * Tested by value: this package's vitest runs in node with no DOM, so the decision is a pure+ * function and the Provider's catch is the thin caller.+ */+import { describe, expect, it } from "vitest";+import { ApiError } from "../src/api/client";+import { loginSessionSurvives } from "../src/state/auth";++describe("a failed read of /api/me right after signing in", () => {+ it("leaves no user to adopt when it came back 401", () => {+ expect(loginSessionSurvives(new ApiError(401, "unauthorized", "Unauthorized"))).toBe(false);+ });++ it("leaves the session standing on every other failure, so the user is still adopted", () => {+ // The statuses api/client.ts can produce here: a network error, a server error, and a 403,+ // which is a refusal of the request rather than of the session.+ expect(loginSessionSurvives(new ApiError(0, "network_error", "Network error"))).toBe(true);+ expect(loginSessionSurvives(new ApiError(500, "http_error", "Server error"))).toBe(true);+ expect(loginSessionSurvives(new ApiError(403, "forbidden", "Forbidden"))).toBe(true);+ });++ it("leaves it standing for a throw that is not an ApiError at all", () => {+ expect(loginSessionSurvives(new TypeError("fetch failed"))).toBe(true);+ expect(loginSessionSurvives({ status: 401 })).toBe(true);+ expect(loginSessionSurvives("unauthorized")).toBe(true);+ expect(loginSessionSurvives(undefined)).toBe(true);+ });+});