Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/fctl-control/migrations/0050_project_icons.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- Projects' icons (fctl#850): the IconMCP glyph people chose for each, with
-- its color and style, as JSON (`ProjectIcon`). NULL: none chosen yet, and
-- the web app draws the one that fits the project's name and description.
ALTER TABLE projects ADD COLUMN icon TEXT;
23 changes: 20 additions & 3 deletions crates/fctl-control/src/api/projects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,14 @@ pub async fn create(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response> {
.map(|d| validate::text("description", d, 500))
.transpose()?
.filter(|d| !d.is_empty());
let icon = body
.icon
.as_ref()
.map(validate::project_icon)
.transpose()?
.flatten()
.map(|i| serde_json::to_string(&i))
.transpose()?;
let slug = match body.slug.as_deref().filter(|s| !s.trim().is_empty()) {
Some(sl) => slugs::chosen(&ctx.db, Of::Project, sl, None).await?,
None => slugs::free(&ctx.db, Of::Project, &naming::project_slug(&name)).await?,
Expand Down Expand Up @@ -375,14 +383,15 @@ pub async fn create(ctx: &mut Ctx, req: &mut Request) -> AppResult<Response> {
vec![
q(
&ctx.db,
"INSERT INTO projects (id, workspace_id, slug, name, description, repo_owner, repo_name, default_branch, settings, created_by, created_at, updated_at) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
"INSERT INTO projects (id, workspace_id, slug, name, description, icon, repo_owner, repo_name, default_branch, settings, created_by, created_at, updated_at) \
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
&[
s(id.as_str()),
s(workspace.id()),
s(&slug),
s(&name),
os(description.as_deref()),
os(icon.as_deref()),
os(repo.as_ref().map(|r| r.owner.as_str())),
os(repo.as_ref().map(|r| r.name.as_str())),
s(default_branch.as_deref().unwrap_or("main")),
Expand Down Expand Up @@ -429,6 +438,13 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Res
Some(d) => Some(validate::text("description", d, 500)?).filter(|d| !d.is_empty()),
None => row.description.clone(),
};
// Absent: unchanged. An empty name: none.
let icon = match &body.icon {
Some(i) => validate::project_icon(i)?
.map(|i| serde_json::to_string(&i))
.transpose()?,
None => row.icon.clone(),
};
let (mut owner, mut repo_name) = (row.repo_owner.clone(), row.repo_name.clone());
// The installation that reaches a newly linked repository.
let mut inst = None;
Expand Down Expand Up @@ -533,10 +549,11 @@ pub async fn update(ctx: &mut Ctx, req: &mut Request, id: &str) -> AppResult<Res
let mut statements = vec![
q(
&ctx.db,
"UPDATE projects SET name = ?, description = ?, repo_owner = ?, repo_name = ?, default_branch = ?, settings = ?, archived_at = ?, updated_at = ? WHERE id = ?",
"UPDATE projects SET name = ?, description = ?, icon = ?, repo_owner = ?, repo_name = ?, default_branch = ?, settings = ?, archived_at = ?, updated_at = ? WHERE id = ?",
&[
s(&name),
os(description.as_deref()),
os(icon.as_deref()),
os(owner.as_deref()),
os(repo_name.as_deref()),
s(&default_branch),
Expand Down
11 changes: 10 additions & 1 deletion crates/fctl-control/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,9 @@ pub struct ProjectRow {
pub slug: String,
pub name: String,
pub description: Option<String>,
/// Its icon, as JSON (`ProjectIcon`).
#[serde(default)]
pub icon: Option<String>,
pub repo_owner: Option<String>,
pub repo_name: Option<String>,
pub default_branch: String,
Expand Down Expand Up @@ -457,6 +460,12 @@ impl ProjectRow {
slug: self.slug.clone(),
name: self.name.clone(),
description: self.description.clone(),
// One that doesn't read as an icon reads as none: the web app
// draws the one that fits.
icon: self
.icon
.as_deref()
.and_then(|i| serde_json::from_str(i).ok()),
repo: self.repo(),
other_repos: self.other_repos.max(0) as u32,
all_repos_of: self.all_repos_of.clone(),
Expand Down Expand Up @@ -536,7 +545,7 @@ impl RepoRow {
/// repositories. Bind: `?1` = caller user id. The counts leave out the
/// sessions the lists do: review agents', and those of schedules that hide
/// theirs.
pub const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.description, p.repo_owner, p.repo_name, \
pub const PROJECT_SELECT: &str = "SELECT p.id, p.slug, p.name, p.description, p.icon, p.repo_owner, p.repo_name, \
p.default_branch, p.settings, p.session_counter, p.created_by, cu.name AS creator_name, \
cu.avatar_url AS creator_avatar, p.created_at, p.updated_at, p.archived_at, m.role AS member_role, \
(SELECT COUNT(*) FROM sessions s WHERE s.project_id = p.id AND s.status IN ('provisioning','preparing','running','idle','paused','stopping') \
Expand Down
67 changes: 66 additions & 1 deletion crates/fctl-domain/src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
//! [`ApiError`] naming the field, so handlers can return it as is.

use crate::webpush;
use fctl_proto::session::ImageBuild;
use fctl_proto::session::{ImageBuild, ProjectIcon};
use fctl_proto::{ApiError, AttachmentId};

pub type Result<T> = std::result::Result<T, ApiError>;
Expand Down Expand Up @@ -291,6 +291,37 @@ pub fn slug_shape(input: &str) -> Result<String> {
Ok(s)
}

/// A project's icon: the name of an IconMCP glyph, 1–64 of `a-z 0-9 -`
/// with dashes between words. An empty name means no icon (`None`). The
/// name isn't checked against the glyphs the web app has: it draws the one
/// that fits the project in place of one it doesn't know.
pub fn project_icon(icon: &ProjectIcon) -> Result<Option<ProjectIcon>> {
let name = icon.name.trim().to_lowercase();
if name.is_empty() {
return Ok(None);
}
let bad = |m: &str| ApiError::validation("icon", m);
if name.len() > 64 {
return Err(bad("Use an icon's name of at most 64 characters"));
}
if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|| name.starts_with('-')
|| name.ends_with('-')
|| name.contains("--")
{
return Err(bad(
"Use an icon's name: lowercase letters, digits and dashes between words",
));
}
Ok(Some(ProjectIcon {
name,
color: icon.color,
style: icon.style,
}))
}

/// A git branch name, following `git check-ref-format --branch`.
pub fn branch(field: &str, input: &str) -> Result<String> {
let s = input.trim();
Expand Down Expand Up @@ -972,4 +1003,38 @@ mod tests {
assert_eq!(effort("MAX").ok().as_deref(), Some("max"));
assert!(effort("extreme").is_err());
}

#[test]
fn project_icons() {
use fctl_proto::session::{IconStyle, WorkspaceColor};
let icon = |name: &str| ProjectIcon {
name: name.into(),
color: WorkspaceColor::Pink,
style: IconStyle::Duotone,
};
assert_eq!(
project_icon(&icon(" Server-Stack ")).ok().flatten(),
Some(ProjectIcon {
name: "server-stack".into(),
color: WorkspaceColor::Pink,
style: IconStyle::Duotone,
})
);
assert_eq!(project_icon(&icon("")).ok(), Some(None));
assert_eq!(project_icon(&icon(" ")).ok(), Some(None));
for bad in [
"-store",
"store-",
"two--dashes",
"sl/ash",
"store icon",
&"a".repeat(65),
] {
assert!(project_icon(&icon(bad)).is_err(), "{bad}");
}
// Old clients leave out the color and the style: ink lines.
let plain: ProjectIcon = serde_json::from_str(r#"{"name":"cube"}"#).unwrap_or(icon("x"));
assert_eq!(plain.color, WorkspaceColor::Ink);
assert_eq!(plain.style, IconStyle::Outline);
}
}
11 changes: 8 additions & 3 deletions crates/fctl-proto/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
use crate::event::SessionEvent;
use crate::runner::{ClaudeCredentialKind, DriverInfo, RunnerClaudeToken, SandboxLimits};
use crate::session::{
GithubAccess, InstanceRole, Memory, Project, ProjectRole, ProjectSettings, PullRequestRef,
RepoAccess, RepoRef, Retrospective, RetrospectiveOutcome, Session, SessionRef, SessionRole,
SessionStatus, UserRef, WorkspaceColor, WorkspaceRef, WorkspaceRole,
GithubAccess, InstanceRole, Memory, Project, ProjectIcon, ProjectRole, ProjectSettings,
PullRequestRef, RepoAccess, RepoRef, Retrospective, RetrospectiveOutcome, Session, SessionRef,
SessionRole, SessionStatus, UserRef, WorkspaceColor, WorkspaceRef, WorkspaceRole,
};
use crate::{
AccessRequestId, AllowId, AttachmentId, CredentialId, DeliveryId, EnrollmentTokenId,
Expand Down Expand Up @@ -2416,6 +2416,8 @@ pub struct CreateProjectRequest {
pub create_repo: Option<CreateRepoRequest>,
pub default_branch: Option<String>,
pub settings: Option<ProjectSettings>,
/// Its icon. Absent: the one that fits its name and description.
pub icon: Option<ProjectIcon>,
}

#[skip_serializing_none]
Expand All @@ -2424,6 +2426,9 @@ pub struct CreateProjectRequest {
pub struct UpdateProjectRequest {
pub name: Option<String>,
pub description: Option<String>,
/// Its icon; one with an empty name takes it away. Control planes
/// before icons ignore it.
pub icon: Option<ProjectIcon>,
/// `owner/name`, or `""` to unlink.
pub repo: Option<String>,
pub default_branch: Option<String>,
Expand Down
54 changes: 54 additions & 0 deletions crates/fctl-proto/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,57 @@ impl WorkspaceColor {
}
}

/// How a project's icon is drawn: in lines, in lines over a soft fill of
/// its color, or filled with its details cut out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum IconStyle {
#[default]
Outline,
Duotone,
Solid,
}

impl IconStyle {
pub const ALL: [Self; 3] = [Self::Outline, Self::Duotone, Self::Solid];

pub fn as_str(self) -> &'static str {
match self {
Self::Outline => "outline",
Self::Duotone => "duotone",
Self::Solid => "solid",
}
}

pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.as_str() == s)
}
}

/// A project's icon, which people choose for it: one of the glyphs of
/// [IconMCP](https://iconmcp.com) that the web app has, by its name there,
/// in a workspace color and a style. A project without one shows the glyph
/// that fits its name and description best, in ink lines.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct ProjectIcon {
/// The glyph's name in IconMCP (`store`, `server-stack`): lowercase
/// letters, digits and dashes. In an update, an empty name takes the
/// project's icon away.
pub name: String,
#[serde(default = "ink")]
#[cfg_attr(feature = "ts", ts(as = "Option<WorkspaceColor>", optional))]
pub color: WorkspaceColor,
#[serde(default)]
#[cfg_attr(feature = "ts", ts(as = "Option<IconStyle>", optional))]
pub style: IconStyle,
}

fn ink() -> WorkspaceColor {
WorkspaceColor::Ink
}

/// A workspace as projects, sessions and runners name it.
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -1036,6 +1087,9 @@ pub struct Project {
pub slug: String,
pub name: String,
pub description: Option<String>,
/// The icon people chose for it. Absent: none yet, and from control
/// planes before icons.
pub icon: Option<ProjectIcon>,
pub repo: Option<RepoRef>,
/// How many repositories its agents may use besides `repo`, named one
/// by one (`GET /api/v1/projects/{id}/repos` lists them). Absent from
Expand Down
Loading