Skip to content

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

Settings: answers to review

Simon Flack002757097892
diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
index 6f985d8fb..235c3b8f9 100644
--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/controller.ts
@@ -655,7 +655,7 @@ export const switchServersController = createRPCController({
if (server) trackEvent('server_sign_out', { server_kind: serverKindOf(server) });
},
- /** Change the signed-in person's display name; refreshes the signed-in status after. */
+ /** Change the signed-in person's display name, answering with the updated user. The caller re-reads the signed-in status (`refreshStatus`) so the new name shows everywhere. */
updateMyName: async (params: { serverId: string; name: string }): Promise<SwitchUser> => {
const server = await requireReachableServer(params.serverId);
return updateMyName(server, params.name);
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 40d8274d4..9e4634c8b 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
@@ -81,6 +81,23 @@ describe('account', () => {
expect(user.name).toBe('Ada Lovelace');
});
+ it('says when the account has no password of its own, and leaves it unsaid otherwise', async () => {
+ fetchMock.mockImplementation(async () =>
+ response(200, {
+ id: 'u1',
+ name: 'Ada',
+ email: '[email protected]',
+ role: 'user',
+ has_password: false,
+ })
+ );
+ expect((await updateMyName(SERVER, 'Ada')).hasPassword).toBe(false);
+ fetchMock.mockImplementation(async () =>
+ response(200, { id: 'u1', name: 'Ada', email: '[email protected]', role: 'user' })
+ );
+ expect(await updateMyName(SERVER, 'Ada')).not.toHaveProperty('hasPassword');
+ });
+
it('changes the password in the server’s field names', async () => {
fetchMock.mockImplementation(async () => response(200, { ok: true }));
await changeMyPassword(SERVER, 'old-pass', 'new-password-1');
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 a87edb030..ff49a030f 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
@@ -551,6 +551,7 @@ type UserResponseJson = {
email: string;
role: string;
server?: ServerDeclarationJson | null;
+ has_password?: boolean;
};
/**
@@ -575,6 +576,7 @@ function mapUser(json: UserResponseJson): SwitchUser {
email: json.email,
role: json.role,
server: mapServerDeclaration(json.server ?? null),
+ ...(json.has_password !== undefined ? { hasPassword: json.has_password } : {}),
};
}
@@ -626,8 +628,9 @@ export async function updateMyName(server: SwitchServer, name: string): Promise<
/**
* Change the signed-in person's password (`PUT /auth/me/password`). Refused
- * with the server's reason — a wrong current password, or an account that
- * signs in through single sign-on and so has none.
+ * 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.
*/
export async function changeMyPassword(
server: SwitchServer,
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 7ca00c765..c8f0dd9d7 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
@@ -24,7 +24,8 @@ export function AccountSettingsPage() {
description="Your profile in Switch, and how to leave it."
/>
<OnSignedInServer>
- {({ server, user }) => <Account server={server} user={user} />}
+ {/* Keyed on the server so a half-typed name never carries over to another one. */}
+ {({ server, user }) => <Account key={server.id} server={server} user={user} />}
</OnSignedInServer>
</div>
);
@@ -38,9 +39,11 @@ const Account = observer(function Account({
user: SwitchUser;
}) {
const showDeleteAccount = useShowModal('deleteAccountModal');
- // Whether this server signs people in with a password at all; one that uses
- // only single sign-on has no password of yours to change.
- const passwords = switchServersStore.authConfigFor(server.id)?.passwordLoginEnabled ?? false;
+ // Only a server that signs people in with a password, and only an account
+ // that has one: one made through single sign-on has no password to change.
+ const passwords =
+ (switchServersStore.authConfigFor(server.id)?.passwordLoginEnabled ?? false) &&
+ user.hasPassword !== false;
useEffect(() => {
void switchServersStore.ensureAuthConfig(server.id);
}, [server.id]);
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx
index d8ead2a94..95b73354e 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/pages/api-keys-page.tsx
@@ -15,7 +15,12 @@ import {
import { splitApiKeys } from './api-keys';
import { OnSignedInServer, SectionLabel } from './settings-server';
-export const apiKeysQueryKey = (serverId: string) => ['my-api-keys', serverId];
+/** Keyed on the person as well as the server, so one person's keys are never shown to the next to sign in. */
+export const apiKeysQueryKey = (serverId: string, userId: string) => [
+ 'my-api-keys',
+ serverId,
+ userId,
+];
/**
* Your keys on the server: the registration keys you made to register agents
@@ -30,19 +35,22 @@ export function ApiKeysSettingsPage() {
title="API keys"
description="Your keys: the ones you register agents with, and your agents' own."
/>
- <OnSignedInServer>{({ server }) => <ApiKeys serverId={server.id} />}</OnSignedInServer>
+ <OnSignedInServer>
+ {({ server, user }) => <ApiKeys serverId={server.id} userId={user.id} />}
+ </OnSignedInServer>
</div>
);
}
-function ApiKeys({ serverId }: { serverId: string }) {
+function ApiKeys({ serverId, userId }: { serverId: string; userId: string }) {
const queryClient = useQueryClient();
const keys = useQuery({
- queryKey: apiKeysQueryKey(serverId),
+ queryKey: apiKeysQueryKey(serverId, userId),
queryFn: () => rpc.switchServers.listMyApiKeys(serverId),
});
const [created, setCreated] = useState<CreatedRegistrationKey | null>(null);
- const refresh = () => void queryClient.invalidateQueries({ queryKey: apiKeysQueryKey(serverId) });
+ const refresh = () =>
+ void queryClient.invalidateQueries({ queryKey: apiKeysQueryKey(serverId, userId) });
if (keys.isLoading) {
return (
@@ -190,7 +198,8 @@ function KeyTable({
<thead>
<tr className="border-b border-border text-left text-xs text-foreground-muted">
<th className="px-3 py-2 font-normal">Label</th>
- <th className="px-3 py-2 font-normal">Key prefix</th>
+ {/* The start of the key's hash, not of the key: it tells keys apart without showing one. */}
+ <th className="px-3 py-2 font-normal">Fingerprint</th>
<th className="px-3 py-2 font-normal">Created</th>
<th className="px-3 py-2" />
</tr>
@@ -199,9 +208,7 @@ function KeyTable({
{keys.map((key) => (
<tr key={key.id} className="border-b border-border last:border-b-0">
<td className="px-3 py-2 text-foreground">{key.label}</td>
- <td className="px-3 py-2 font-mono text-xs text-foreground-muted">
- {key.keyPrefix}…
- </td>
+ <td className="px-3 py-2 font-mono text-xs text-foreground-muted">{key.keyPrefix}</td>
<td className="px-3 py-2 text-foreground-muted">{key.createdAt.slice(0, 10)}</td>
<td className="px-3 py-2">
<span className="flex items-center justify-end gap-1">
diff --git a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
index 493dabf65..548358e42 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/sidebar/workspace-nav.tsx
@@ -99,7 +99,9 @@ export const WorkspaceNav = observer(function WorkspaceNav() {
})}
<SidebarMenuButton
isActive={onSettings}
- onClick={() => navigate('settings')}
+ // A Switch this Console runs that is not answering is started from
+ // System status, so that is where Settings opens while it is down.
+ onClick={() => (frozen ? navigate('settings', { tab: 'status' }) : navigate('settings'))}
aria-label="Settings"
>
<Settings className="size-[15px] shrink-0" />
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx
index f5d052201..2afe59c39 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/lib/layout/workspace-layout.tsx
@@ -1,4 +1,3 @@
-import { detectPlatform } from '@tanstack/hotkeys';
import { type ReactNode } from 'react';
import { useDefaultLayout } from 'react-resizable-panels';
import { useWorkspaceLayoutContext } from '@renderer/lib/layout/layout-provider';
@@ -10,8 +9,6 @@ const LEFT_SIDEBAR_MIN_SIZE = '200px';
const LEFT_SIDEBAR_MAX_SIZE = '30%';
const MAIN_PANEL_MIN_SIZE = '30%';
-const isMac = detectPlatform() === 'mac';
-
interface WorkspaceLayoutProps {
leftSidebar: ReactNode;
mainContent: ReactNode;
@@ -29,7 +26,7 @@ interface WorkspaceLayoutProps {
/** Classes for the view and the persistent layer under the banner. */
contentClassName: string | undefined;
/** The strip across the top of the window, above the card: search and docs. */
- topBar?: ReactNode;
+ topBar: ReactNode;
}
export function WorkspaceLayout({
@@ -38,7 +35,7 @@ export function WorkspaceLayout({
persistentLayer = null,
banner,
contentClassName,
- topBar = null,
+ topBar,
}: WorkspaceLayoutProps) {
const { leftPanelRef, syncLeftOpenFromPanel, isLeftOpen } = useWorkspaceLayoutContext();
const { defaultLayout, onLayoutChanged } = useDefaultLayout({
@@ -92,10 +89,9 @@ export function WorkspaceLayout({
<div
className={cn(
'relative flex h-full w-full flex-col overflow-hidden pr-2 pb-2 [-webkit-app-region:drag]',
- isLeftOpen ? 'pl-px' : 'pl-2',
// The top bar is the gap above the card, and clears the macOS window
- // buttons itself; without one, the card keeps its own inset.
- topBar === null && (isLeftOpen ? 'pt-2' : isMac ? 'pt-9' : 'pt-2')
+ // buttons itself.
+ isLeftOpen ? 'pl-px' : 'pl-2'
)}
>
{topBar}
diff --git a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
index 3e1cc9a67..d7e5f8bd0 100644
--- a/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/switch-servers/switch-servers.ts
@@ -198,7 +198,6 @@ export type SwitchServerDeclaration = {
contracts: Record<string, { speaks: number; accepts: number }>;
};
-/** The authenticated user, as returned by `GET /gateway/auth/me`. */
/**
* One of the signed-in person's API keys (mirrors the gateway `ApiKeyDetail`).
* `type` is `registration` for a key they made to register agents with,
@@ -214,14 +213,20 @@ export type SwitchApiKey = {
createdAt: string;
};
-/** A registration key just made: the one time its full value is shown. */
+/** A registration key just made, with its full value. */
export type CreatedRegistrationKey = { id: string; label: string; key: string; createdAt: string };
+/** The authenticated user, as returned by `GET /gateway/auth/me`. */
export type SwitchUser = {
id: string;
name: string;
email: string;
role: string;
+ /**
+ * Whether the account has a password of its own to change: false for one
+ * made through single sign-on. Absent from a server that does not say.
+ */
+ hasPassword?: boolean;
/**
* What the server declared on this session response.
*
diff --git a/core/switch_core/chats/member_names.py b/core/switch_core/chats/member_names.py
new file mode 100644
index 000000000..697a261b1
--- /dev/null
+++ b/core/switch_core/chats/member_names.py
@@ -0,0 +1,33 @@
+"""Keeping a person's member clients named after them.
+
+A member client takes its display name from the person's `User.name` when
+it is created (`ChatsService.member_actor`), and the name is what other
+members see beside what the person writes. So when the person renames
+themselves, each of their member clients is renamed with them, in every
+workspace they can reach: one client per tenant, each behind that tenant's
+row-level security, so one tenant session at a time.
+"""
+
+from __future__ import annotations
+
+from sqlalchemy import update
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.chats import MEMBER_CLIENT_TYPE
+from switch_core.db.models import Client
+from switch_core.db.session_scope import tenant_session
+from switch_core.db.tenant_lookup import tenants_bindable_by_user
+
+
+async def rename_member_clients(
+ session_factory: async_sessionmaker[AsyncSession], user_id: str, name: str
+) -> None:
+ """Give every member client of `user_id` the display name `name`."""
+ for tenant_id in await tenants_bindable_by_user(session_factory, user_id):
+ async with tenant_session(session_factory, tenant_id) as session:
+ await session.execute(
+ update(Client)
+ .where(Client.user_id == user_id, Client.type == MEMBER_CLIENT_TYPE)
+ .values(display_name=name)
+ )
+ await session.commit()
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index a1264a28c..02eac1567 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -16,6 +16,7 @@ from switch_core.accounts.deletion import (
)
from switch_core.bridges.agent.protocol.agent_core import AgentCore
from switch_core.bridges.resource.service import ResourceService
+from switch_core.chats.member_names import rename_member_clients
from switch_core.clients.client_lifecycle_service import ClientLifecycleService
from switch_core.config import SwitchConfig
from switch_core.connections.broker import ServiceBroker, get_service_broker
@@ -117,6 +118,7 @@ def _session_response(user: User) -> SessionUserResponse:
email=user.email,
role=user.role,
created_at=str(user.created_at),
+ has_password=user.password_hash is not None,
server=_gateway_declaration(),
)
@@ -533,6 +535,9 @@ async def delete_my_account(
async def update_me(
req: UpdateMeRequest,
session: Annotated[AsyncSession, Depends(get_session)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
user: Annotated[User, Depends(get_current_user)],
) -> SessionUserResponse:
"""Change the signed-in person's display name.
@@ -543,6 +548,9 @@ async def update_me(
"""
user.name = req.name
await session.commit()
+ # The name other members see beside what this person writes in a
+ # Console chat is their member client's, copied when it was made.
+ await rename_member_clients(session_factory, user.id, req.name)
return _session_response(user)
diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.py
index 3c523a014..9ba4d74eb 100644
--- a/core/switch_core/gateway/schemas.py
+++ b/core/switch_core/gateway/schemas.py
@@ -1379,6 +1379,10 @@ class SessionUserResponse(UserResponse):
"""
server: ServerDeclaration
+ # Whether the account has a password of its own to change. False for one
+ # made through single sign-on, which signs in without one. Added later and
+ # defaulted, so the frozen authentication surface stays compatible.
+ has_password: bool = True
class SignupResponse(SessionUserResponse):
diff --git a/core/tests/switch_core/gateway/test_update_me.py b/core/tests/switch_core/gateway/test_update_me.py
index 207e4f9c9..47da06541 100644
--- a/core/tests/switch_core/gateway/test_update_me.py
+++ b/core/tests/switch_core/gateway/test_update_me.py
@@ -12,9 +12,12 @@ from types import SimpleNamespace
import httpx
from fastapi import FastAPI
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
-from switch_core.db.models import User
+from switch_core.chats import MEMBER_CLIENT_TYPE
+from switch_core.db.models import TENANT_ZERO_ID, Client, User
+from switch_core.db.session_scope import tenant_session
from switch_core.db.stores.user_store import UserStore
from switch_core.gateway import dependencies as gw_deps
from switch_core.gateway.auth import create_jwt
@@ -47,10 +50,12 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:
async def _seed_user(
- session_factory: async_sessionmaker[AsyncSession], email: str
+ session_factory: async_sessionmaker[AsyncSession],
+ email: str,
+ password_hash: str | None = None,
) -> str:
async with session_factory() as session:
- user = User(name="Ada", email=email, role="user", password_hash=None)
+ user = User(name="Ada", email=email, role="user", password_hash=password_hash)
await _USER_STORE.create(session, user)
await session.commit()
return user.id
@@ -112,3 +117,55 @@ async def test_signed_out_is_refused(
) as anonymous:
response = await anonymous.patch("/auth/me", json={"name": "Anyone"})
assert response.status_code == 401
+
+
+async def test_says_whether_the_account_has_a_password_of_its_own(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ sso_email = "[email protected]"
+ sso = await _seed_user(session_factory, sso_email)
+ pw_email = "[email protected]"
+ pw = await _seed_user(session_factory, pw_email, password_hash="not-a-real-hash")
+ app = _app(session_factory)
+
+ async with _client(app, sso, sso_email) as client:
+ sso_answer = await client.patch("/auth/me", json={"name": "Sso"})
+ async with _client(app, pw, pw_email) as client:
+ pw_answer = await client.patch("/auth/me", json={"name": "Pw"})
+
+ assert sso_answer.json()["has_password"] is False
+ assert pw_answer.json()["has_password"] is True
+
+
+async def test_renames_the_member_client_others_see_in_console_chats(
+ session_factory: async_sessionmaker[AsyncSession],
+) -> None:
+ email = "[email protected]"
+ user_id = await _seed_user(session_factory, email)
+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:
+ session.add(
+ Client(
+ tenant_id=TENANT_ZERO_ID,
+ transport_user_id=f"@switch-member-{user_id}:test",
+ display_name="Ada",
+ type=MEMBER_CLIENT_TYPE,
+ user_id=user_id,
+ )
+ )
+ await session.commit()
+
+ async with _client(_app(session_factory), user_id, email) as client:
+ response = await client.patch("/auth/me", json={"name": "Cy Young"})
+
+ assert response.status_code == 200, response.text
+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:
+ names = (
+ (
+ await session.execute(
+ select(Client.display_name).where(Client.user_id == user_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert names == ["Cy Young"]