Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

Console: stay signed in after a password change, and show a revoked session as signed out (CHOO-4224)

Simon Flack62c66d17f8a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7e24241e1..2d370ea7f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2824,6 +2824,14 @@ version of their own to them without also giving them a release of their own.
agent"; it was the only place Console showed that name.
#### Fixed
+- **Changing your password no longer signs Console out without a word.** The
+ server ends every session on a password change and hands the one that made
+ it a new session, which Console now keeps, so it stays signed in. The
+ account page says "Password changed successfully" in place of a toast. And
+ whenever a server ends Console's session (it expired, or was signed out from
+ elsewhere), Console re-checks its sign-in and shows the server as signed out
+ with a sign-in prompt, instead of "Chats offline" and a warning that its
+ rooms may be out of date.
- **Direct and group conversations no longer offer adding or removing
agents**, in a room's side column, the sidebar or an agent's "Add to rooms",
where the server refuses it now that their platform decides who is in them.
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts
index 9e4634c8b..afaaed15b 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.account.test.ts
@@ -1,17 +1,19 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const getSessionCookie = vi.hoisted(() => vi.fn());
+const setSessionCookie = vi.hoisted(() => vi.fn());
vi.mock('@main/core/managed-switch-server/managed-server-status', () => ({
managedServerHostBlocked: () => null,
managedServerStoppedPhase: () => null,
noteManagedServerUnanswered: () => undefined,
}));
-vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie: vi.fn() }));
+vi.mock('./servers-store', () => ({ getSessionCookie, setSessionCookie }));
vi.mock('./auth', () => ({
refreshSession: vi.fn(),
reauthenticateManagedServer: vi.fn(),
- extractAuthCookie: () => null,
+ extractAuthCookie: (setCookies: string[]) =>
+ setCookies.map((c) => /^switch_auth=([^;]*)/.exec(c)?.[1]).find(Boolean) ?? null,
}));
vi.mock('./console-identity', () => ({ consoleIdentityHeaders: async () => ({}) }));
@@ -23,6 +25,7 @@ const {
revealApiKey,
updateMyName,
} = await import('./gateway-client');
+const { onSessionEnded } = await import('./session-ended');
const SERVER = {
id: 'srv-1',
@@ -39,12 +42,12 @@ function makeJwt(secondsFromNow: number): string {
return `${header}.${payload}.sig`;
}
-function response(status: number, body: unknown): Response {
+function response(status: number, body: unknown, setCookies: string[] = []): Response {
return {
status,
ok: status < 400,
json: async () => body,
- headers: { get: () => null, getSetCookie: () => [] },
+ headers: { get: () => null, getSetCookie: () => setCookies },
text: async () => JSON.stringify(body),
} as unknown as Response;
}
@@ -108,6 +111,22 @@ describe('account', () => {
expect(lastCall().url).toMatch(/\/auth\/me\/password$/);
});
+ it('keeps the new session the server answers a password change with', async () => {
+ // The change ends every session, this one included; the cookie it sends
+ // back is the only one that still works, so it has to replace the old.
+ fetchMock.mockImplementation(async () =>
+ response(200, { ok: true }, ['switch_auth=fresh-session; HttpOnly; Path=/; SameSite=Lax'])
+ );
+ await changeMyPassword(SERVER, 'old-pass', 'new-password-1');
+ expect(setSessionCookie).toHaveBeenCalledWith('srv-1', 'fresh-session');
+ });
+
+ it('leaves the stored session alone when the server sends no new one', async () => {
+ fetchMock.mockImplementation(async () => response(200, { ok: true }));
+ await changeMyPassword(SERVER, 'old-pass', 'new-password-1');
+ expect(setSessionCookie).not.toHaveBeenCalled();
+ });
+
it('passes on the server’s reason when the current password is wrong', async () => {
fetchMock.mockImplementation(async () =>
response(403, { detail: 'Current password is incorrect' })
@@ -162,3 +181,29 @@ describe('API keys', () => {
expect(lastCall().url).toMatch(/\/api-keys\/k1$/);
});
});
+
+describe('a session the server has ended', () => {
+ it('says so when a signed-in call is refused with 401', async () => {
+ const ended: string[] = [];
+ const stop = onSessionEnded((serverId) => ended.push(serverId));
+ try {
+ fetchMock.mockImplementation(async () => response(401, { detail: 'Session ended' }));
+ await expect(updateMyName(SERVER, 'Ada')).rejects.toThrow();
+ expect(ended).toEqual(['srv-1']);
+ } finally {
+ stop();
+ }
+ });
+
+ it('says nothing for any other refusal', async () => {
+ const ended: string[] = [];
+ const stop = onSessionEnded((serverId) => ended.push(serverId));
+ try {
+ fetchMock.mockImplementation(async () => response(403, { detail: 'Forbidden' }));
+ await expect(updateMyName(SERVER, 'Ada')).rejects.toThrow();
+ expect(ended).toEqual([]);
+ } finally {
+ stop();
+ }
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
index 4a813b89d..82e5fe69c 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -136,6 +136,7 @@ import { extractAuthCookie, reauthenticateManagedServer, refreshSession } from '
import { consoleIdentityHeaders } from './console-identity';
import { NoManagementApiError } from './server-address';
import { getSessionCookie, setSessionCookie } from './servers-store';
+import { noteSessionEnded } from './session-ended';
/** The gateway management API is mounted under `/gateway` on the server. */
function gatewayUrl(server: SwitchServer, path: string): string {
@@ -426,6 +427,9 @@ export async function gatewayRequest(
}
if (response.status === 401) {
+ // Only a call that sent a session can say the session is gone; a 401 to an
+ // unauthenticated call is about something else.
+ if (options.authenticated) noteSessionEnded(server.id);
throw new GatewayError('unauthorized', 'Switch session expired — please sign in again.', 401);
}
if (answeredWithPage(response)) {
@@ -777,6 +781,11 @@ export async function updateMyName(server: SwitchServer, name: string): Promise<
* with the server's reason, such as a wrong current password. An account made
* through single sign-on has no password to change; the server says so on the
* user (`hasPassword`), and Settings offers no change for one.
+ *
+ * The server ends every session on a password change, the one that made it
+ * included, and answers with a new session cookie for this caller. Keeping it
+ * is what leaves Console signed in: the stored cookie is now refused. A server
+ * that sends none leaves the old one, and the next call finds it signed out.
*/
export async function changeMyPassword(
server: SwitchServer,
@@ -784,11 +793,13 @@ export async function changeMyPassword(
newPassword: string
): Promise<void> {
try {
- await gatewayFetch(server, '/auth/me/password', {
+ const res = await gatewayFetch(server, '/auth/me/password', {
authenticated: true,
method: 'PUT',
body: { current_password: currentPassword, new_password: newPassword },
});
+ const cookie = extractAuthCookie(res.headers.getSetCookie());
+ if (cookie) await setSessionCookie(server.id, cookie);
} catch (error) {
if (error instanceof GatewayError && error.detail) throw new Error(error.detail);
throw error;
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/session-ended-bridge.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/session-ended-bridge.ts
new file mode 100644
index 000000000..b81097163
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/session-ended-bridge.ts
@@ -0,0 +1,8 @@
+import { events } from '@main/lib/events';
+import { gatewaySessionEndedChannel } from '@shared/events/switchServerEvents';
+import { onSessionEnded } from './session-ended';
+
+/** Forward {@link onSessionEnded} to the window, which re-checks the server's sign-in. */
+export function bridgeSessionEndedToRenderer(): void {
+ onSessionEnded((serverId) => events.emit(gatewaySessionEndedChannel, { serverId }));
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/session-ended.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/session-ended.ts
new file mode 100644
index 000000000..8869e7c9b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/session-ended.ts
@@ -0,0 +1,24 @@
+/**
+ * Word that a signed-in gateway call was refused with 401, so whatever shows
+ * the server as signed in can check again.
+ *
+ * This is a hint, not a sign-out. Every 401 the gateway gives a session call
+ * means the session is gone, but a hint costs nothing to get wrong: the window
+ * answers it by asking `/auth/me` again, the same check that decides "signed
+ * in" everywhere else, so only a refusal there shows the signed-out state.
+ *
+ * Kept free of Electron so the gateway client and its tests can import it; the
+ * main process forwards it to the window ({@link bridgeSessionEndedToRenderer}).
+ */
+type Listener = (serverId: string) => void;
+
+const listeners = new Set<Listener>();
+
+export function onSessionEnded(listener: Listener): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function noteSessionEnded(serverId: string): void {
+ for (const listener of listeners) listener(serverId);
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/user-changes/user-changes.ts b/console/apps/switch-console-desktop/src/main/core/user-changes/user-changes.ts
index 31cacd32b..41b0e6db5 100644
--- a/console/apps/switch-console-desktop/src/main/core/user-changes/user-changes.ts
+++ b/console/apps/switch-console-desktop/src/main/core/user-changes/user-changes.ts
@@ -2,6 +2,7 @@ import {
gatewaySocketTarget,
type GatewaySocketTarget,
} from '@main/core/switch-servers/gateway-client';
+import { noteSessionEnded } from '@main/core/switch-servers/session-ended';
import {
withReachableServerWorkspaceSession,
withReachableWorkspaceSession,
@@ -38,6 +39,8 @@ const RESTART_WINDOW_MS = 2 * 60_000;
const RESTART_RETRY_MS = 5_000;
/** Pings missed before the socket is taken for dead and opened again. */
const MISSED_PINGS = 3;
+/** The gateway's close code for a session that expired or was ended (`gateway/changes.py`). */
+const SESSION_ENDED_CLOSE = 4401;
type Hello = { kinds: string[]; ping_interval_s: number };
@@ -129,6 +132,9 @@ class ServerSocket {
// A socket the watchdog already gave up on has been replaced or is
// waiting for its retry: its late close changes nothing.
if (this.socket !== socket) return;
+ // The gateway closes a socket whose session has expired or been ended
+ // with 4401: let the window check whether it is still signed in.
+ if (event.code === SESSION_ENDED_CLOSE) noteSessionEnded(this.serverId);
// A handshake that never opened, on a server that has never said hello,
// is most likely a server without the socket. One that has said hello
// is restarting or unreachable for now: keep trying at the usual pace.
diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.ts
index 6ed5d87e0..27d421a0b 100644
--- a/console/apps/switch-console-desktop/src/main/index.ts
+++ b/console/apps/switch-console-desktop/src/main/index.ts
@@ -41,6 +41,7 @@ import { appSettingsService } from './core/settings/settings-service';
import { sshConnectionManager } from './core/ssh/lifecycle/production-ssh-connection-manager';
import { autoSessionWatcher } from './core/switch-rooms/auto-session-watcher';
import { retireDashboardFallbacks } from './core/switch-servers/server-address';
+import { bridgeSessionEndedToRenderer } from './core/switch-servers/session-ended-bridge';
import { startActivationTracking } from './core/telemetry/activation';
import { currentInternalFlag } from './core/telemetry/internal-account';
import { readThisLaunch, reportLaunch } from './core/telemetry/launch-history';
@@ -226,6 +227,10 @@ void app.whenReady().then(async () => {
log.error('Could not check which servers still need a separate dashboard address:', error);
});
+ // A signed-in call refused with 401 tells the window to re-check that server's
+ // sign-in, so a revoked session reads as signed out rather than offline.
+ bridgeSessionEndedToRenderer();
+
// Each server's feature flags, read on a schedule so a redeploy that changes
// them reaches the window without a restart. Started once the managed stacks
// report themselves, for the same reason as the reconcile above.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/account-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/account-page.tsx
index c8f0dd9d7..822942fa3 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/account-page.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/account-page.tsx
@@ -1,5 +1,5 @@
import { useMutation } from '@tanstack/react-query';
-import { LogOut, Pencil, Trash2 } from 'lucide-react';
+import { CircleCheck, LogOut, Pencil, Trash2 } from 'lucide-react';
import { observer } from 'mobx-react-lite';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
@@ -8,6 +8,7 @@ import { PageHeader } from '@renderer/lib/components/page-header';
import { describeFailure } from '@renderer/lib/errors/describe-failure';
import { rpc } from '@renderer/lib/ipc';
import { useShowModal } from '@renderer/lib/modal/modal-provider';
+import { Alert, AlertTitle } from '@renderer/lib/ui/alert';
import { Button } from '@renderer/lib/ui/button';
import { Input } from '@renderer/lib/ui/input';
import { Label } from '@renderer/lib/ui/label';
@@ -170,8 +171,11 @@ function DisplayName({ serverId, name }: { serverId: string; name: string }) {
);
}
-function ChangePassword({ serverId }: { serverId: string }) {
+export function ChangePassword({ serverId }: { serverId: string }) {
const [open, setOpen] = useState(false);
+ // Said on the page rather than in a toast that can be missed, and held here
+ // only, so it is gone once the person navigates away and back.
+ const [changed, setChanged] = useState(false);
const [current, setCurrent] = useState('');
const [next, setNext] = useState('');
const [confirm, setConfirm] = useState('');
@@ -190,7 +194,7 @@ function ChangePassword({ serverId }: { serverId: string }) {
}),
onSuccess: () => {
reset();
- toast.success('Password changed');
+ setChanged(true);
},
onError: (error) => {
const { headline, detail } = describeFailure(error, 'Could not change your password.');
@@ -202,8 +206,21 @@ function ChangePassword({ serverId }: { serverId: string }) {
return (
<div className="space-y-1.5">
<Label>Password</Label>
+ {changed && (
+ <Alert className="max-w-md">
+ <CircleCheck className="text-foreground-success" />
+ <AlertTitle>Password changed successfully</AlertTitle>
+ </Alert>
+ )}
<div>
- <Button variant="outline" size="sm" onClick={() => setOpen(true)}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setChanged(false);
+ setOpen(true);
+ }}
+ >
Change password
</Button>
</div>
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
index 013cbf16f..20870a046 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.test.ts
@@ -297,6 +297,26 @@ describe('listed rooms', () => {
serversStore.isConnected = () => true;
});
+ it('asks for a sign-in, not a retry, once a session the server ended reads as signed out', async () => {
+ // A password change elsewhere revokes the session: the next room load is
+ // refused, then the server's status is re-checked and reads signed out.
+ // "Rooms may be out of date" with a Retry would be the wrong thing to say.
+ workspaces.activeId = 'ws-a';
+ listRooms.mockImplementation(async () => {
+ throw new Error('Switch session expired — please sign in again.');
+ });
+ const store = new SwitchRoomsStore();
+ await store.loadRoomNames();
+ expect(store.workspacesThatFailedToLoad.map((w) => w.name)).toEqual(['Alpha']);
+
+ serversStore.isConnected = (serverId: string) => serverId !== 'srv-a';
+ await store.loadRoomNames();
+
+ expect(store.workspacesNotSignedIn.map((w) => w.name)).toEqual(['Alpha']);
+ expect(store.workspacesThatFailedToLoad).toEqual([]);
+ serversStore.isConnected = () => true;
+ });
+
it('names the server to sign in to, not the workspace', async () => {
// The sidebar's "Sign in" link opens this server's page; handed the
// workspace id instead, it opened nothing.
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
index b49f2edfd..771b58715 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-rooms-store.ts
@@ -356,6 +356,13 @@ export class SwitchRoomsStore {
...this.unreachableWorkspaceIds.filter((id) => !askedIds.has(id)),
...asked.filter((w) => !switchServersStore.isConnected(w.serverId)).map((w) => w.id),
];
+ // A load that failed because the session had ended is the same fact as
+ // being signed out, which is said on its own; a retry cannot fix it.
+ for (const workspace of asked) {
+ if (serverAvailability(workspace.serverId) === 'signed-out') {
+ this.roomListErrors.delete(workspace.id);
+ }
+ }
});
await Promise.all(
connected.map(async (workspace) => {
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
index b7bf7f64d..008090ccc 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.test.ts
@@ -15,8 +15,9 @@ const oidcLogin = vi.hoisted(() => vi.fn());
/** SSH hosts the reachability manager currently considers down. */
const blockedHosts = vi.hoisted(() => new Set<string>());
+const eventsOn = vi.hoisted(() => vi.fn());
vi.mock('@renderer/lib/ipc', () => ({
- events: { on: vi.fn() },
+ events: { on: eventsOn },
rpc: {
switchServers: {
getAuthConfig,
@@ -68,7 +69,13 @@ vi.mock('@renderer/lib/stores/app-state', () => ({
appState: { navigation: { revalidate } },
}));
-const { SwitchServersStore } = await import('./switch-servers-store');
+const { SwitchServersStore, switchServersStore } = await import('./switch-servers-store');
+const { gatewaySessionEndedChannel } = await import('@shared/events/switchServerEvents');
+/** What the store does with word from the main process that a session ended,
+ * taken before `beforeEach` clears the record of it being subscribed. */
+const onSessionEnded = eventsOn.mock.calls.find(
+ ([channel]) => channel === gatewaySessionEndedChannel
+)?.[1] as ((payload: { serverId: string }) => void) | undefined;
/** Scope the window to a server, the way choosing one of its workspaces does. */
function selectServer(serverId: string | null): void {
@@ -753,3 +760,63 @@ describe('the error banner', () => {
expect(store.error).toBe('Invalid email or password');
});
});
+
+describe('a session the server has ended', () => {
+ const user = { id: 'u1', name: 'Ada', email: '[email protected]', role: 'user' } as never;
+
+ it('re-checks a signed-in server and shows it signed out once the check is refused', async () => {
+ const store = newStore([server('a')]);
+ getConnectionStatus.mockResolvedValueOnce({ serverId: 'a', connected: true, user });
+ await store.refreshStatus('a');
+ expect(store.isConnected('a')).toBe(true);
+
+ // The session was revoked (a password change elsewhere): `/auth/me` now refuses it.
+ getConnectionStatus.mockResolvedValueOnce({ serverId: 'a', connected: false, user: null });
+ await store.noteSessionEnded('a');
+
+ expect(store.isConnected('a')).toBe(false);
+ // Signed out, not unreachable: the sidebar asks for a sign-in rather than
+ // calling the rooms out of date or the server offline.
+ expect(store.isUnreachable('a')).toBe(false);
+ });
+
+ it('stays signed in when the re-check finds the session still good', async () => {
+ const store = newStore([server('a')]);
+ getConnectionStatus.mockResolvedValue({ serverId: 'a', connected: true, user });
+ await store.refreshStatus('a');
+ await store.noteSessionEnded('a');
+ expect(store.isConnected('a')).toBe(true);
+ });
+
+ it('does not re-check a server already signed out, so a refused re-check cannot loop', async () => {
+ const store = newStore([server('a')]);
+ await store.refreshStatus('a');
+ getConnectionStatus.mockClear();
+ await store.noteSessionEnded('a');
+ expect(getConnectionStatus).not.toHaveBeenCalled();
+ });
+
+ it('does not start a second check while one is running', async () => {
+ const store = newStore([server('a')]);
+ getConnectionStatus.mockResolvedValueOnce({ serverId: 'a', connected: true, user });
+ await store.refreshStatus('a');
+ const pending = deferred<unknown>();
+ getConnectionStatus.mockReturnValueOnce(pending.promise);
+ const first = store.noteSessionEnded('a');
+ await store.noteSessionEnded('a');
+ expect(getConnectionStatus).toHaveBeenCalledTimes(2);
+ pending.resolve({ serverId: 'a', connected: false, user: null });
+ await first;
+ });
+
+ it('listens for the main process saying so', async () => {
+ expect(onSessionEnded).toBeDefined();
+ switchServersStore.servers = [server('a')];
+ getConnectionStatus.mockResolvedValueOnce({ serverId: 'a', connected: true, user });
+ await switchServersStore.refreshStatus('a');
+ getConnectionStatus.mockResolvedValueOnce({ serverId: 'a', connected: false, user: null });
+ onSessionEnded!({ serverId: 'a' });
+ await flush();
+ expect(switchServersStore.isConnected('a')).toBe(false);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
index 6e8bca837..acdf59483 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/switch-servers-store.ts
@@ -2,7 +2,7 @@ import { makeAutoObservable, runInAction } from 'mobx';
import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';
import { workspacesStore } from '@renderer/features/workspaces/workspaces-store';
import { describeFailure, type FailureDescription } from '@renderer/lib/errors/describe-failure';
-import { rpc } from '@renderer/lib/ipc';
+import { events, rpc } from '@renderer/lib/ipc';
import { appState } from '@renderer/lib/stores/app-state';
import type { InviteServer } from '@shared/core/switch-servers/switch-cloud';
import type {
@@ -13,6 +13,7 @@ import type {
SwitchServer,
UpdateServerResult,
} from '@shared/core/switch-servers/switch-servers';
+import { gatewaySessionEndedChannel } from '@shared/events/switchServerEvents';
/**
* How long the first read of the server list may take before the window says so
@@ -345,6 +346,23 @@ export class SwitchServersStore {
await Promise.all([this.refreshStatus(serverId), this.ensureAuthConfig(serverId)]);
}
+ /**
+ * A signed-in call to this server was refused with 401. Re-read its status
+ * rather than signing out on the spot: `/auth/me` is what decides, so a
+ * session that has really gone reads as signed out — the sidebar asks for a
+ * sign-in instead of calling its rooms out of date and its chats offline —
+ * and a stray 401 costs one request and changes nothing.
+ *
+ * Only a server that reads as signed in is re-checked, and not while a check
+ * is already running. The re-check of a dead session is itself refused with
+ * 401 and says so again; once it has landed, the server no longer reads as
+ * signed in, so that echo ends here.
+ */
+ async noteSessionEnded(serverId: string): Promise<void> {
+ if (!this.isConnected(serverId) || this.refreshing.has(serverId)) return;
+ await this.refreshStatus(serverId);
+ }
+
async refreshStatus(serverId: string): Promise<void> {
runInAction(() => {
this.refreshing.add(serverId);
@@ -742,3 +760,7 @@ export class SwitchServersStore {
}
export const switchServersStore = new SwitchServersStore();
+
+events.on(gatewaySessionEndedChannel, ({ serverId }) => {
+ void switchServersStore.noteSessionEnded(serverId);
+});
diff --git a/console/apps/switch-console-desktop/src/renderer/tests/browser/change-password.test.tsx b/console/apps/switch-console-desktop/src/renderer/tests/browser/change-password.test.tsx
new file mode 100644
index 000000000..c4b8c3091
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/tests/browser/change-password.test.tsx
@@ -0,0 +1,117 @@
+/**
+ * Changing your password from Settings › Your account: success is said on the
+ * page, where the person just acted, and only until they leave it.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.hoisted(() => {
+ window.electronAPI ??= {
+ invoke: () => Promise.resolve(undefined),
+ eventOn: () => () => {},
+ eventSend: () => {},
+ } as unknown as typeof window.electronAPI;
+});
+
+const changeMyPassword = vi.hoisted(() => vi.fn());
+
+vi.mock('@renderer/lib/ipc', () => ({
+ events: { on: () => () => {} },
+ rpc: { switchServers: { changeMyPassword } },
+}));
+vi.mock('@renderer/features/switch-servers/switch-servers-store', () => ({
+ switchServersStore: {},
+}));
+
+import { ChangePassword } from '@renderer/features/settings/pages/account-page';
+import '@renderer/index.css';
+
+let container: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+afterEach(async () => {
+ await act(async () => root?.unmount());
+ container?.remove();
+ container = null;
+ root = null;
+ vi.clearAllMocks();
+});
+
+async function render() {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const client = new QueryClient({
+ defaultOptions: { mutations: { retry: false } },
+ });
+ await act(async () =>
+ root!.render(
+ <QueryClientProvider client={client}>
+ <ChangePassword serverId="srv-1" />
+ </QueryClientProvider>
+ )
+ );
+}
+
+function button(name: string): HTMLButtonElement {
+ const found = [...document.querySelectorAll('button')].find(
+ (each) => each.textContent?.trim() === name
+ );
+ if (!found) throw new Error(`no button ${name}`);
+ return found;
+}
+
+async function type(id: string, value: string) {
+ const input = document.getElementById(id) as HTMLInputElement;
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ await act(async () => {
+ setter.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+
+async function changePassword() {
+ await act(async () => button('Change password').click());
+ await type('account-current-password', 'old-password');
+ await type('account-new-password', 'new-password-1');
+ await type('account-confirm-password', 'new-password-1');
+ const submit = document.querySelector('button[type="submit"]') as HTMLButtonElement;
+ await act(async () => submit.click());
+}
+
+describe('ChangePassword', () => {
+ it('says the password changed on the page once the server accepts it', async () => {
+ changeMyPassword.mockResolvedValueOnce(undefined);
+ await render();
+ await changePassword();
+ expect(changeMyPassword).toHaveBeenCalledWith({
+ serverId: 'srv-1',
+ currentPassword: 'old-password',
+ newPassword: 'new-password-1',
+ });
+ expect(document.querySelector('[role="alert"]')?.textContent).toBe(
+ 'Password changed successfully'
+ );
+ });
+
+ it('does not carry the message over once the page is left and opened again', async () => {
+ changeMyPassword.mockResolvedValueOnce(undefined);
+ await render();
+ await changePassword();
+ expect(document.body.textContent).toContain('Password changed successfully');
+
+ await act(async () => root!.unmount());
+ container!.remove();
+ await render();
+ expect(document.body.textContent).not.toContain('Password changed successfully');
+ });
+
+ it('says nothing of success when the server refuses', async () => {
+ changeMyPassword.mockRejectedValueOnce(new Error('Current password is incorrect'));
+ await render();
+ await changePassword();
+ expect(document.body.textContent).not.toContain('Password changed successfully');
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/events/switchServerEvents.ts b/console/apps/switch-console-desktop/src/shared/events/switchServerEvents.ts
new file mode 100644
index 000000000..53d760bcd
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/shared/events/switchServerEvents.ts
@@ -0,0 +1,11 @@
+import { defineEvent } from '@shared/lib/ipc/events';
+
+/**
+ * A signed-in call to this server's gateway was refused with 401: its session
+ * may have expired or been revoked (a password change elsewhere, "sign out of
+ * all devices"). The window re-checks the server's sign-in rather than taking
+ * this as a sign-out on its own.
+ */
+export const gatewaySessionEndedChannel = defineEvent<{ serverId: string }>(
+ 'switch-servers:session-ended'
+);