Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

teams: find a team's chat even when its name differs in case

Lin (kwant bot)3ed20ea5fbb0
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 16a7e521..d3fb68fb 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -75,6 +75,7 @@ import { canRunNow } from './engines';
import { useEngines } from './useEngines';
import { claudeNeedsSignIn } from './claudeLogin';
import { personFetch } from './auth';
+import { teamChannelOf, teamOfChannel } from './teamChannel';
// Kwant and Tools editors are their own chunks. They stay mounted (rendering nothing while closed),
// so both load right after start-up and opening them never waits.
@@ -539,9 +540,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
selectedIdRef.current = init.id;
setIsChannel(true);
isChannelRef.current = true;
- const matchedTeam = normalizedTeams.find(
- (t) => `team-${t.name}` === init.name || t.id === init.id
- );
+ const matchedTeam = teamOfChannel(normalizedTeams, init);
setSelectedTeamId(matchedTeam ? matchedTeam.id : null);
}
} catch (err) {
@@ -857,9 +856,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const initialSpeakerName =
kwantsRef.current.find((k) => k.id === initialSpeakerId)?.name || initialSpeakerId;
- const matchedChannel = channelsRef.current.find(
- (c) => c.name === `team-${event.data?.team_name}` || c.id === teamId
- );
+ const matchedChannel = teamChannelOf(channelsRef.current, { id: teamId ?? '', name: event.data?.team_name ?? '' });
const contextId = matchedChannel ? matchedChannel.id : (teamId || selectedIdRef.current);
streamingContextIdRef.current = contextId;
@@ -1190,9 +1187,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setShowParallel(false);
setPhoneView('chat');
setSelectedTeamId(team.id);
- const targetChannel = channels.find(
- (c) => c.name === `team-${team.name}` || c.id === team.id
- );
+ const targetChannel = teamChannelOf(channels, team);
if (targetChannel) {
setSelectedId(targetChannel.id);
selectedIdRef.current = targetChannel.id;
@@ -1209,9 +1204,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
.then((r) => (r.ok ? r.json() : []))
.then((freshChannels: Channel[]) => {
setChannels(freshChannels);
- const match = freshChannels.find(
- (c) => c.name === `team-${team.name}` || c.id === team.id
- );
+ const match = teamChannelOf(freshChannels, team);
if (match) {
setSelectedId(match.id);
selectedIdRef.current = match.id;
@@ -1235,9 +1228,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
selectedIdRef.current = channel.id;
setIsChannel(true);
isChannelRef.current = true;
- const matchedTeam = teams.find(
- (t) => `team-${t.name}` === channel.name || t.id === channel.id
- );
+ const matchedTeam = teamOfChannel(teams, channel);
setSelectedTeamId(matchedTeam ? matchedTeam.id : null);
setMessages(messagesCacheRef.current[channel.id] || []);
playSfx('click');
@@ -1811,9 +1802,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
if (cRes.ok) {
const freshChannels: Channel[] = await cRes.json();
setChannels(freshChannels);
- const teamChan = freshChannels.find(
- (c) => c.name === `team-${created.name}` || c.id === created.id
- );
+ const teamChan = teamChannelOf(freshChannels, created);
if (teamChan) {
setSelectedId(teamChan.id);
selectedIdRef.current = teamChan.id;
@@ -1953,7 +1942,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const currentTeam = selectedTeamId
? teams.find((t) => t.id === selectedTeamId)
: isChannel && currentChannel?.name.startsWith('team-')
- ? teams.find((t) => `team-${t.name}` === currentChannel.name)
+ ? teamOfChannel(teams, currentChannel)
: null;
const activeSandboxId = currentTeam?.id || currentKwant?.id || selectedTeamId || (isChannel ? selectedId : 'default');
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index a6f8f96c..7a5d0a9c 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -11,6 +11,7 @@ import { SpaceSwitcher, SpaceTile } from './Spaces';
import { isMac } from './LayaStatus';
import { ApprovalsOffBadge } from './ApprovalsSetting';
import { approvalsOff, spaceOffLine } from '../approvalMode';
+import { teamChannelOf } from '../teamChannel';
export interface Kwant {
id: string;
@@ -184,7 +185,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
// Channels to display: hide auto-created team channels to avoid duplication with Teams section
const displayChannels = channels.filter(
- (c) => !teams.some((t) => c.name === `team-${t.name}`)
+ (c) => !teams.some((t) => teamChannelOf(channels, t)?.id === c.id)
);
const isTeamActive = (team: Team) => {
@@ -193,7 +194,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
}
return (
(isChannel && selectedId === team.id) ||
- channels.some((c) => c.id === selectedId && c.name === `team-${team.name}`)
+ (!!selectedId && teamChannelOf(channels, team)?.id === selectedId)
);
};
diff --git a/frontend/src/teamChannel.ts b/frontend/src/teamChannel.ts
new file mode 100644
index 00000000..e7377e62
--- /dev/null
+++ b/frontend/src/teamChannel.ts
@@ -0,0 +1,18 @@
+// A team's chat is the channel `team-<team name>`. A team renamed by an older version kept its chat
+// under the old name, so names also match ignoring (ASCII) case, as the server does; some events
+// carry the team's id where the chat's would be, so an id match counts too.
+
+type Named = { id: string; name: string };
+
+const fold = (s: string) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
+
+/** Whether channel `c` is team `t`'s chat. */
+export const isTeamChannel = (c: Named, t: Named) => c.id === t.id || fold(c.name) === fold(`team-${t.name}`);
+
+/** Team `t`'s chat among `channels`: an exact match first, else one that differs only in case. */
+export const teamChannelOf = <C extends Named>(channels: C[], t: Named): C | undefined =>
+ channels.find((c) => c.id === t.id || c.name === `team-${t.name}`) ?? channels.find((c) => isTeamChannel(c, t));
+
+/** The team whose chat channel `c` is, if any. */
+export const teamOfChannel = <T extends Named>(teams: T[], c: Named): T | undefined =>
+ teams.find((t) => t.id === c.id || c.name === `team-${t.name}`) ?? teams.find((t) => isTeamChannel(c, t));
diff --git a/frontend/tests/teamChannel.test.mjs b/frontend/tests/teamChannel.test.mjs
new file mode 100644
index 00000000..7bcfa834
--- /dev/null
+++ b/frontend/tests/teamChannel.test.mjs
@@ -0,0 +1,37 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const { isTeamChannel, teamChannelOf, teamOfChannel } = await loadBundled(`export * from './src/teamChannel';`);
+
+const startup = { id: 't1', name: 'startup' };
+const general = { id: 'c0', name: 'general' };
+const oldChat = { id: 'c1', name: 'team-Startup' };
+
+test('a chat left under a differently-cased name is still the team chat', () => {
+ // What Oleks saw: @startup in Teams, and its chat listed again as #team-Startup.
+ assert.equal(isTeamChannel(oldChat, startup), true);
+ assert.equal(teamChannelOf([general, oldChat], startup), oldChat);
+ assert.equal(teamOfChannel([startup], oldChat), startup);
+ assert.equal(isTeamChannel(general, startup), false);
+});
+
+test('an exact name wins over one that differs only in case', () => {
+ const exact = { id: 'c2', name: 'team-startup' };
+ assert.equal(teamChannelOf([oldChat, exact], startup), exact);
+ assert.equal(teamOfChannel([{ id: 't2', name: 'Startup' }, startup], exact), startup);
+});
+
+test('an id match counts, other teams do not', () => {
+ assert.equal(teamChannelOf([{ id: 't1', name: 'whatever' }], startup)?.id, 't1');
+ assert.equal(teamChannelOf([{ id: 'c3', name: 'team-startups' }], startup), undefined);
+ assert.equal(teamOfChannel([startup], { id: 'c4', name: 'team-other' }), undefined);
+});
+
+test('the sidebar hides every team chat and nothing else', async () => {
+ const src = (await import('node:fs')).readFileSync(new URL('../src/components/Sidebar.tsx', import.meta.url), 'utf8');
+ assert.match(src, /teamChannelOf\(channels, t\)\?\.id === c\.id/);
+ const channels = [general, oldChat, { id: 'c5', name: 'team-ghost' }];
+ const shown = channels.filter((c) => ![startup].some((t) => teamChannelOf(channels, t)?.id === c.id));
+ assert.deepEqual(shown.map((c) => c.name), ['general', 'team-ghost']);
+});
diff --git a/src/db/hires.rs b/src/db/hires.rs
index 818244e9..a9cfc278 100644
--- a/src/db/hires.rs
+++ b/src/db/hires.rs
@@ -404,11 +404,11 @@ impl Database {
let json = serde_json::to_string(&members)?;
let mut tx = self.pool.begin().await?;
sqlx::query("UPDATE teams SET member_kwants = ? WHERE id = ?").bind(&json).bind(team_id).execute(&mut *tx).await?;
- let channel: Option<(String, String)> = sqlx::query_as("SELECT id, member_kwants FROM channels WHERE name = ? AND space_id = ?")
- .bind(format!("team-{}", team.name))
- .bind(&team.space_id)
- .fetch_optional(&mut *tx)
- .await?;
+ let space = SpaceId::new(team.space_id.clone());
+ let channel: Option<(String, String)> = match super::team_channel_id(&mut *tx, &space, &team.name).await? {
+ Some(cid) => sqlx::query_as("SELECT id, member_kwants FROM channels WHERE id = ?").bind(cid).fetch_optional(&mut *tx).await?,
+ None => None,
+ };
if let Some((cid, raw)) = channel {
let mut cm: Vec<String> = serde_json::from_str(&raw).unwrap_or_default();
if !cm.iter().any(|m| m == kwant_id) {
diff --git a/src/db/imports.rs b/src/db/imports.rs
index 6cc0c6ba..9562758d 100644
--- a/src/db/imports.rs
+++ b/src/db/imports.rs
@@ -259,12 +259,7 @@ impl Database {
.await?;
created.teams.push(team_id);
let channel = format!("team-{name}");
- let (exists,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM channels WHERE space_id = ? AND name = ?")
- .bind(space.as_str())
- .bind(&channel)
- .fetch_one(&mut *tx)
- .await?;
- if exists == 0 {
+ if super::team_channel_id(&mut *tx, space, &name).await?.is_none() {
created.channels.push(insert_channel(&mut tx, space, &channel, None, &lead, &members_json).await?);
}
}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 3fab996f..8166c49d 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -637,6 +637,11 @@ impl Database {
self.get_team(id).await
}
+ /// The id of the team's chat (see [`team_channel_id`]).
+ pub async fn team_channel(&self, space: &SpaceId, team_name: &str) -> Result<Option<String>, DbError> {
+ team_channel_id(&self.pool, space, team_name).await
+ }
+
pub async fn delete_team(&self, id: &str) -> Result<bool, DbError> {
let res = sqlx::query("DELETE FROM teams WHERE id = ?")
.bind(id)
diff --git a/src/server/hires.rs b/src/server/hires.rs
index 52a6daa2..1d0902b5 100644
--- a/src/server/hires.rs
+++ b/src/server/hires.rs
@@ -672,8 +672,8 @@ async fn accept(state: &AppState, h: &Hire, auto: bool) -> Result<Hire, (StatusC
};
match state.db.create_team(&space, &new_team).await {
Ok(team) => {
- let channel = state.db.list_channels(&space).await.unwrap_or_default().into_iter().find(|c| c.name == format!("team-{}", team.name));
- made_team = Some(json!({"id": team.id, "name": team.name, "channel_id": channel.map(|c| c.id)}));
+ let channel = state.db.team_channel(&space, &team.name).await.ok().flatten();
+ made_team = Some(json!({"id": team.id, "name": team.name, "channel_id": channel}));
}
Err(e) => {
let _ = remove_made(state, &ids, None).await;
diff --git a/tests/team_channel_test.rs b/tests/team_channel_test.rs
index 426e13e3..dc9434cb 100644
--- a/tests/team_channel_test.rs
+++ b/tests/team_channel_test.rs
@@ -141,3 +141,22 @@ async fn startup_leaves_ambiguous_chats_alone() {
assert!(channel_named(&db, "team-DUP").await.is_some());
assert!(channel_named(&db, "team-dup").await.is_none(), "two candidates: neither is guessed at");
}
+
+#[tokio::test]
+async fn lookups_find_a_chat_that_differs_only_in_case() {
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let space = SpaceId::default_space();
+ let ks = db.list_kwants(&space).await.unwrap();
+ let (a, b) = (ks[0].id.clone(), ks[1].id.clone());
+ let t = db.create_team(&space, &team("Startup", &a, &[&a])).await.unwrap();
+ let chat = channel_named(&db, "team-Startup").await.unwrap();
+ // Renamed behind the running app's back, as an older version did.
+ rename_team_only(tmp.path(), "Startup", "startup", &serde_json::to_string(&[&a]).unwrap()).await;
+
+ assert_eq!(db.team_channel(&space, "startup").await.unwrap(), Some(chat.id.clone()));
+ assert!(db.add_team_member(&t.id, &b).await.unwrap());
+ let members: Vec<String> = serde_json::from_str(&channel_named(&db, "team-Startup").await.unwrap().member_kwants).unwrap();
+ assert!(members.contains(&b), "a new member joins the team's chat too");
+ assert_eq!(db.team_channel(&space, "nobody").await.unwrap(), None);
+}