From 342dd17b2723a086e43888d14c61eff05e4b8c03 Mon Sep 17 00:00:00 2001 From: Sami Fouad Date: Fri, 6 Nov 2026 19:19:42 -0600 Subject: [PATCH 1/2] Orgs: seats in a tree (5 levels), teams, workspaces in an org; channel access by org, team or member in the channel's history; an agent's place in its profile; 0.22.0 --- README.md | 18 +- package-lock.json | 4 +- package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/src/lib.rs | 96 +++++++- src-tauri/src/records.rs | 14 +- src-tauri/src/store.rs | 173 ++++++++++++--- src-tauri/src/store/org.rs | 441 +++++++++++++++++++++++++++++++++++++ src/app/Agents.tsx | 76 +++---- src/app/Org.tsx | 370 +++++++++++++++++++++++++++++++ src/app/Profile.tsx | 2 +- src/app/Settings.tsx | 7 +- src/app/globals.css | 55 +++++ src/app/page.tsx | 5 +- src/lib/core.ts | 21 +- tests/e2e/smoke.mjs | 35 +++ 17 files changed, 1231 insertions(+), 92 deletions(-) create mode 100644 src-tauri/src/store/org.rs create mode 100644 src/app/Org.tsx diff --git a/README.md b/README.md index 0d2aacd..8d82f70 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ as members with permissions. This is the desktop app. It works on its own computer today; the plan for everything after that is the design doc. -## What works (0.21.0) +## What works (0.22.0) - A workspaces home: create workspaces, open them. - Inside a workspace: channels, with the top third of each channel kept for @@ -29,7 +29,7 @@ everything after that is the design doc. anything else. 2. **Channels:** a switch per channel it can work in, saved as you flip it (the one you're in starts on). Agents see nothing else; finer - access is in a channel's **Access** button: *can read*, or *can read + access, and the org and team rules, are in a channel's **Access** button: *can read*, or *can read and change*. 3. **Done:** "Now write @intake in #student-intake and you're set." @@ -124,6 +124,20 @@ everything after that is the design doc. grants what an add-on asks to touch (Markdown: files matching `*.md`; off, it edits nothing) and shows which agents may use its tools. An agent's settings are a page in Settings, opened from the sidebar too. +- **Orgs.** Every workspace belongs to an org: Settings › *workspace* › + **Org** shows it as an outline of seats. A seat has a title, reports to + one other seat, and is held by you, an agent, or nobody yet (open). The + top seat leads it (you, as CEO, to start), and it goes at most five + levels deep. A seat and everyone under it is a *team*; moving a seat + moves its team. A channel's **Access** opens it to any of: everyone in + the org (new channels start that way), whole teams, and named members, + then lists who that comes to and why, with *can read* or *can read and + change* for each. An agent without a seat gets in only by name. Each + change is a commit in the channel's history. An agent's **Profile** + shows where it sits, up to the top, and its reports as @mentions that + open their profiles. Removing an agent leaves its seat open. Seats are + the groundwork for more people: someone who joins takes a seat, and the + team and channels under it are already theirs. - **Export.** *Export workspace* in the sidebar writes a folder to Documents/gild exports: each channel's chat as markdown and JSON lines, its table as CSV and JSON, its docs as markdown, its full history as a git repository you can clone, diff --git a/package-lock.json b/package-lock.json index 26efa3c..b889277 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gild-desktop", - "version": "0.21.0", + "version": "0.22.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gild-desktop", - "version": "0.21.0", + "version": "0.22.0", "license": "Apache-2.0", "dependencies": { "@tauri-apps/api": "^2.11.1", diff --git a/package.json b/package.json index e464579..8b131a4 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "gild-desktop", "private": true, - "version": "0.21.0", + "version": "0.22.0", "license": "Apache-2.0", "type": "module", "scripts": { diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 3bfd8c0..092643e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1919,7 +1919,7 @@ dependencies = [ [[package]] name = "gild-desktop" -version = "0.21.0" +version = "0.22.0" dependencies = [ "axum", "getrandom 0.3.4", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 09b0dee..5067cdb 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "gild-desktop" -version = "0.21.0" +version = "0.22.0" description = "gild: the open workspace where people and agents work together" license = "Apache-2.0" repository = "https://github.com/gildworkspaces/desktop" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bdb32db..7c6a5e7 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -15,7 +15,7 @@ use std::collections::BTreeMap; use clients::{ClientStatus, Clients, KINDS}; use records::{Access, Change, Doc, Record}; -use store::{Agent, AgentAccess, AgentInfo, AuditEntry, Channel, ChannelData, ChannelDocs, ChannelView, LoopRules, Message, Profile, Store, Workspace, Working}; +use store::{Agent, AgentAccess, AgentInfo, AuditEntry, Channel, ChannelData, ChannelDocs, ChannelView, Holder, LoopRules, Message, Org, Profile, Store, Workspace, Working}; use tauri::{Manager, State}; /// The one store, opened when the app starts. @@ -455,6 +455,90 @@ fn set_access(core: State, channel_id: String, agent_id: String, access: O }) } +/// Open a channel to its org, to teams in it, or neither. +#[tauri::command] +fn set_channel_rules(core: State, channel_id: String, org: bool, teams: Vec) -> Result, String> { + with(&core, |s| { + s.set_rules(&channel_id, &s.me()?, org, &teams)?; + s.channel_access(&channel_id) + }) +} + +/// Read or change for an agent that's in a channel, however it's in. +#[tauri::command] +fn set_level(core: State, channel_id: String, agent_id: String, access: Access) -> Result, String> { + with(&core, |s| { + s.set_level(&channel_id, &s.me()?, &agent_id, access)?; + s.channel_access(&channel_id) + }) +} + +/// The channel's org and team rules, as its history has them. +#[tauri::command] +fn channel_rules(core: State, channel_id: String) -> Result { + with(&core, |s| { + let acl = s.current_acl(&channel_id)?; + Ok(ChannelRules { org: acl.org, teams: acl.teams }) + }) +} + +#[derive(Serialize)] +struct ChannelRules { + org: bool, + teams: Vec, +} + +#[tauri::command] +fn orgs(core: State) -> Result, String> { + with(&core, |s| s.orgs()) +} + +#[tauri::command] +fn rename_org(core: State, org_id: String, name: String) -> Result, String> { + with(&core, |s| { + s.rename_org(&org_id, &name)?; + s.orgs() + }) +} + +#[tauri::command] +fn add_seat(core: State, parent_id: String, title: String) -> Result, String> { + with(&core, |s| { + s.add_seat(&parent_id, &title)?; + s.orgs() + }) +} + +#[tauri::command] +fn set_seat(core: State, seat_id: String, title: String, holder: Option) -> Result, String> { + with(&core, |s| { + s.set_seat(&seat_id, &title, holder)?; + s.orgs() + }) +} + +#[tauri::command] +fn move_seat(core: State, seat_id: String, parent_id: String) -> Result, String> { + with(&core, |s| { + s.move_seat(&seat_id, &parent_id)?; + s.orgs() + }) +} + +#[tauri::command] +fn remove_seat(core: State, seat_id: String) -> Result, String> { + with(&core, |s| { + s.remove_seat(&seat_id)?; + s.orgs() + }) +} + +/// You, as the holder of seats. +#[tauri::command] +fn me_id(core: State) -> Result { + with(&core, |s| s.me_id()) +} + #[tauri::command] fn activity(core: State, channel_id: String) -> Result, String> { with(&core, |s| s.activity(&channel_id)) @@ -570,6 +654,16 @@ pub fn run() { connect_agent, remove_agent, channel_access, + set_channel_rules, + set_level, + channel_rules, + orgs, + rename_org, + add_seat, + set_seat, + move_seat, + remove_seat, + me_id, set_access, activity, mcp_status, diff --git a/src-tauri/src/records.rs b/src-tauri/src/records.rs index 1810c64..479495d 100644 --- a/src-tauri/src/records.rs +++ b/src-tauri/src/records.rs @@ -4,7 +4,8 @@ //! //! In the repository: //! .gild/acl.json who besides the workspace's people may use -//! this channel: agent id → "read" | "write" +//! this channel: agent id → "read" | "write", +//! and the org and teams it's open to //! .gild/view.json the channel's view: columns and statuses //! .gild/records/.json one file per record, so two writers never //! touch the same file for different records @@ -36,9 +37,20 @@ pub enum Access { Write, } +/// Who may be in a channel: named agents, and, through the workspace's org, +/// everyone in it (`org`) or whole teams (`teams`: a seat and every seat +/// under it). `levels` sets read or change for a member who is in through +/// the org or a team (change when unset). Fields left at their default +/// aren't written, so a channel with only named agents keeps the file it had. #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] pub struct Acl { pub agents: std::collections::BTreeMap, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub org: bool, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub teams: Vec, + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + pub levels: std::collections::BTreeMap, } pub const RECORDS_DIR: &str = ".gild/records"; diff --git a/src-tauri/src/store.rs b/src-tauri/src/store.rs index 49b1336..08cb84e 100644 --- a/src-tauri/src/store.rs +++ b/src-tauri/src/store.rs @@ -23,6 +23,9 @@ use turso_core::{Connection, Database, PlatformIO, SqliteDialect, Value, IO}; use crate::records::{self, Access, Acl, Change, DiffLine, Doc, Record, View}; use sha2::{Digest, Sha256}; +mod org; +pub use org::{Holder, Org, Via}; + /// Bumped when a table's columns or meaning change. const FORMAT: i64 = 1; @@ -45,6 +48,10 @@ CREATE TABLE IF NOT EXISTS quiet_mentions (mention_id TEXT PRIMARY KEY); CREATE TABLE IF NOT EXISTS profile (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS coordinators (agent_id TEXT PRIMARY KEY); CREATE TABLE IF NOT EXISTS agent_everyone (agent_id TEXT PRIMARY KEY); +CREATE TABLE IF NOT EXISTS orgs (id TEXT PRIMARY KEY, name TEXT NOT NULL, created_at INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS org_workspaces (workspace_id TEXT PRIMARY KEY, org_id TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS seats (id TEXT PRIMARY KEY, org_id TEXT NOT NULL, parent_id TEXT, title TEXT NOT NULL, holder_kind TEXT, holder_id TEXT, created_at INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS channel_rules (channel_id TEXT NOT NULL, kind TEXT NOT NULL, value TEXT NOT NULL, access TEXT NOT NULL, PRIMARY KEY (channel_id, kind, value)); CREATE TABLE IF NOT EXISTS agent_profile (agent_id TEXT PRIMARY KEY, picture TEXT, prompt TEXT NOT NULL); CREATE TABLE IF NOT EXISTS agent_tools (agent_id TEXT NOT NULL, tool TEXT NOT NULL, allowed INTEGER NOT NULL, PRIMARY KEY (agent_id, tool)); CREATE TABLE IF NOT EXISTS addon_grants (addon_id TEXT NOT NULL, kind TEXT NOT NULL, value TEXT NOT NULL, granted INTEGER NOT NULL, PRIMARY KEY (addon_id, kind, value)); @@ -275,6 +282,7 @@ impl Store { Some(row) => return Err(format!("this database is format {}, and this gild reads format {FORMAT}", int(&row[0]))), } store.catch_up()?; + store.ensure_org()?; Ok(store) } @@ -348,6 +356,7 @@ impl Store { "INSERT INTO workspaces (id, name, created_at) VALUES (?1, ?2, ?3)", &[Value::from_text(id.clone()), Value::from_text(name.to_string()), Value::from_i64(at)], )?; + self.ensure_org()?; self.create_channel(&id, "general", "Anything for the whole workspace")?; self.workspaces()?.into_iter().find(|w| w.id == id).ok_or_else(|| "the new workspace was not saved".into()) } @@ -382,6 +391,12 @@ impl Store { Value::from_i64(channel.created_at), ], )?; + // A new channel is open to everyone in the workspace's org. + self.ensure_org()?; + if let Some(org) = self.channel_org(&channel.id)? { + let org_name = self.orgs()?.into_iter().find(|o| o.id == org).map(|o| o.name).unwrap_or_default(); + self.save_acl(&channel.id, &self.me()?, &format!("Open to everyone in {org_name}"), &Acl { org: true, ..Acl::default() })?; + } Ok(channel) } @@ -612,6 +627,7 @@ impl Store { &[id.clone(), Value::from_text(agent.clone()), Value::from_text(access.as_str().unwrap_or("read").to_string())], )?; } + self.index_rules(channel_id, &snap.acl)?; if let (Some(view), Some(commit)) = (&snap.view, &snap.commit) { let config = serde_json::to_string(view).map_err(|e| err("indexing the view", e))?; self.run( @@ -1037,6 +1053,8 @@ pub struct Agent { pub struct AgentAccess { pub agent: Agent, pub access: Option, + /// Why it's in: named, or through the org or a team. + pub via: Option, } #[derive(Serialize, Clone, Debug, PartialEq)] @@ -1125,6 +1143,8 @@ impl Store { for row in self.query("SELECT channel_id FROM grants WHERE agent_id = ?1", std::slice::from_ref(&id))? { self.set_access(&text(&row[0]), author, agent_id, None)?; } + // Its seat stays, open; with no seat it's in no channel through the org. + self.vacate(agent_id)?; self.run("DELETE FROM agent_wake WHERE agent_id = ?1", std::slice::from_ref(&id))?; self.run("DELETE FROM agent_context WHERE agent_id = ?1", std::slice::from_ref(&id))?; self.run("DELETE FROM coordinators WHERE agent_id = ?1", std::slice::from_ref(&id))?; @@ -1147,12 +1167,11 @@ impl Store { Ok(rows.first().map(|r| Agent { id: text(&r[0]), name: text(&r[1]), created_at: int(&r[2]) })) } + /// What an agent may do in a channel: named there, or in through its + /// seat in the org (see `reach`). Every check of an agent's access comes + /// through here. pub fn access(&self, agent_id: &str, channel_id: &str) -> Result, String> { - let rows = self.query( - "SELECT access FROM grants WHERE channel_id = ?1 AND agent_id = ?2", - &[Value::from_text(channel_id.to_string()), Value::from_text(agent_id.to_string())], - )?; - Ok(rows.first().and_then(|r| parse_access(&text(&r[0])))) + Ok(self.reach(agent_id, channel_id)?.map(|(a, _)| a)) } /// Refuse unless the agent has at least `need` in the channel. The answer @@ -1169,7 +1188,10 @@ impl Store { pub fn channel_access(&self, channel_id: &str) -> Result, String> { self.agents()? .into_iter() - .map(|agent| Ok(AgentAccess { access: self.access(&agent.id, channel_id)?, agent })) + .map(|agent| { + let reach = self.reach(&agent.id, channel_id)?; + Ok(AgentAccess { access: reach.as_ref().map(|(a, _)| *a), via: reach.map(|(_, v)| v), agent }) + }) .collect() } @@ -1178,12 +1200,7 @@ impl Store { pub fn set_access(&self, channel_id: &str, author: &str, agent_id: &str, access: Option) -> Result<(), String> { self.require_channel(channel_id)?; let agent = self.agents()?.into_iter().find(|a| a.id == agent_id).ok_or("That agent no longer exists.")?; - let mut acl = Acl::default(); - for row in self.query("SELECT agent_id, access FROM grants WHERE channel_id = ?1", &[Value::from_text(channel_id.to_string())])? { - if let Some(a) = parse_access(&text(&row[1])) { - acl.agents.insert(text(&row[0]), a); - } - } + let mut acl = self.current_acl(channel_id)?; if acl.agents.get(agent_id).copied() == access { return Ok(()); } @@ -1196,28 +1213,24 @@ impl Store { Some(a) => acl.agents.insert(agent_id.to_string(), a), None => acl.agents.remove(agent_id), }; - let bytes = serde_json::to_vec_pretty(&acl).map_err(|e| err("saving access", e))?; - self.write(channel_id, author, &message, &[(records::ACL_PATH.to_string(), bytes)]) + self.save_acl(channel_id, author, &message, &acl) } - /// The channels shared with an agent, with what it may do in each. + /// The channels an agent can be in, with what it may do in each. pub fn agent_channels(&self, agent: &Agent) -> Result, String> { let rows = self.query( - "SELECT w.name, c.id, c.workspace_id, c.name, c.topic, c.created_at, g.access - FROM grants g JOIN channels c ON c.id = g.channel_id JOIN workspaces w ON w.id = c.workspace_id - WHERE g.agent_id = ?1 ORDER BY w.created_at, c.created_at", - &[Value::from_text(agent.id.clone())], + "SELECT w.name, c.id, c.workspace_id, c.name, c.topic, c.created_at + FROM channels c JOIN workspaces w ON w.id = c.workspace_id ORDER BY w.created_at, c.created_at", + &[], )?; - Ok(rows - .iter() - .filter_map(|r| { - Some(AgentChannel { - workspace: text(&r[0]), - channel: Channel { id: text(&r[1]), workspace_id: text(&r[2]), name: text(&r[3]), topic: text(&r[4]), created_at: int(&r[5]) }, - access: parse_access(&text(&r[6]))?, - }) - }) - .collect()) + let mut out = Vec::new(); + for r in &rows { + let channel = Channel { id: text(&r[1]), workspace_id: text(&r[2]), name: text(&r[3]), topic: text(&r[4]), created_at: int(&r[5]) }; + if let Some(access) = self.access(&agent.id, &channel.id)? { + out.push(AgentChannel { workspace: text(&r[0]), channel, access }); + } + } + Ok(out) } pub fn channel(&self, channel_id: &str) -> Result, String> { @@ -1311,6 +1324,9 @@ impl Store { "INSERT INTO workspaces (id, name, created_at) VALUES (?1, ?2, ?3)", &[Value::from_text(ws_id.clone()), Value::from_text(name.to_string()), Value::from_i64(at)], )?; + // An imported workspace joins this computer's org; its channels keep + // the rules their history has (a team from another org matches no one). + self.ensure_org()?; for (i, c) in channels.into_iter().enumerate() { let id = new_id(); if let Some(h) = &c.history { @@ -2584,7 +2600,7 @@ mod tests { // Grants are commits, and they survive losing the index. store.set_access(&general.id, DEMO_NAME, &agent.id, Some(Access::Write)).unwrap(); let log: Vec = records::history(&dir, &general.id, records::ACL_PATH).unwrap().into_iter().map(|c| c.message).collect(); - assert_eq!(log, ["Let intake read and change this channel", "Let intake read this channel"]); + assert_eq!(log, ["Let intake read and change this channel", "Let intake read this channel", "Open to everyone in Demo's org"]); store.run("DELETE FROM grants", &[]).unwrap(); store.run("DELETE FROM indexed", &[]).unwrap(); drop(store); @@ -3056,6 +3072,103 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn an_org_is_a_tree_of_seats_and_channels_open_to_it_or_to_its_teams() { + let (dir, file) = temp(); + let store = Store::open(&file).unwrap(); + let ws = store.create_workspace("Addis").unwrap(); + let general = store.channels(&ws.id).unwrap()[0].clone(); + let org = store.orgs().unwrap().remove(0); + assert!(org.workspaces.contains(&ws.id), "a workspace belongs to an org"); + let top = org.seats[0].clone(); + assert_eq!((top.level, top.holder.clone()), (1, Some(Holder::Person(store.me_id().unwrap()))), "you lead it"); + + // Five levels: the top and four under it. + let vp = store.add_seat(&top.id, "VP Engineering").unwrap(); + let lead = store.add_seat(&vp, "p8 Runtime Project Lead").unwrap(); + let eng = store.add_seat(&lead, "p8 Runtime Engineering Lead").unwrap(); + let staff = store.add_seat(&eng, "p8 Runtime Staff").unwrap(); + assert!(store.add_seat(&staff, "Intern").unwrap_err().contains("level 5")); + let sales = store.add_seat(&top.id, "VP Sales").unwrap(); + let seats = store.seats(&org.id).unwrap(); + assert_eq!( + seats.iter().map(|s| (s.title.as_str(), s.level)).collect::>(), + [("CEO", 1), ("VP Engineering", 2), ("p8 Runtime Project Lead", 3), ("p8 Runtime Engineering Lead", 4), ("p8 Runtime Staff", 5), ("VP Sales", 2)], + "in outline order" + ); + assert_eq!(seats.iter().map(|s| s.team).collect::>(), [6, 4, 3, 2, 1, 1], "each seat's team, itself included"); + + let agent = |name: &str| store.create_agent(name).unwrap().0; + let (ava, kimi, codex, grok, lulu, stray) = (agent("ava"), agent("kimi"), agent("codex"), agent("grok"), agent("lulu"), agent("stray")); + for (seat, a, title) in [(&vp, &ava, "VP Engineering"), (&lead, &kimi, "p8 Runtime Project Lead"), (&eng, &codex, "p8 Runtime Engineering Lead"), (&staff, &grok, "p8 Runtime Staff")] { + store.set_seat(seat, title, Some(Holder::Agent(a.id.clone()))).unwrap(); + } + let assistant = store.add_seat(&sales, "Sales Assistant").unwrap(); + store.set_seat(&assistant, "Sales Assistant", Some(Holder::Agent(lulu.id.clone()))).unwrap(); + assert!(store.set_seat(&sales, "VP Sales", Some(Holder::Agent(ava.id.clone()))).unwrap_err().contains("ava already holds VP Engineering"), "one seat each"); + assert!(store.set_seat(&sales, "VP Sales", Some(Holder::Person("someone".into()))).is_err(), "only people in gild hold seats"); + + // A new channel is open to the org: every agent with a seat is in, + // one without isn't. + assert_eq!(store.reach(&ava.id, &general.id).unwrap(), Some((Access::Write, Via::Org))); + assert_eq!(store.access(&stray.id, &general.id).unwrap(), None); + assert!(store.agent_channels(&ava).unwrap().iter().any(|c| c.channel.id == general.id), "and its tools see it"); + + // A channel for one team: a seat and everyone under it. + let p8 = store.create_channel(&ws.id, "p8-runtime", "").unwrap(); + store.set_rules(&p8.id, DEMO_NAME, false, std::slice::from_ref(&lead)).unwrap(); + let team_of_lead = Some((Access::Write, Via::Team { seat: lead.clone() })); + for a in [&kimi, &codex, &grok] { + assert_eq!(store.reach(&a.id, &p8.id).unwrap(), team_of_lead, "{}", a.name); + } + assert_eq!(store.access(&ava.id, &p8.id).unwrap(), None, "above the team"); + assert_eq!(store.access(&lulu.id, &p8.id).unwrap(), None, "another team"); + // Named members, and read or change for anyone who's in. + store.set_access(&p8.id, DEMO_NAME, &lulu.id, Some(Access::Read)).unwrap(); + assert_eq!(store.reach(&lulu.id, &p8.id).unwrap(), Some((Access::Read, Via::Named))); + store.set_level(&p8.id, DEMO_NAME, &grok.id, Access::Read).unwrap(); + assert_eq!(store.reach(&grok.id, &p8.id).unwrap(), Some((Access::Read, Via::Team { seat: lead.clone() }))); + assert!(store.set_level(&p8.id, DEMO_NAME, &ava.id, Access::Read).is_err(), "only for someone who's in"); + assert!(store.set_rules(&p8.id, DEMO_NAME, false, &["nope".into()]).is_err()); + let log: Vec = records::history(&dir, &p8.id, records::ACL_PATH).unwrap().into_iter().map(|c| c.message).collect(); + assert_eq!(log, ["Let grok read this channel", "Let lulu read this channel", "Close to the rest of Demo's org; Open to p8 Runtime Project Lead's team", "Open to everyone in Demo's org"]); + + // The team follows the tree: a seat moves with everyone under it. + store.move_seat(&eng, &sales).unwrap(); + assert_eq!(store.access(&codex.id, &p8.id).unwrap(), None); + assert_eq!(store.access(&grok.id, &p8.id).unwrap(), None); + store.move_seat(&eng, &lead).unwrap(); + assert_eq!(store.reach(&grok.id, &p8.id).unwrap(), Some((Access::Read, Via::Team { seat: lead.clone() })), "back, with its level"); + assert!(store.move_seat(&vp, &staff).unwrap_err().contains("its own team")); + assert!(store.move_seat(&vp, &assistant).unwrap_err().contains("past level 5"), "VP Engineering's team is 4 deep"); + assert!(store.move_seat(&top.id, &sales).is_err(), "the top seat reports to no one"); + + // An open seat lets no one in; filling it does. + store.set_seat(&lead, "p8 Runtime Project Lead", None).unwrap(); + assert_eq!(store.access(&kimi.id, &p8.id).unwrap(), None); + store.set_seat(&lead, "p8 Runtime Project Lead", Some(Holder::Agent(stray.id.clone()))).unwrap(); + assert_eq!(store.reach(&stray.id, &p8.id).unwrap(), team_of_lead); + + // The rules are in the channel's history; the index is rebuilt from it. + store.run("DELETE FROM channel_rules", &[]).unwrap(); + store.run("DELETE FROM indexed", &[]).unwrap(); + drop(store); + let store = Store::open(&file).unwrap(); + assert_eq!(store.reach(&grok.id, &p8.id).unwrap(), Some((Access::Read, Via::Team { seat: lead.clone() }))); + assert_eq!(store.orgs().unwrap().len(), 1, "one org, kept"); + + // Removing a seat: its reports move up. Removing an agent opens its seat. + store.remove_seat(&eng).unwrap(); + assert_eq!(store.seats(&org.id).unwrap().iter().find(|s| s.id == staff).map(|s| (s.parent.clone(), s.level)), Some((Some(lead.clone()), 4))); + assert!(store.remove_seat(&top.id).is_err()); + store.remove_agent(&ava.id, DEMO_NAME).unwrap(); + assert_eq!(store.seats(&org.id).unwrap().iter().find(|s| s.id == vp).unwrap().holder, None); + store.rename_org(&org.id, "Addis Corp").unwrap(); + assert_eq!(store.orgs().unwrap()[0].name, "Addis Corp"); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn an_agent_s_profile_is_its_picture_and_its_prompt() { let (dir, file) = temp(); diff --git a/src-tauri/src/store/org.rs b/src-tauri/src/store/org.rs new file mode 100644 index 0000000..3998d1f --- /dev/null +++ b/src-tauri/src/store/org.rs @@ -0,0 +1,441 @@ +//! Orgs: who works with whom, as a tree of seats. +//! +//! A seat has a title and reports to one other seat; the top seat leads the +//! org. A seat is held by a person, an agent, or nobody yet (an open seat), +//! so everything that points at a seat keeps working when it's filled: a +//! person who joins later takes a seat and brings their agents as the team +//! under it. A team is a seat and every seat under it. The tree is at most +//! `MAX_LEVELS` deep, counting the top. +//! +//! Every workspace belongs to an org. A channel can be open to its +//! workspace's whole org, to teams in it, and to named agents (its +//! `.gild/acl.json`, so each change is a commit in the channel's history). + +use serde::{Deserialize, Serialize}; +use turso_core::Value; + +use super::{new_id, now_ms, parse_access, text, Store}; +use crate::records::{self, Access, Acl}; + +/// The top seat and four levels under it. +pub const MAX_LEVELS: usize = 5; +const MAX_TITLE: usize = 60; + +/// Who holds a seat. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] +#[serde(tag = "kind", content = "id", rename_all = "lowercase")] +pub enum Holder { + Person(String), + Agent(String), +} + +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct Seat { + pub id: String, + pub title: String, + /// The seat it reports to; none for the top seat. + pub parent: Option, + /// None: open, waiting for someone. + pub holder: Option, + /// 1 for the top seat. + pub level: usize, + /// How many seats its team has, itself included. + pub team: usize, +} + +#[derive(Serialize, Clone, Debug, PartialEq)] +pub struct Org { + pub id: String, + pub name: String, + /// The workspaces that belong to it. + pub workspaces: Vec, + /// In outline order: each seat, then its reports (oldest first). + pub seats: Vec, + /// How deep the tree may go (`MAX_LEVELS`), for the window. + pub max_levels: usize, +} + +/// Why an agent can be in a channel. +#[derive(Serialize, Clone, Debug, PartialEq)] +#[serde(tag = "kind", rename_all = "lowercase")] +pub enum Via { + /// Named in the channel's access. + Named, + /// It holds a seat in the org, and the channel is open to the org. + Org, + /// It's in the team under `seat`, which the channel is open to. + Team { seat: String }, +} + +/// A seat and the seats under it, from an outline. +pub fn team<'a>(seats: &'a [Seat], seat_id: &str) -> Vec<&'a Seat> { + let Some(start) = seats.iter().position(|s| s.id == seat_id) else { return Vec::new() }; + let level = seats[start].level; + let mut out = vec![&seats[start]]; + out.extend(seats[start + 1..].iter().take_while(|s| s.level > level)); + out +} + +fn title_ok(title: &str) -> Result { + let t = title.trim(); + if t.is_empty() || t.chars().count() > MAX_TITLE { + return Err(format!("A seat's title has 1 to {MAX_TITLE} characters.")); + } + Ok(t.to_string()) +} + +struct Row { + id: String, + parent: Option, + title: String, + holder: Option, +} + +fn holder(kind: &Value, id: &Value) -> Option { + match (text(kind).as_str(), text(id)) { + ("person", id) => Some(Holder::Person(id)), + ("agent", id) => Some(Holder::Agent(id)), + _ => None, + } +} + +fn holder_values(h: &Option) -> (Value, Value) { + match h { + Some(Holder::Person(id)) => (Value::from_text("person".to_string()), Value::from_text(id.clone())), + Some(Holder::Agent(id)) => (Value::from_text("agent".to_string()), Value::from_text(id.clone())), + None => (Value::Null, Value::Null), + } +} + +impl Store { + /// You, as a holder of seats. Made once, kept. + pub fn me_id(&self) -> Result { + if let Some(id) = self.setting("person_id")? { + return Ok(id); + } + let id = new_id(); + self.set_setting("person_id", Some(&id))?; + Ok(id) + } + + /// The first org, made with you leading it if there's none, and every + /// workspace not in an org put in it. + pub(crate) fn ensure_org(&self) -> Result { + let org = match self.query("SELECT id FROM orgs ORDER BY created_at, id LIMIT 1", &[])?.first() { + Some(r) => text(&r[0]), + None => { + let (id, at) = (new_id(), now_ms()); + self.run( + "INSERT INTO orgs (id, name, created_at) VALUES (?1, ?2, ?3)", + &[Value::from_text(id.clone()), Value::from_text(format!("{}'s org", self.me()?)), Value::from_i64(at)], + )?; + self.insert_seat(&id, None, "CEO", &Some(Holder::Person(self.me_id()?)))?; + id + } + }; + self.run( + "INSERT INTO org_workspaces (workspace_id, org_id) SELECT id, ?1 FROM workspaces WHERE id NOT IN (SELECT workspace_id FROM org_workspaces)", + &[Value::from_text(org.clone())], + )?; + Ok(org) + } + + fn insert_seat(&self, org_id: &str, parent: Option<&str>, title: &str, holder: &Option) -> Result { + let id = new_id(); + let (kind, who) = holder_values(holder); + self.run( + "INSERT INTO seats (id, org_id, parent_id, title, holder_kind, holder_id, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + &[ + Value::from_text(id.clone()), + Value::from_text(org_id.to_string()), + parent.map(|p| Value::from_text(p.to_string())).unwrap_or(Value::Null), + Value::from_text(title.to_string()), + kind, + who, + Value::from_i64(now_ms()), + ], + )?; + Ok(id) + } + + /// An org's seats, in outline order with their levels. + pub fn seats(&self, org_id: &str) -> Result, String> { + let rows: Vec = self + .query( + "SELECT id, parent_id, title, holder_kind, holder_id FROM seats WHERE org_id = ?1 ORDER BY created_at, id", + &[Value::from_text(org_id.to_string())], + )? + .iter() + .map(|r| Row { + id: text(&r[0]), + parent: match &r[1] { + Value::Null => None, + v => Some(text(v)), + }, + title: text(&r[2]), + holder: holder(&r[3], &r[4]), + }) + .collect(); + fn walk(rows: &[Row], parent: Option<&str>, level: usize, out: &mut Vec) { + for r in rows.iter().filter(|r| r.parent.as_deref() == parent) { + out.push(Seat { id: r.id.clone(), title: r.title.clone(), parent: r.parent.clone(), holder: r.holder.clone(), level, team: 1 }); + walk(rows, Some(&r.id), level + 1, out); + } + } + let mut out = Vec::new(); + walk(&rows, None, 1, &mut out); + let sizes: Vec = out.iter().map(|s| team(&out, &s.id).len()).collect(); + for (s, n) in out.iter_mut().zip(sizes) { + s.team = n; + } + Ok(out) + } + + /// Every org, with its workspaces and seats. + pub fn orgs(&self) -> Result, String> { + self.ensure_org()?; + self.query("SELECT id, name FROM orgs ORDER BY created_at, id", &[])? + .iter() + .map(|r| { + let id = text(&r[0]); + let workspaces = self + .query("SELECT workspace_id FROM org_workspaces WHERE org_id = ?1", &[Value::from_text(id.clone())])? + .iter() + .map(|w| text(&w[0])) + .collect(); + Ok(Org { seats: self.seats(&id)?, id, name: text(&r[1]), workspaces, max_levels: MAX_LEVELS }) + }) + .collect() + } + + fn seat_org(&self, seat_id: &str) -> Result { + self.query("SELECT org_id FROM seats WHERE id = ?1", &[Value::from_text(seat_id.to_string())])? + .first() + .map(|r| text(&r[0])) + .ok_or_else(|| "That seat no longer exists.".to_string()) + } + + /// The org a channel's workspace belongs to. + pub(crate) fn channel_org(&self, channel_id: &str) -> Result, String> { + Ok(self + .query( + "SELECT o.org_id FROM channels c JOIN org_workspaces o ON o.workspace_id = c.workspace_id WHERE c.id = ?1", + &[Value::from_text(channel_id.to_string())], + )? + .first() + .map(|r| text(&r[0]))) + } + + pub fn rename_org(&self, org_id: &str, name: &str) -> Result<(), String> { + let name = name.trim(); + if name.is_empty() || name.chars().count() > 60 { + return Err("An org's name has 1 to 60 characters.".into()); + } + if self.query("SELECT 1 FROM orgs WHERE id = ?1", &[Value::from_text(org_id.to_string())])?.is_empty() { + return Err("That org no longer exists.".into()); + } + self.run("UPDATE orgs SET name = ?1 WHERE id = ?2", &[Value::from_text(name.to_string()), Value::from_text(org_id.to_string())]) + } + + /// A new, open seat reporting to `parent_id`. + pub fn add_seat(&self, parent_id: &str, title: &str) -> Result { + let title = title_ok(title)?; + let org = self.seat_org(parent_id)?; + let seats = self.seats(&org)?; + let parent = seats.iter().find(|s| s.id == parent_id).ok_or("That seat no longer exists.")?; + if parent.level >= MAX_LEVELS { + return Err(format!("{} is on level {MAX_LEVELS}, the deepest an org goes, so it can't have reports.", parent.title)); + } + self.insert_seat(&org, Some(parent_id), &title, &None) + } + + /// A seat's title and who holds it (None: open). A person or agent holds + /// one seat in an org at most. + pub fn set_seat(&self, seat_id: &str, title: &str, holder: Option) -> Result<(), String> { + let title = title_ok(title)?; + let org = self.seat_org(seat_id)?; + let who = match &holder { + None => None, + Some(Holder::Agent(id)) => Some(self.agent(id)?.name), + Some(Holder::Person(id)) if *id == self.me_id()? => Some(self.me()?), + Some(Holder::Person(_)) => return Err("That person isn't in gild yet.".into()), + }; + if let (Some(who), Some(h)) = (who, &holder) { + if let Some(other) = self.seats(&org)?.iter().find(|s| s.id != seat_id && s.holder.as_ref() == Some(h)) { + return Err(format!("{who} already holds {}. Open that seat first.", other.title)); + } + } + let (kind, id) = holder_values(&holder); + self.run( + "UPDATE seats SET title = ?1, holder_kind = ?2, holder_id = ?3 WHERE id = ?4", + &[Value::from_text(title), kind, id, Value::from_text(seat_id.to_string())], + ) + } + + /// Have a seat, and its whole team with it, report to another seat. + pub fn move_seat(&self, seat_id: &str, parent_id: &str) -> Result<(), String> { + let org = self.seat_org(seat_id)?; + if self.seat_org(parent_id)? != org { + return Err("Seats can only move within their org.".into()); + } + let seats = self.seats(&org)?; + let moving = team(&seats, seat_id); + let seat = moving.first().ok_or("That seat no longer exists.")?; + if seat.parent.is_none() { + return Err("The top seat leads the org; it doesn't report to anyone.".into()); + } + if moving.iter().any(|s| s.id == parent_id) { + return Err(format!("{} can't report to a seat in its own team.", seat.title)); + } + let parent = seats.iter().find(|s| s.id == parent_id).ok_or("That seat no longer exists.")?; + let depth = moving.iter().map(|s| s.level - seat.level + 1).max().unwrap_or(1); + if parent.level + depth > MAX_LEVELS { + return Err(format!("Under {}, {}'s team would go past level {MAX_LEVELS}.", parent.title, seat.title)); + } + self.run("UPDATE seats SET parent_id = ?1 WHERE id = ?2", &[Value::from_text(parent_id.to_string()), Value::from_text(seat_id.to_string())]) + } + + /// Remove a seat; its reports report to its own parent instead. + pub fn remove_seat(&self, seat_id: &str) -> Result<(), String> { + let org = self.seat_org(seat_id)?; + let seats = self.seats(&org)?; + let seat = seats.iter().find(|s| s.id == seat_id).ok_or("That seat no longer exists.")?; + let Some(parent) = &seat.parent else { return Err("The top seat leads the org, so it stays.".into()) }; + let (p, id) = (Value::from_text(parent.clone()), Value::from_text(seat_id.to_string())); + self.run("UPDATE seats SET parent_id = ?1 WHERE parent_id = ?2", &[p, id.clone()])?; + self.run("DELETE FROM seats WHERE id = ?1", &[id]) + } + + /// An agent that's removed leaves its seat open. + pub(crate) fn vacate(&self, agent_id: &str) -> Result<(), String> { + self.run( + "UPDATE seats SET holder_kind = NULL, holder_id = NULL WHERE holder_kind = 'agent' AND holder_id = ?1", + &[Value::from_text(agent_id.to_string())], + ) + } + + /// The channel's access as its history has it now. + pub(crate) fn current_acl(&self, channel_id: &str) -> Result { + let id = Value::from_text(channel_id.to_string()); + let mut acl = Acl::default(); + for row in self.query("SELECT agent_id, access FROM grants WHERE channel_id = ?1", std::slice::from_ref(&id))? { + if let Some(a) = parse_access(&text(&row[1])) { + acl.agents.insert(text(&row[0]), a); + } + } + for row in self.query("SELECT kind, value, access FROM channel_rules WHERE channel_id = ?1 ORDER BY rowid", &[id])? { + match text(&row[0]).as_str() { + "org" => acl.org = true, + "team" => acl.teams.push(text(&row[1])), + "level" => { + if let Some(a) = parse_access(&text(&row[2])) { + acl.levels.insert(text(&row[1]), a); + } + } + _ => {} + } + } + Ok(acl) + } + + /// Index a channel's org and team rules from its history. + pub(crate) fn index_rules(&self, channel_id: &str, acl: &Acl) -> Result<(), String> { + let id = Value::from_text(channel_id.to_string()); + self.run("DELETE FROM channel_rules WHERE channel_id = ?1", std::slice::from_ref(&id))?; + let mut rows: Vec<(&str, String, &str)> = Vec::new(); + if acl.org { + rows.push(("org", String::new(), "")); + } + rows.extend(acl.teams.iter().map(|t| ("team", t.clone(), ""))); + rows.extend(acl.levels.iter().map(|(agent, a)| ("level", agent.clone(), if *a == Access::Write { "write" } else { "read" }))); + for (kind, value, access) in rows { + self.run( + "INSERT INTO channel_rules (channel_id, kind, value, access) VALUES (?1, ?2, ?3, ?4)", + &[id.clone(), Value::from_text(kind.to_string()), Value::from_text(value), Value::from_text(access.to_string())], + )?; + } + Ok(()) + } + + pub(crate) fn save_acl(&self, channel_id: &str, author: &str, message: &str, acl: &Acl) -> Result<(), String> { + let bytes = serde_json::to_vec_pretty(acl).map_err(|e| format!("saving access: {e}"))?; + self.write(channel_id, author, message, &[(records::ACL_PATH.to_string(), bytes)]) + } + + /// What an agent may do in a channel, and why: named there, or in + /// through the org or a team. Named access wins. + pub fn reach(&self, agent_id: &str, channel_id: &str) -> Result, String> { + let acl = self.current_acl(channel_id)?; + if let Some(a) = acl.agents.get(agent_id) { + return Ok(Some((*a, Via::Named))); + } + if !acl.org && acl.teams.is_empty() { + return Ok(None); + } + let Some(org) = self.channel_org(channel_id)? else { return Ok(None) }; + let seats = self.seats(&org)?; + let me = Holder::Agent(agent_id.to_string()); + let Some(mine) = seats.iter().find(|s| s.holder.as_ref() == Some(&me)) else { return Ok(None) }; + let level = acl.levels.get(agent_id).copied().unwrap_or(Access::Write); + if let Some(t) = acl.teams.iter().find(|t| team(&seats, t).iter().any(|s| s.id == mine.id)) { + return Ok(Some((level, Via::Team { seat: t.clone() }))); + } + Ok(acl.org.then_some((level, Via::Org))) + } + + /// Open a channel to its org, to teams in it, or neither (named agents + /// stay as they are). A commit in the channel's history. + pub fn set_rules(&self, channel_id: &str, author: &str, org: bool, teams: &[String]) -> Result<(), String> { + self.require_channel(channel_id)?; + let org_id = self.channel_org(channel_id)?.ok_or("This channel's workspace isn't in an org.")?; + let seats = self.seats(&org_id)?; + let name = |id: &str| seats.iter().find(|s| s.id == id).map(|s| s.title.clone()); + let mut wanted: Vec = Vec::new(); + for t in teams { + name(t).ok_or("That team isn't in this channel's org.")?; + if !wanted.contains(t) { + wanted.push(t.clone()); + } + } + let mut acl = self.current_acl(channel_id)?; + let org_name = self.orgs()?.into_iter().find(|o| o.id == org_id).map(|o| o.name).unwrap_or_default(); + let mut said: Vec = Vec::new(); + if acl.org != org { + said.push(if org { format!("Open to everyone in {org_name}") } else { format!("Close to the rest of {org_name}") }); + } + for t in wanted.iter().filter(|t| !acl.teams.contains(t)) { + said.push(format!("Open to {}'s team", name(t).unwrap_or_default())); + } + for t in acl.teams.iter().filter(|t| !wanted.contains(t)) { + said.push(format!("Close to {}'s team", name(t).unwrap_or_else(|| "a removed seat".into()))); + } + if said.is_empty() { + return Ok(()); + } + acl.org = org; + acl.teams = wanted; + self.save_acl(channel_id, author, &said.join("; "), &acl) + } + + /// Read or change for an agent in a channel, whether it's named there + /// or in through the org or a team. + pub fn set_level(&self, channel_id: &str, author: &str, agent_id: &str, access: Access) -> Result<(), String> { + let agent = self.agent(agent_id)?; + let mut acl = self.current_acl(channel_id)?; + match self.reach(agent_id, channel_id)? { + None => return Err(format!("{} isn't in this channel.", agent.name)), + Some((have, _)) if have == access => return Ok(()), + Some((_, Via::Named)) => { + acl.agents.insert(agent_id.to_string(), access); + } + Some(_) => { + acl.levels.insert(agent_id.to_string(), access); + } + } + let message = match access { + Access::Write => format!("Let {} read and change this channel", agent.name), + Access::Read => format!("Let {} read this channel", agent.name), + }; + self.save_acl(channel_id, author, &message, &acl) + } +} diff --git a/src/app/Agents.tsx b/src/app/Agents.tsx index abdd534..3a98ba3 100644 --- a/src/app/Agents.tsx +++ b/src/app/Agents.tsx @@ -3,8 +3,9 @@ // the members list, Settings' agents page, what an agent may do in a // channel, and what agents did there. import { useEffect, useRef, useState } from 'react' -import { core, clock, day, errorText, MAX_AGENT_PROMPT, type Agent, type AgentAccess, type Access, type AuditEntry, type Channel, type ClientStatus, type Connected, type LoopRules, type ModelInfo, type Profile, type ProviderInfo, type ToolInfo } from '@/lib/core' +import { core, clock, day, errorText, MAX_AGENT_PROMPT, type Holder, type Via, type Agent, type Access, type AuditEntry, type Channel, type ClientStatus, type Connected, type LoopRules, type ModelInfo, type Profile, type ProviderInfo, type ToolInfo } from '@/lib/core' import { Avatar } from './Profile' +import { OrgPlace } from './Org' /** Tell every agents list in the window that the agents changed. */ const changed = () => window.dispatchEvent(new Event('gild:agents')) @@ -312,6 +313,8 @@ export function AgentSetup({ agent, fresh, channels, current, onAgents, onClose, const [coordinator, setCoordinator] = useState(!!agent.coordinator) const [everyone, setEveryone] = useState(!!agent.everyone) const [shared, setShared] = useState | null>(null) + // How it's in each channel: named (its switch), or through the org or a team. + const [via, setVia] = useState>(new Map()) const [picked, setPicked] = useState>(new Set()) const [busy, setBusy] = useState(false) const [removing, setRemoving] = useState(false) @@ -322,11 +325,11 @@ export function AgentSetup({ agent, fresh, channels, current, onAgents, onClose, setClients(cs) setChosen(new Set(cs.filter(c => c.installed).map(c => c.id))) }, e => setError(errorText(e))) - Promise.all(channels.map(c => core.channelAccess(c.id).then(rows => [c.id, rows.find(r => r.agent.id === agent.id)?.access ?? null] as const))) + Promise.all(channels.map(c => core.channelAccess(c.id).then(rows => [c.id, rows.find(r => r.agent.id === agent.id)] as const))) .then(pairs => { - const m = new Map(pairs) - setShared(m) - setPicked(new Set(pairs.filter(([, a]) => a).map(([id]) => id))) + setShared(new Map(pairs.map(([id, r]) => [id, r?.access ?? null]))) + setVia(new Map(pairs.map(([id, r]) => [id, r?.via ?? null]))) + setPicked(new Set(pairs.filter(([, r]) => r?.access).map(([id]) => id))) }, e => setError(errorText(e))) }, [agent.id, channels]) @@ -363,6 +366,7 @@ export function AgentSetup({ agent, fresh, channels, current, onAgents, onClose, if (on && !had) await core.setAccess(channelId, agent.id, 'write') if (!on && had) await core.setAccess(channelId, agent.id, null) setShared(m => new Map(m ?? []).set(channelId, on ? (had ?? 'write') : null)) + setVia(m => new Map(m).set(channelId, on ? { kind: 'named' } : null)) setPicked(s => { const n = new Set(s); if (on) n.add(channelId); else n.delete(channelId); return n }) window.dispatchEvent(new Event('gild:reach')) }) @@ -462,11 +466,17 @@ export function AgentSetup({ agent, fresh, channels, current, onAgents, onClose, <>

Which channels can {agent.name} work in? It sees nothing else, and every change here is saved in the channel’s history.

- {channels.map(c => ( - shareOne(c.id, on)} /> - ))} + {channels.map(c => { + const through = via.get(c.id) + const byOrg = through?.kind === 'org' || through?.kind === 'team' + const hint = byOrg + ? `In through ${through.kind === 'org' ? 'the whole org' : 'its team'}; change that in the channel’s Access.` + : shared?.get(c.id) === 'read' ? 'Can read only (set in the channel’s Access).' : undefined + return ( + shareOne(c.id, on)} /> + ) + })}

A channel that’s on lets {agent.name} read, answer and change it. For read-only, use the channel’s Access button.

{fresh &&
} @@ -583,14 +593,16 @@ export function AgentPage({ agentId, channels, current, onBack }: { agentId: str /** Settings › Agents › an agent's profile: its picture, and the prompt it * gets on every wake. Laid out like your own profile. */ -export function AgentProfilePage({ agentId, onBack, pickPicture }: { agentId: string; onBack: () => void; pickPicture: (f: File) => Promise }) { +type ProfileLinks = { workspaceId: string | null; onOpenProfile: (h: Holder) => void; onOpenOrg: () => void } + +export function AgentProfilePage({ agentId, onBack, pickPicture, ...links }: { agentId: string; onBack: () => void; pickPicture: (f: File) => Promise } & ProfileLinks) { const [agents, setAgents] = useAgents() const agent = agents.find(a => a.id === agentId) if (!agent) return

Loading…

- return + return } -function AgentProfileForm({ agent, onAgents, onBack, pickPicture }: { agent: Agent; onAgents: (a: Agent[]) => void; onBack: () => void; pickPicture: (f: File) => Promise }) { +function AgentProfileForm({ agent, onAgents, onBack, pickPicture, workspaceId, onOpenProfile, onOpenOrg }: { agent: Agent; onAgents: (a: Agent[]) => void; onBack: () => void; pickPicture: (f: File) => Promise } & ProfileLinks) { const [picture, setPicture] = useState(agent.picture ?? null) const [prompt, setPrompt] = useState(agent.prompt ?? '') const [note, setNote] = useState<{ ok: boolean; text: string } | null>(null) @@ -627,6 +639,10 @@ function AgentProfileForm({ agent, onAgents, onBack, pickPicture }: { agent: Age {agent.name} gets this every time it’s woken, before the conversation. {prompt.length} / {MAX_AGENT_PROMPT} +
+ In the org + +
Preview @@ -688,40 +704,6 @@ function ToolsTab({ agent }: { agent: Agent }) { ) } -const LEVELS: { value: '' | Access; label: string }[] = [ - { value: '', label: 'No access' }, - { value: 'read', label: 'Can read' }, - { value: 'write', label: 'Can read and change' }, -] - -export function AccessPanel({ channelId, channelName, onClose }: { channelId: string; channelName: string; onClose: () => void }) { - const [rows, setRows] = useState(null) - const [error, setError] = useState('') - useEffect(() => { core.channelAccess(channelId).then(setRows, e => setError(errorText(e))) }, [channelId]) - async function change(agentId: string, value: string) { - setError('') - try { setRows(await core.setAccess(channelId, agentId, (value || null) as Access | null)); window.dispatchEvent(new Event('gild:reach')) } catch (err) { setError(errorText(err)) } - } - return ( - - ) -} - const ACTIONS: Record = { list_channels: 'listed its channels', read_channel: 'read the channel', diff --git a/src/app/Org.tsx b/src/app/Org.tsx new file mode 100644 index 0000000..1f99268 --- /dev/null +++ b/src/app/Org.tsx @@ -0,0 +1,370 @@ +'use client' +// The org: who works with whom, as an outline of seats (Settings › Org), +// and the org's part of a channel's access. +import { useEffect, useState } from 'react' +import { core, errorText, type Access, type Agent, type AgentAccess, type Channel, type ChannelRules, type Holder, type Org, type Seat } from '@/lib/core' +import { AgentAvatar, NameModal, Toggle } from './Agents' +import { Avatar, useMe } from './Profile' + +/** Tell every org view in the window that the org changed. */ +export const orgChanged = () => window.dispatchEvent(new Event('gild:org')) + +/** Every org, kept current. */ +export function useOrgs(): [Org[] | null, (o: Org[]) => void, string] { + const [orgs, setOrgs] = useState(null) + const [error, setError] = useState('') + useEffect(() => { + const load = () => core.orgs().then(setOrgs, e => setError(errorText(e))) + load() + window.addEventListener('gild:org', load) + window.addEventListener('gild:agents', load) + return () => { window.removeEventListener('gild:org', load); window.removeEventListener('gild:agents', load) } + }, []) + return [orgs, (o: Org[]) => { setOrgs(o); orgChanged() }, error] +} + +/** The holder's name, as the window shows it. */ +export function holderName(h: Holder | null, agents: Agent[], me: { id: string; name: string } | null): string | null { + if (!h) return null + if (h.kind === 'person') return h.id === me?.id ? me.name : null + return agents.find(a => a.id === h.id)?.name ?? null +} + +/** A seat's picture: yours, its agent's, or a dashed circle when it's open. */ +export function SeatAvatar({ seat, agents, size = 26 }: { seat: Seat; agents: Agent[]; size?: number }) { + const me = useMe() + if (seat.holder?.kind === 'person' && me) return + const agent = seat.holder?.kind === 'agent' ? agents.find(a => a.id === seat.holder?.id) : undefined + if (agent) return 24} /> + return +} + +/** Settings › Org: the workspace's org as an outline, and the selected seat. */ +export function OrgPage({ workspaceId, channels }: { workspaceId: string | null; channels: Channel[] }) { + const [orgs, setOrgs, error] = useOrgs() + const [agents, setAgents] = useState([]) + const [meId, setMeId] = useState(null) + const [selected, setSelected] = useState(null) + const [adding, setAdding] = useState(null) + const [renaming, setRenaming] = useState(false) + const me = useMe() + useEffect(() => { + const load = () => core.agents().then(setAgents, () => {}) + load() + core.meId().then(setMeId, () => {}) + window.addEventListener('gild:agents', load) + return () => window.removeEventListener('gild:agents', load) + }, []) + const org = orgs?.find(o => workspaceId && o.workspaces.includes(workspaceId)) ?? orgs?.[0] + if (!org) return
{error ?

{error}

:

Loading…

}
+ const seat = org.seats.find(s => s.id === selected) ?? org.seats[0] + const who = { id: meId ?? '', name: me?.name ?? 'You' } + const open = org.seats.filter(s => !s.holder).length + + function renderSeat(s: Seat) { + const kids = org!.seats.filter(k => k.parent === s.id) + const name = holderName(s.holder, agents, who) + const agent = s.holder?.kind === 'agent' ? agents.find(a => a.id === s.holder?.id) : undefined + return ( +
+ + {(kids.length > 0 || s.level < org!.max_levels) && ( +
+ {kids.map(renderSeat)} + {kids.length > 0 && kids[0].level >= org!.max_levels &&

Level {org!.max_levels}: these seats can’t have reports.

} + {s.level < org!.max_levels && ( + + )} +
+ )} +
+ ) + } + + return ( +
+
+

{org.name}

+ {org.seats.length} {org.seats.length === 1 ? 'seat' : 'seats'}{open ? ` · ${open} open` : ''} + + +
+

Each seat reports to one other seat, up to {org.max_levels} levels deep. A seat and everyone under it is a team, and a channel can be opened to a whole team in its Access. An open seat keeps its place until someone takes it.

+
+
{org.seats[0] && renderSeat(org.seats[0])}
+ setSelected(seat.parent)} /> +
+ {adding && ( + setAdding(null)} + onSubmit={async title => { + const before = new Set(org.seats.map(s => s.id)) + const next = await core.addSeat(adding.id, title) + setOrgs(next) + const made = next.find(o => o.id === org.id)?.seats.find(s => !before.has(s.id)) + if (made) setSelected(made.id) + setAdding(null) + }} /> + )} + {renaming && ( + setRenaming(false)} + onSubmit={async name => { setOrgs(await core.renameOrg(org.id, name)); setRenaming(false) }} /> + )} +
+ ) +} + +/** Where an agent sits: its chain of seats up to the top, and its reports, + * each an @mention that opens that report's profile. */ +export function OrgPlace({ workspaceId, agent, onOpenProfile, onOpenOrg }: { + workspaceId: string | null; agent: Agent; onOpenProfile: (h: Holder) => void; onOpenOrg: () => void +}) { + const [orgs] = useOrgs() + const [agents, setAgents] = useState([]) + const [meId, setMeId] = useState(null) + const me = useMe() + useEffect(() => { core.agents().then(setAgents, () => {}); core.meId().then(setMeId, () => {}) }, []) + const org = orgs?.find(o => workspaceId && o.workspaces.includes(workspaceId)) ?? orgs?.[0] + if (!org) return null + const mine = org.seats.find(s => s.holder?.kind === 'agent' && s.holder.id === agent.id) + if (!mine) return

{agent.name} doesn’t have a seat in {org.name} yet.

+ const chain: Seat[] = [] + for (let s: Seat | undefined = mine; s; s = org.seats.find(x => x.id === s?.parent)) chain.unshift(s) + const reports = org.seats.filter(s => s.parent === mine.id) + const who = { id: meId ?? '', name: me?.name ?? 'You' } + return ( +
+
+ {chain.map((s, i) => ( +
+ {i > 0 && } +
+ + {s.title}{holderName(s.holder, agents, who) ?? 'Open'} +
+
+ ))} +
+

+ {reports.length === 0 ? No reports. : <> + Reports:{' '} + {reports.map((r, i) => { + const name = holderName(r.holder, agents, who) + return ( + + {i > 0 && ', '} + {r.holder && name + ? + : {r.title} (open)} + + ) + })} + } +

+
+ ) +} + +/** A channel's access: open to the org, to teams in it, and to named + * members, and who that comes to right now. */ +export function AccessPanel({ channelId, channelName, workspaceId, onClose }: { channelId: string; channelName: string; workspaceId: string; onClose: () => void }) { + const [rows, setRows] = useState(null) + const [rules, setRules] = useState(null) + const [orgs] = useOrgs() + const [error, setError] = useState('') + useEffect(() => { + core.channelAccess(channelId).then(setRows, e => setError(errorText(e))) + core.channelRules(channelId).then(setRules, e => setError(errorText(e))) + }, [channelId]) + const org = orgs?.find(o => o.workspaces.includes(workspaceId)) + const agents = rows?.map(r => r.agent) ?? [] + + async function act(f: () => Promise) { + setError('') + try { + setRows(await f()) + setRules(await core.channelRules(channelId)) + window.dispatchEvent(new Event('gild:reach')) + } catch (e) { setError(errorText(e)) } + } + const setOrgRule = (on: boolean) => rules && act(() => core.setChannelRules(channelId, on, rules.teams)) + const setTeams = (teams: string[]) => rules && act(() => core.setChannelRules(channelId, rules.org, teams)) + + const named = rows?.filter(r => r.via?.kind === 'named') ?? [] + const inHere = rows?.filter(r => r.access) ?? [] + const seat = (id: string) => org?.seats.find(s => s.id === id) + const why = (r: AgentAccess) => r.via?.kind === 'named' ? 'named' : r.via?.kind === 'org' ? `everyone in ${org?.name ?? 'the org'}` : r.via?.kind === 'team' ? `${seat(r.via.seat)?.title ?? 'a removed seat'}’s team` : '' + + return ( + + ) +} + +type Kind = 'person' | 'agent' | 'open' + +function SeatPanel({ org, seat, agents, meId, meName, channels, onOrgs, onRemoved }: { + org: Org; seat: Seat; agents: Agent[]; meId: string | null; meName: string; channels: Channel[] + onOrgs: (o: Org[]) => void; onRemoved: () => void +}) { + const [title, setTitle] = useState(seat.title) + const [kind, setKind] = useState(seat.holder?.kind ?? 'open') + const [agentId, setAgentId] = useState(seat.holder?.kind === 'agent' ? seat.holder.id : '') + const [note, setNote] = useState<{ ok: boolean; text: string } | null>(null) + const [teamChannels, setTeamChannels] = useState([]) + const [removing, setRemoving] = useState(false) + useEffect(() => { + Promise.all(channels.map(c => core.channelRules(c.id).then(r => (r.teams.includes(seat.id) ? c : null)))) + .then(cs => setTeamChannels(cs.filter((c): c is Channel => !!c)), () => {}) + }, [channels, seat.id]) + const seatOf = (id: string) => org.seats.find(s => s.holder?.kind === 'agent' && s.holder.id === id && s.id !== seat.id) + const holder: Holder | null = kind === 'person' && meId ? { kind: 'person', id: meId } : kind === 'agent' && agentId ? { kind: 'agent', id: agentId } : null + const dirty = title !== seat.title || JSON.stringify(holder) !== JSON.stringify(seat.holder) + const parent = org.seats.find(s => s.id === seat.parent) + // Where it can move: any seat outside its own team (in the outline, the + // seat and the deeper seats right after it). The core refuses the rest. + const at = org.seats.findIndex(s => s.id === seat.id) + const team = new Set(org.seats.slice(at, at + seat.team).map(s => s.id)) + const meSeat = org.seats.find(s => s.holder?.kind === 'person' && s.id !== seat.id) + + async function act(f: () => Promise) { + setNote(null) + try { await f() } catch (e) { setNote({ ok: false, text: errorText(e) }) } + } + + return ( + + ) +} diff --git a/src/app/Profile.tsx b/src/app/Profile.tsx index 90052b9..74bbfc8 100644 --- a/src/app/Profile.tsx +++ b/src/app/Profile.tsx @@ -32,7 +32,7 @@ export function Avatar({ profile, size, status, ring }: { profile: Pick} {at === 'appearance' && } {at === 'agents' && setAt(`agent:${a.id}`)} onOpenProfile={a => setAt(`agentprofile:${a.id}`)} />} - {at.startsWith('agentprofile:') && setAt('agents')} pickPicture={smallPicture} />} + {at.startsWith('agentprofile:') && setAt('agents')} pickPicture={smallPicture} + onOpenProfile={h => setAt(h.kind === 'agent' ? `agentprofile:${h.id}` : 'profile')} onOpenOrg={() => setAt('org')} />} {at.startsWith('agent:') && setAt('agents')} />} {at === 'providers' && } {at === 'addons' && setAt(`addon:${id}`)} />} {at.startsWith('addon:') && setAt('addons')} />} + {at === 'org' && } {at === 'data' && }
diff --git a/src/app/globals.css b/src/app/globals.css index 2284f9b..cdc5358 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -476,3 +476,58 @@ tbody tr:hover { background: var(--chip); } .mention.off .mcard::after { content: ''; position: absolute; left: 0; right: 0; bottom: -8px; height: 8px; } .mention.off .mcard .primary { padding: 4px 10px; font-size: 12px; } .mention.all { background: color-mix(in srgb, var(--mark) 14%, transparent); border-radius: 4px; padding: 0 3px; } + +/* Org: the outline of seats (Settings › Org), a seat, an agent's place in it, + and a channel's org and team rules. */ +.opill { font-family: var(--mono); font-size: 10.5px; padding: 1px 7px; border-radius: 999px; background: var(--chip); color: var(--soft); } +.orgbody { display: grid; grid-template-columns: minmax(0, 1fr) 280px; gap: 24px; align-items: start; } +.tree { display: flex; flex-direction: column; min-width: 0; } +.seatgroup { display: flex; flex-direction: column; } +.seat { all: unset; cursor: pointer; display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 10px; align-items: center; padding: 7px 10px; border-radius: 9px; } +.seat:hover { background: var(--chip); } +.seat.sel { background: var(--chip); box-shadow: inset 0 0 0 1px var(--accent); } +.seat:focus-visible { outline: 2px solid var(--accent); } +.seat .who { display: flex; flex-direction: column; min-width: 0; line-height: 1.3; } +.seat .title { font-weight: 600; font-size: 13.5px; overflow-wrap: anywhere; color: var(--ink); } +.seat .holder { font-size: 12px; color: var(--soft); } +.seat .holder.open { color: var(--faint); font-style: italic; } +.seat .meta { display: flex; gap: 8px; align-items: center; font-size: 11px; color: var(--faint); font-family: var(--mono); white-space: nowrap; } +.kids { margin-left: 22px; padding-left: 12px; border-left: 1px solid var(--rule); display: flex; flex-direction: column; } +.floor { font-size: 11.5px; color: var(--faint); margin: 2px 10px 6px; } +.addseat { all: unset; cursor: pointer; font-size: 12px; color: var(--faint); padding: 5px 10px; display: flex; gap: 6px; align-items: center; border-radius: 7px; } +.addseat:hover { color: var(--ink); } +.addseat:focus-visible { outline: 2px solid var(--accent); } +.plusbox { width: 18px; height: 18px; border-radius: 5px; border: 1px dashed var(--faint); display: grid; place-items: center; font-size: 12px; } +.seatav { display: inline-grid; place-items: center; flex: none; } +.seatav .aavatar { width: 100%; height: 100%; } +.seatav.open { border-radius: 50%; border: 1.5px dashed var(--faint); color: var(--faint); font-size: 11px; font-weight: 700; } +.seatpanel { background: var(--sunk); border: 1px solid var(--rule); border-radius: 12px; padding: 16px; display: flex; flex-direction: column; gap: 14px; min-width: 0; } +.seatpanel .field { width: 100%; } +.seatpanel .seg { align-self: stretch; } +.seatpanel .seg button { flex: 1; text-align: center; padding: 6px 4px; font-size: 12px; } +.seatpanel .removebar { border-top: 1px solid var(--rule); padding-top: 10px; } +.seatpanel .confirm { flex-basis: 100%; font-size: 13px; margin: 0; } +.achips { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; } +.achip { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--rule); border-radius: 999px; padding: 3px 8px; font-size: 12.5px; background: var(--surface); color: var(--ink); } +.achip .n { font-family: var(--mono); font-size: 11px; color: var(--faint); } +.achip .x { all: unset; cursor: pointer; color: var(--faint); padding: 0 2px; } +.achip .x:hover { color: var(--bad); } +.achip .x:focus-visible { outline: 2px solid var(--accent); } +.field.add { width: auto; font-size: 12.5px; padding: 3px 6px; } +.access .arule { display: flex; flex-direction: column; gap: 8px; padding: 10px 0; border-top: 1px solid var(--rule); } +.access .arule .flabel .faint { font-weight: 400; } +.access .accessrow .aname { display: flex; align-items: center; gap: 8px; min-width: 0; } +.access .accessrow .why { font-size: 11.5px; } +.orgplace { display: flex; flex-direction: column; gap: 8px; } +.chain { display: flex; flex-direction: column; } +.chainrow { display: flex; gap: 10px; align-items: center; } +.chainrow .t { font-size: 12px; color: var(--faint); line-height: 1.2; } +.chainrow .n { font-size: 13px; font-weight: 600; line-height: 1.3; } +.chainrow.me .n { color: var(--accent); } +.chain .vline { width: 26px; display: flex; justify-content: center; } +.chain .vline i { width: 1px; height: 10px; background: var(--rule); display: block; } +.reports { margin: 0; font-size: 13px; } +.mention.mentionlink { all: unset; cursor: pointer; color: var(--mark); font-weight: 600; } +.mentionlink:hover { text-decoration: underline; } +.mentionlink:focus-visible { outline: 2px solid var(--accent); border-radius: 3px; } +@media (max-width: 820px) { .orgbody { grid-template-columns: minmax(0, 1fr); } } diff --git a/src/app/page.tsx b/src/app/page.tsx index 3fe54bc..394e6d7 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -3,7 +3,8 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { ViewPane } from './ChannelView' import { DocsPane } from './Docs' import { FilesPane } from './Files' -import { MembersGroup, NameModal, PlusButton, AccessPanel, ActivityPanel } from './Agents' +import { MembersGroup, NameModal, PlusButton, ActivityPanel } from './Agents' +import { AccessPanel } from './Org' import { MeContext, UserCard, type SettingsSection } from './Profile' import { SettingsModal } from './Settings' import { HeldBar, MessageRow, ReachContext, ReachWarning, ThreadPanel, WorkingLine, type Reach } from './Thread' @@ -300,7 +301,7 @@ function ChannelView({ channel }: { channel: Channel }) { {error &&

{error}

} - {panel === 'access' && setPanel(null)} />} + {panel === 'access' && setPanel(null)} />} {threadId && setThreadId(null)} />} {panel === 'activity' && setPanel(null)} />} diff --git a/src/lib/core.ts b/src/lib/core.ts index 952bf51..3d0d697 100644 --- a/src/lib/core.ts +++ b/src/lib/core.ts @@ -63,7 +63,16 @@ export type ModelInfo = { id: string; description: string; tools: boolean; conte /** Settings › Agents › Runaway loops. */ export type LoopRules = { limit: number; ask_coordinator: boolean; notify_me: boolean } export type NewAgent = { agent: Agent; token: string; endpoint: string } -export type AgentAccess = { agent: Agent; access: Access | null } +/** Why an agent can be in a channel: named there, or through the org or a team (`seat`: the team's top seat). */ +export type Via = { kind: 'named' } | { kind: 'org' } | { kind: 'team'; seat: string } +export type AgentAccess = { agent: Agent; access: Access | null; via: Via | null } +/** Who holds a seat: you (a person), an agent, or nobody yet (null). */ +export type Holder = { kind: 'person' | 'agent'; id: string } +/** `team`: how many seats its team has, itself included. */ +export type Seat = { id: string; title: string; parent: string | null; holder: Holder | null; level: number; team: number } +/** `seats` in outline order: each seat, then its reports. */ +export type Org = { id: string; name: string; workspaces: string[]; seats: Seat[]; max_levels: number } +export type ChannelRules = { org: boolean; teams: string[] } /** An MCP client on this computer that gild can set an agent up in. */ export type ClientStatus = { id: string; name: string; installed: boolean; connected: boolean; wake: string } export type Connected = { token: string; endpoint: string; clients: ClientStatus[]; errors: string[]; agents: Agent[] } @@ -155,6 +164,16 @@ export const core = { setWake: (agentId: string, command: string) => invoke('set_wake', { agentId, command }), channelAccess: (channelId: string) => invoke('channel_access', { channelId }), setAccess: (channelId: string, agentId: string, access: Access | null) => invoke('set_access', { channelId, agentId, access }), + setLevel: (channelId: string, agentId: string, access: Access) => invoke('set_level', { channelId, agentId, access }), + channelRules: (channelId: string) => invoke('channel_rules', { channelId }), + setChannelRules: (channelId: string, org: boolean, teams: string[]) => invoke('set_channel_rules', { channelId, org, teams }), + orgs: () => invoke('orgs'), + renameOrg: (orgId: string, name: string) => invoke('rename_org', { orgId, name }), + addSeat: (parentId: string, title: string) => invoke('add_seat', { parentId, title }), + setSeat: (seatId: string, title: string, holder: Holder | null) => invoke('set_seat', { seatId, title, holder }), + moveSeat: (seatId: string, parentId: string) => invoke('move_seat', { seatId, parentId }), + removeSeat: (seatId: string) => invoke('remove_seat', { seatId }), + meId: () => invoke('me_id'), activity: (channelId: string) => invoke('activity', { channelId }), mcpStatus: () => invoke('mcp_status'), exportWorkspace: (workspaceId: string) => invoke('export_workspace', { workspaceId }), diff --git a/tests/e2e/smoke.mjs b/tests/e2e/smoke.mjs index 5948cd0..7587315 100644 --- a/tests/e2e/smoke.mjs +++ b/tests/e2e/smoke.mjs @@ -179,6 +179,41 @@ try { assert.deepEqual(channels, ['student-intake:write'], 'general was never shared') console.log('agent sees:', JSON.stringify(channels)) + // The org: give intake a seat (Settings › Org), and the channels open to + // the whole org (new channels are) let it in; close #general to the org in + // its Access, and it's out again. + const seen = async id => JSON.parse((await mcp({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'list_channels', arguments: {} } }, init.session)).json.result.content[0].text).channels.map(c => `${c.name}:${c.access}`) + await driver.findElement(By.css("button[aria-label='App settings']")).click() + await driver.wait(until.elementLocated(By.xpath("//button[contains(@class,'sitem') and .='Org']")), 10000).click() + await driver.wait(until.elementLocated(By.xpath("//button[contains(@class,'addseat') and contains(., 'Add a report to CEO')]")), 10000, 'Add a report to CEO').click() + await driver.wait(until.elementLocated(By.css('#seat-title')), 10000).sendKeys('VP Intake', Key.ENTER) + await driver.wait(until.elementLocated(By.css("aside[aria-label='Seat: VP Intake']")), 10000, 'the new seat, selected') + await driver.findElement(By.xpath("//aside[contains(@class,'seatpanel')]//button[@role='radio' and .='An agent']")).click() + await driver.findElement(By.xpath("//select[@id='seat-agent']/option[.='intake']")).click() + await driver.findElement(By.xpath("//aside[contains(@class,'seatpanel')]//button[.='Save']")).click() + await driver.wait(until.elementLocated(By.xpath("//aside[contains(@class,'seatpanel')]//span[@class='ok' and .='Saved.']")), 10000, 'the seat saved') + await driver.wait(until.elementLocated(By.css("button.seat[aria-label='VP Intake, intake']")), 10000, 'the outline shows who holds it') + assert.deepEqual(await seen(30), ['general:write', 'student-intake:write'], 'a seat lets it into the channels open to the org') + // Its profile shows where it sits. + await driver.findElement(By.xpath("//button[contains(@class,'sitem') and .='Agents']")).click() + await driver.wait(until.elementLocated(By.css("button[aria-label='intake: profile']")), 10000).click() + const place = await driver.wait(until.elementLocated(By.css('.chainrow.me')), 10000, 'its place in the org') + assert.match(await place.getAttribute('textContent'), /VP Intake\s*intake/) + await driver.findElement(By.css("button[aria-label='Close settings']")).click() + // #general's Access: closed to the org, so intake is out. + await driver.findElement(By.xpath("//button[contains(@class,'chan') and contains(., 'general')]")).click() + await driver.wait(until.elementLocated(By.xpath("//button[contains(@class,'ghost') and .='Access']")), 10000).click() + const orgRule = await driver.wait(until.elementLocated(By.css('#rule-org')), 10000, 'the org rule') + assert.equal(await orgRule.getAttribute('aria-checked'), 'true', 'a new channel is open to the org') + await driver.wait(async () => /\bintake\b/.test(await driver.findElement(By.xpath("//section[@aria-label='Who that is']")).getAttribute('textContent')), 10000, 'intake listed, in through the org') + await orgRule.click() + await driver.wait(async () => (await driver.findElement(By.css('#rule-org')).getAttribute('aria-checked')) === 'false', 10000) + assert.deepEqual(await seen(31), ['student-intake:write'], 'closed to the org, general is out of reach again') + await driver.findElement(By.xpath("//aside[contains(@class,'panel')]//button[.='Close']")).click() + await driver.findElement(By.xpath("//button[contains(@class,'chan') and contains(., 'student-intake')]")).click() + await driver.wait(until.elementLocated(By.css('#composer')), 10000) + console.log('org: a seat let intake into the channels open to the org; closing #general to the org took it out') + // Docs: a person writes one in the window; the agent finds the answer in // it, and its edit waits until the person approves it in the window. await driver.findElement(By.xpath("//button[contains(@class,'tab') and starts-with(normalize-space(.),'Docs')]")).click() From 6e0363477dd27424fce8ab5b6e1513661bc7b764 Mon Sep 17 00:00:00 2001 From: Sami Fouad Date: Fri, 6 Nov 2026 19:46:42 -0600 Subject: [PATCH 2/2] e2e: find intake's row in Who that is by its name, not a word boundary in textContent --- tests/e2e/smoke.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/e2e/smoke.mjs b/tests/e2e/smoke.mjs index 7587315..39733ca 100644 --- a/tests/e2e/smoke.mjs +++ b/tests/e2e/smoke.mjs @@ -205,7 +205,8 @@ try { await driver.wait(until.elementLocated(By.xpath("//button[contains(@class,'ghost') and .='Access']")), 10000).click() const orgRule = await driver.wait(until.elementLocated(By.css('#rule-org')), 10000, 'the org rule') assert.equal(await orgRule.getAttribute('aria-checked'), 'true', 'a new channel is open to the org') - await driver.wait(async () => /\bintake\b/.test(await driver.findElement(By.xpath("//section[@aria-label='Who that is']")).getAttribute('textContent')), 10000, 'intake listed, in through the org') + const whoRow = await driver.wait(until.elementLocated(By.xpath("//section[@aria-label='Who that is']//div[contains(@class,'accessrow')][.//b[.='intake']]")), 10000, 'intake listed') + assert.match(await whoRow.getAttribute('textContent'), /everyone in Demo's org/, 'in through the org') await orgRule.click() await driver.wait(async () => (await driver.findElement(By.css('#rule-org')).getAttribute('aria-checked')) === 'false', 10000) assert.deepEqual(await seen(31), ['student-intake:write'], 'closed to the org, general is out of reach again')