Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channels): add manual and smart channel labels (#6675)
Eric Hayes352c85cc188f
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 38709580d1..152b9f52b3 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1973,6 +1973,43 @@"crates/user_quota","crates/workspace-hack"],+ "channel_labels": [+ "crates/agent",+ "crates/ai_toolset",+ "crates/ai_usage",+ "crates/attachment",+ "crates/bot_id",+ "crates/bot_token",+ "crates/channel_labels",+ "crates/cowlike",+ "crates/database_env_vars",+ "crates/document_sub_type",+ "crates/entity_access",+ "crates/genai_telemetry",+ "crates/harness_id",+ "crates/harness_token",+ "crates/macro_auth",+ "crates/macro_authorization",+ "crates/macro_entrypoint",+ "crates/macro_env",+ "crates/macro_env_var",+ "crates/macro_user_id",+ "crates/macro_uuid",+ "crates/model",+ "crates/model-entity",+ "crates/model-error-response",+ "crates/model_file_type",+ "crates/model_owner",+ "crates/model_user",+ "crates/models_bulk_upload",+ "crates/models_entity_access_management",+ "crates/models_pagination",+ "crates/models_permissions",+ "crates/non_empty",+ "crates/prompt",+ "crates/remote_env_var",+ "crates/workspace-hack"+ ],"channel_sender": ["crates/bot_id","crates/channel_sender",@@ -3356,6 +3393,7 @@"crates/calendar_events","crates/call","crates/channel_bots",+ "crates/channel_labels","crates/channel_sender","crates/channels","crates/chat",diff --git a/.sqlx/query-0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad.json b/.sqlx/query-0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad.jsonnew file mode 100644index 0000000000..0a061a2db3--- /dev/null+++ b/.sqlx/query-0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT c.id, c.channel_type::text as \"channel_type!\"\n FROM comms_channels c\n JOIN comms_channel_participants p ON p.channel_id = c.id\n WHERE c.id = ANY($1) AND p.user_id = $2 AND p.left_at IS NULL\n ORDER BY c.id FOR SHARE OF c, p",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "channel_type!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "Text"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "0f6fb3b1db8347505a6104b4dcf3a9a1f918cc66344494c95e3bacffcdb418ad"+}diff --git a/.sqlx/query-158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a.json b/.sqlx/query-158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a.jsonnew file mode 100644index 0000000000..5600624425--- /dev/null+++ b/.sqlx/query-158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a.json@@ -0,0 +1,72 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH labels AS (\n SELECT l.*, ARRAY(\n SELECT c.id\n FROM comms_channels c\n JOIN comms_channel_participants p\n ON p.channel_id = c.id AND p.user_id = $3 AND p.left_at IS NULL\n WHERE (\n l.name_contains IS NULL AND EXISTS (\n SELECT 1 FROM channel_label_channel lc\n WHERE lc.label_id = l.id AND lc.channel_id = c.id\n )\n ) OR (\n l.name_contains IS NOT NULL AND c.channel_type != 'direct_message'\n AND strpos(lower(c.name), lower(l.name_contains)) > 0\n )\n ORDER BY lower(c.name), c.id\n ) AS visible_ids\n FROM channel_label l\n WHERE l.scope_key = $1 AND ($2::uuid IS NULL OR l.id = $2)\n )\n SELECT\n l.id as \"id!\",\n l.team_id as \"team_id?\",\n l.name as \"name!\",\n l.name_contains as \"name_contains?\",\n l.sort_order as \"sort_order!\",\n l.created_at as \"created_at!\",\n l.updated_at as \"updated_at!\",\n l.visible_ids as \"channel_ids!: Vec<Uuid>\",\n CASE WHEN l.name_contains IS NULL THEN\n (SELECT COUNT(*) FROM channel_label_channel lc WHERE lc.label_id = l.id)\n ELSE cardinality(l.visible_ids)::bigint END as \"channel_count!\"\n FROM labels l\n ORDER BY l.sort_order, l.created_at, l.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "name_contains?",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "sort_order!",+ "type_info": "Float8"+ },+ {+ "ordinal": 5,+ "name": "created_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "channel_ids!: Vec<Uuid>",+ "type_info": "UuidArray"+ },+ {+ "ordinal": 8,+ "name": "channel_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ false,+ true,+ false,+ false,+ false,+ null,+ null+ ]+ },+ "hash": "158f9b090edb519c7f9bcb11b4053878870558208d979eb90cde3d9b2c3b0c0a"+}diff --git a/.sqlx/query-18598e232f82a5fbac9fcc2b32605e1c7dba7e3b1d4c9f4db6b9b134dd6bf819.json b/.sqlx/query-18598e232f82a5fbac9fcc2b32605e1c7dba7e3b1d4c9f4db6b9b134dd6bf819.jsonnew file mode 100644index 0000000000..8400bb340f--- /dev/null+++ b/.sqlx/query-18598e232f82a5fbac9fcc2b32605e1c7dba7e3b1d4c9f4db6b9b134dd6bf819.json@@ -0,0 +1,27 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO channel_label (id, team_id, user_id, name, name_contains, sort_order)\n VALUES ($1, $2, $3, $4, $6,\n COALESCE((SELECT MAX(sort_order) + 1 FROM channel_label WHERE scope_key = $5), 0))\n ON CONFLICT DO NOTHING\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "18598e232f82a5fbac9fcc2b32605e1c7dba7e3b1d4c9f4db6b9b134dd6bf819"+}diff --git a/.sqlx/query-29a53a8c3068d8572103b374b6a736d202d5bb61e8aa04e6623848c0aa187d37.json b/.sqlx/query-29a53a8c3068d8572103b374b6a736d202d5bb61e8aa04e6623848c0aa187d37.jsonnew file mode 100644index 0000000000..ddc40ed621--- /dev/null+++ b/.sqlx/query-29a53a8c3068d8572103b374b6a736d202d5bb61e8aa04e6623848c0aa187d37.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM channel_label_channel WHERE scope_key = $1 AND channel_id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "29a53a8c3068d8572103b374b6a736d202d5bb61e8aa04e6623848c0aa187d37"+}diff --git a/.sqlx/query-4cb9fb35e162513bf15aa1f9af408d6c149b2753e2adb041966b4101f5befcc0.json b/.sqlx/query-4cb9fb35e162513bf15aa1f9af408d6c149b2753e2adb041966b4101f5befcc0.jsonnew file mode 100644index 0000000000..c63e32ec97--- /dev/null+++ b/.sqlx/query-4cb9fb35e162513bf15aa1f9af408d6c149b2753e2adb041966b4101f5befcc0.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO channel_label_channel (scope_key, channel_id, label_id)\n VALUES ($1, $2, $3)\n ON CONFLICT (scope_key, channel_id) DO UPDATE SET label_id = EXCLUDED.label_id",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4cb9fb35e162513bf15aa1f9af408d6c149b2753e2adb041966b4101f5befcc0"+}diff --git a/.sqlx/query-58a39b792f68382421cf3755fbc03c0ecb567dbb7e07e3773573ff2fde71a198.json b/.sqlx/query-58a39b792f68382421cf3755fbc03c0ecb567dbb7e07e3773573ff2fde71a198.jsonnew file mode 100644index 0000000000..5fa2145a83--- /dev/null+++ b/.sqlx/query-58a39b792f68382421cf3755fbc03c0ecb567dbb7e07e3773573ff2fde71a198.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM channel_label WHERE id = $2 AND scope_key = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "58a39b792f68382421cf3755fbc03c0ecb567dbb7e07e3773573ff2fde71a198"+}diff --git a/.sqlx/query-6690f1280a982415a150a0db5bc65d750f153701f40cf556a953463104515bd9.json b/.sqlx/query-6690f1280a982415a150a0db5bc65d750f153701f40cf556a953463104515bd9.jsonnew file mode 100644index 0000000000..36b698e070--- /dev/null+++ b/.sqlx/query-6690f1280a982415a150a0db5bc65d750f153701f40cf556a953463104515bd9.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_channels SET name = 'Acme sales' WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "6690f1280a982415a150a0db5bc65d750f153701f40cf556a953463104515bd9"+}diff --git a/.sqlx/query-7a3e50ceb8c28128df6ef8f08870d80dd486a53e2e6372daf9f813263c13d9d1.json b/.sqlx/query-7a3e50ceb8c28128df6ef8f08870d80dd486a53e2e6372daf9f813263c13d9d1.jsonnew file mode 100644index 0000000000..2b188248d7--- /dev/null+++ b/.sqlx/query-7a3e50ceb8c28128df6ef8f08870d80dd486a53e2e6372daf9f813263c13d9d1.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE channel_label\n SET name = $3, name_contains = COALESCE($4, name_contains), updated_at = now()\n WHERE id = $2 AND scope_key = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "7a3e50ceb8c28128df6ef8f08870d80dd486a53e2e6372daf9f813263c13d9d1"+}diff --git a/.sqlx/query-b1e9a9983331e291b2e8053fdd35d23ac43712b3ffe0b13dc1c6f4d6d1b6d6ae.json b/.sqlx/query-b1e9a9983331e291b2e8053fdd35d23ac43712b3ffe0b13dc1c6f4d6d1b6d6ae.jsonnew file mode 100644index 0000000000..6d4fe36092--- /dev/null+++ b/.sqlx/query-b1e9a9983331e291b2e8053fdd35d23ac43712b3ffe0b13dc1c6f4d6d1b6d6ae.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b1e9a9983331e291b2e8053fdd35d23ac43712b3ffe0b13dc1c6f4d6d1b6d6ae"+}diff --git a/.sqlx/query-c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35.json b/.sqlx/query-c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35.jsonnew file mode 100644index 0000000000..50eea93b71--- /dev/null+++ b/.sqlx/query-c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35.json@@ -0,0 +1,36 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT c.id, c.name as \"name!\", COUNT(*) OVER () as \"total_count!\"\n FROM comms_channels c\n JOIN comms_channel_participants p ON p.channel_id = c.id\n WHERE p.user_id = $1 AND p.left_at IS NULL\n AND c.channel_type != 'direct_message'\n AND strpos(lower(c.name), lower($2)) > 0\n ORDER BY lower(c.name), c.id\n LIMIT $3",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "total_count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false,+ true,+ null+ ]+ },+ "hash": "c201471a0db1e3c1c4871898d6b4ad3506323c17457531cca340fcfb84dcad35"+}diff --git a/.sqlx/query-d08cea9c8ce158f5d2dae74eee59b3b7d6c52b6fc8135ef906260893b094652b.json b/.sqlx/query-d08cea9c8ce158f5d2dae74eee59b3b7d6c52b6fc8135ef906260893b094652b.jsonnew file mode 100644index 0000000000..c199999363--- /dev/null+++ b/.sqlx/query-d08cea9c8ce158f5d2dae74eee59b3b7d6c52b6fc8135ef906260893b094652b.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"User\" (id, email, macro_user_id) VALUES ($1, $1, $2)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d08cea9c8ce158f5d2dae74eee59b3b7d6c52b6fc8135ef906260893b094652b"+}diff --git a/.sqlx/query-d5620eed745df4ee9bfaef64f03c85c3eae33387aa1a2b60c1da079d2cf485b9.json b/.sqlx/query-d5620eed745df4ee9bfaef64f03c85c3eae33387aa1a2b60c1da079d2cf485b9.jsonnew file mode 100644index 0000000000..6ccf99f5dc--- /dev/null+++ b/.sqlx/query-d5620eed745df4ee9bfaef64f03c85c3eae33387aa1a2b60c1da079d2cf485b9.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO channel_label_channel (scope_key, channel_id, label_id)\n SELECT $1, channel_id, $2 FROM unnest($3::uuid[]) AS channel_id\n ON CONFLICT (scope_key, channel_id) DO UPDATE SET label_id = EXCLUDED.label_id",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "d5620eed745df4ee9bfaef64f03c85c3eae33387aa1a2b60c1da079d2cf485b9"+}diff --git a/.sqlx/query-f06cd7119b02213fea929bf02339100d938122ca54abe75b94a013abd301075f.json b/.sqlx/query-f06cd7119b02213fea929bf02339100d938122ca54abe75b94a013abd301075f.jsonnew file mode 100644index 0000000000..df848204f4--- /dev/null+++ b/.sqlx/query-f06cd7119b02213fea929bf02339100d938122ca54abe75b94a013abd301075f.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id, name_contains FROM channel_label WHERE id = $2 AND scope_key = $1 FOR KEY SHARE",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name_contains",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "f06cd7119b02213fea929bf02339100d938122ca54abe75b94a013abd301075f"+}diff --git a/.sqlx/query-fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433.json b/.sqlx/query-fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433.jsonnew file mode 100644index 0000000000..ad01379f13--- /dev/null+++ b/.sqlx/query-fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "fda562d30ca57ca7b5b112f2414f38f809e78207c82ed1fb32fcb01ef7864433"+}diff --git a/Cargo.lock b/Cargo.lockindex 01068044b7..fcc84757a3 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3514,6 +3514,30 @@ dependencies = ["workspace-hack",]+[[package]]+name = "channel_labels"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum",+ "chrono",+ "cowlike",+ "entity_access",+ "macro_authorization",+ "macro_db_migrator",+ "macro_user_id",+ "model-entity",+ "model-error-response",+ "serde",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "utoipa",+ "uuid",+ "workspace-hack",+]+[[package]]name = "channel_sender"version = "0.1.0"@@ -5512,6 +5536,7 @@ dependencies = ["calendar_events","call","channel_bots",+ "channel_labels","channels","chat","chrono",diff --git a/Cargo.toml b/Cargo.tomlindex dfcb78beb0..a7369629ee 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -16,6 +16,7 @@ members = ["crates/broadcast","crates/calendar_events","crates/channel_bots",+ "crates/channel_labels","crates/client/cache-core","crates/client/cache-turso","crates/client/cache-wasm",diff --git a/apps/web/src/components/app/ItemDragAndDrop.tsx b/apps/web/src/components/app/ItemDragAndDrop.tsxindex 1d38951c14..6f98d24cd3 100644--- a/apps/web/src/components/app/ItemDragAndDrop.tsx+++ b/apps/web/src/components/app/ItemDragAndDrop.tsx@@ -7,7 +7,6 @@ import { TruncatedText } from '@core/component/FileList/TruncatedText';import { UserIcon } from '@core/component/UserIcon';import type { EntityDragData } from '@entity';import {- type CollisionDetector,DragDropProvider,DragDropSensors,DragOverlay,@@ -24,6 +23,7 @@ import {Show,useContext,} from 'solid-js';+import { createPointerCollisionDetector } from './pointer-collision';type DragOperationContextValue = {isAltKey: Accessor<boolean>;@@ -31,40 +31,6 @@ type DragOperationContextValue = {const DragOperationContext = createContext<DragOperationContextValue>();-let pointerPosition: { x: number; y: number } | undefined;--const pointerWithin: CollisionDetector = (_draggable, droppables, context) => {- if (!pointerPosition) return null;-- const enabledDroppables = droppables.filter((droppable) => {- const isDisabled = droppable.data.isDropTargetDisabled as- | (() => boolean)- | undefined;- return !isDisabled?.();- });-- const hits = enabledDroppables.filter((droppable) => {- const layout = droppable.layout;- return (- pointerPosition !== undefined &&- pointerPosition.x >= layout.left &&- pointerPosition.x <= layout.right &&- pointerPosition.y >= layout.top &&- pointerPosition.y <= layout.bottom- );- });-- if (hits.length === 0) return null;- if (hits.length === 1) return hits[0];-- return hits.toSorted(- (a, b) =>- a.layout.width * a.layout.height - b.layout.width * b.layout.height ||- Number(b.id === context.activeDroppableId) -- Number(a.id === context.activeDroppableId)- )[0];-};-export function useDragOperation() {const context = useContext(DragOperationContext);if (!context) {@@ -84,7 +50,7 @@ function ItemDragOverlay() {if (!data) return 'default';// Favorite sortables carry a precomputed icon type (see FavoriteDragData// in app-sidebar/favorites-section) instead of an entity shape.- if (data.dragType === 'favorite') {+ if (data.dragType === 'favorite' || data.dragType === 'channel-label') {return data.iconType as EntityIconSelector;}if (data.dragType === 'stage') return 'default';@@ -158,6 +124,8 @@ function ItemDragOverlay() {}export function ItemDndProvider(props: { children: JSXElement }) {+ let pointerPosition: { x: number; y: number } | undefined;+ const pointerWithin = createPointerCollisionDetector(() => pointerPosition);const [isAltPressed, setIsAltPressed] = createSignal(false);const handleKeyDown = (e: KeyboardEvent) => {@@ -219,7 +187,7 @@ export function ItemDndProvider(props: { children: JSXElement }) {<DragDropProvider collisionDetector={pointerWithin}><DragDropSensors />{props.children}- <DragOverlay class="z-drag">+ <DragOverlay class="z-drag pointer-events-none"><ItemDragOverlay /></DragOverlay></DragDropProvider>diff --git a/apps/web/src/components/app/pointer-collision.test.ts b/apps/web/src/components/app/pointer-collision.test.tsnew file mode 100644index 0000000000..bbd1bd7f7d--- /dev/null+++ b/apps/web/src/components/app/pointer-collision.test.ts@@ -0,0 +1,93 @@+import type { CollisionDetector } from '@thisbeyond/solid-dnd';+import { describe, expect, it, vi } from 'vitest';+import { createPointerCollisionDetector } from './pointer-collision';++type Draggable = Parameters<CollisionDetector>[0];+type Droppable = Parameters<CollisionDetector>[1][number];+function item(node: HTMLElement, id: string, dndScope?: string): Droppable {+ const layout = {+ x: 999,+ y: 999,+ width: 1,+ height: 1,+ left: 999,+ top: 999,+ right: 1000,+ bottom: 1000,+ rect: { x: 999, y: 999, width: 1, height: 1 },+ center: { x: 999.5, y: 999.5 },+ corners: {+ topLeft: { x: 999, y: 999 },+ topRight: { x: 1000, y: 999 },+ bottomRight: { x: 1000, y: 1000 },+ bottomLeft: { x: 999, y: 1000 },+ },+ };+ return {+ id,+ node,+ data: { dndScope },+ layout,+ transformers: {},+ transform: { x: 0, y: 0 },+ transformed: layout,+ };+}+const context = { activeDroppableId: null };++describe('pointer collision', () => {+ it('uses the innermost visible target regardless of stale cached bounds', () => {+ const list = document.createElement('div');+ const row = document.createElement('div');+ const name = document.createElement('span');+ list.append(row);+ row.append(name);+ const source = item(+ document.createElement('div'),+ 'source',+ 'rail'+ ) as Draggable;+ const targets = [item(list, 'list', 'rail'), item(row, 'row', 'rail')];+ const hit = vi.fn(() => name);+ const detector = createPointerCollisionDetector(+ () => ({ x: 50, y: 75 }),+ hit+ );+ expect(detector(source, targets, context)?.id).toBe('row');+ expect(hit).toHaveBeenCalledWith(50, 75);+ });++ it('ignores clipped or covered targets and follows scroll changes', () => {+ const list = document.createElement('div');+ const row = document.createElement('div');+ list.append(row);+ const source = item(row, 'source') as Draggable;+ const targets = [item(list, 'list'), item(row, 'row')];+ let visible: Element = row;+ const detector = createPointerCollisionDetector(+ () => ({ x: 10, y: 20 }),+ () => visible+ );+ expect(detector(source, targets, context)?.id).toBe('row');+ visible = list;+ expect(detector(source, targets, context)?.id).toBe('list');+ visible = document.createElement('div');+ expect(detector(source, targets, context)).toBeNull();+ });++ it('isolates drag scopes and skips disabled targets', () => {+ const row = document.createElement('div');+ const source = item(row, 'source', 'first') as Draggable;+ const target = item(row, 'target', 'second');+ const detector = createPointerCollisionDetector(+ () => ({ x: 0, y: 0 }),+ () => row+ );+ expect(detector(source, [target], context)).toBeNull();+ target.data.dndScope = 'first';+ target.data.isDropTargetDisabled = () => true;+ expect(detector(source, [target], context)).toBeNull();+ target.data.isDropTargetDisabled = () => false;+ expect(detector(source, [target], context)?.id).toBe('target');+ });+});diff --git a/apps/web/src/components/app/pointer-collision.ts b/apps/web/src/components/app/pointer-collision.tsnew file mode 100644index 0000000000..918d7ca084--- /dev/null+++ b/apps/web/src/components/app/pointer-collision.ts@@ -0,0 +1,31 @@+import type { CollisionDetector } from '@thisbeyond/solid-dnd';++/** Hit-test visible DOM nodes so scrolling, clipping and layout changes are honored. */+export function createPointerCollisionDetector(+ pointer: () => { x: number; y: number } | undefined,+ elementAtPoint = (x: number, y: number) => document.elementFromPoint(x, y)+): CollisionDetector {+ return (draggable, droppables) => {+ const position = pointer();+ if (!position) return null;+ const element = elementAtPoint(position.x, position.y);+ if (!element) return null;++ // Walk from the actual hit toward its ancestors: a channel row wins over+ // its enclosing list, and clipped/covered rows can never win a collision.+ for (let node: Element | null = element; node; node = node.parentElement) {+ const hit = droppables.find((droppable) => {+ const disabled = droppable.data.isDropTargetDisabled as+ | (() => boolean)+ | undefined;+ return (+ droppable.node === node &&+ draggable.data.dndScope === droppable.data.dndScope &&+ !disabled?.()+ );+ });+ if (hit) return hit;+ }+ return null;+ };+}diff --git a/apps/web/src/features/channels-view/channels-view-context.test.tsx b/apps/web/src/features/channels-view/channels-view-context.test.tsxindex 070724585d..cee170d9bd 100644--- a/apps/web/src/features/channels-view/channels-view-context.test.tsx+++ b/apps/web/src/features/channels-view/channels-view-context.test.tsx@@ -125,6 +125,26 @@ describe('ChannelsViewProvider preview selection', () => {expect(context.previewChannelId()).toBeUndefined();});+ it('persists collapsed labels per user and restores them', () => {+ const storageKey = 'macro:channels:view-state:v1:alice';+ const first = mountProvider();++ first.context.setLabelOpen('enterprise', false);+ first.context.setLabelOpen('smb', false);+ first.context.setLabelOpen('enterprise', false);+ expect(first.context.state.collapsedLabels).toEqual(['enterprise', 'smb']);+ first.context.setLabelOpen('smb', true);+ expect(first.context.state.collapsedLabels).toEqual(['enterprise']);+ expect(JSON.parse(localStorage.getItem(storageKey)!)).toMatchObject({+ collapsedLabels: ['enterprise'],+ expandedGroups: expect.objectContaining({ unread: true }),+ });+ first.unmount();++ const second = mountProvider();+ expect(second.context.state.collapsedLabels).toEqual(['enterprise']);+ });+it('keeps touch selections out of the preview registry', () => {touch.value = true;guard.allow = false;diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsxindex a9eea00a21..1df5ad262b 100644--- a/apps/web/src/features/channels-view/channels-view-context.tsx+++ b/apps/web/src/features/channels-view/channels-view-context.tsx@@ -37,6 +37,8 @@ export type ChannelsViewContext = {setMobileTab: (tab: ChannelsQueryScope) => void;setSelectedChannelId: (channelId: string | undefined) => void;setGroupOpen: (group: ChannelsRailSection, open: boolean) => void;+ /** Per-user collapse state of a team channel label. */+ setLabelOpen: (labelId: string, open: boolean) => void;setSortBy: (group: ChannelsGroup, sort: ChannelListSort) => void;setAsideWidth: (width: number) => void;};@@ -51,9 +53,11 @@ function createInitialState(selectedChannelId: initial.selectedChannelId,expandedGroups: {favorites: initial.expandedGroups?.favorites ?? true,+ unread: initial.expandedGroups?.unread ?? true,channels: initial.expandedGroups?.channels ?? true,direct_messages: initial.expandedGroups?.direct_messages ?? true,},+ collapsedLabels: initial.collapsedLabels ?? [],sortBy: {channels: initial.sortBy?.channels ?? CHANNELS_DEFAULT_SORT_BY.channels,direct_messages:@@ -112,6 +116,14 @@ export const [ChannelsViewProvider, useChannelsView] =setMobileTab: (tab) => setState('mobileTab', tab),setSelectedChannelId,setGroupOpen: (group, open) => setState('expandedGroups', group, open),+ setLabelOpen: (labelId, open) =>+ setState('collapsedLabels', (collapsed) =>+ open+ ? collapsed.filter((id) => id !== labelId)+ : collapsed.includes(labelId)+ ? collapsed+ : [...collapsed, labelId]+ ),setSortBy: (group, sort) => setState('sortBy', group, sort),setAsideWidth: (width) =>setState('asideWidth', clampChannelsRailWidth(width)),diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsxnew file mode 100644index 0000000000..f68fbd303d--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.test.tsx@@ -0,0 +1,94 @@+import { ImperativeDialogHost } from '@app/components/ui/components/ImperativeDialog';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import type { ComponentProps, ParentProps } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { promptLabelName } from './ChannelLabelNameDialog';++vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@ui', async () => ({+ ...(await import('@app/components/ui/components/ImperativeDialog')),+ ...(await import('@app/components/ui/components/Dialog')),+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ Layer: (props: ParentProps) => props.children,+ Surface: (props: ParentProps) => <div>{props.children}</div>,+ Input: (props: ComponentProps<'input'>) => <input {...props} />,+ Button: (props: ComponentProps<'button'>) => (+ <button type={props.type} disabled={props.disabled} onClick={props.onClick}>+ {props.children}+ </button>+ ),+}));+beforeEach(() => vi.stubGlobal('scrollTo', vi.fn()));+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe('label naming', () => {+ it('retains the name after failure, prevents duplicate submits, and closes only after saving', async () => {+ render(() => <ImperativeDialogHost />);+ let finish!: () => void;+ const onConfirm = vi+ .fn()+ .mockRejectedValueOnce(new Error('A label with this name already exists'))+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const result = promptLabelName({+ title: 'New label',+ body: 'Private',+ confirmLabel: 'Create label',+ onConfirm,+ });+ const input = screen.getByRole('textbox', {+ name: 'Label name',+ }) as HTMLInputElement;+ fireEvent.input(input, { target: { value: ' My group ' } });+ fireEvent.submit(input.closest('form')!);+ await waitFor(() =>+ expect(screen.getByRole('alert').textContent).toContain('already exists')+ );+ expect(input.value).toBe(' My group ');+ fireEvent.input(input, { target: { value: 'New name' } });+ fireEvent.submit(input.closest('form')!);+ fireEvent.submit(input.closest('form')!);+ expect(onConfirm).toHaveBeenCalledTimes(2);+ expect(screen.getByRole('dialog', { name: 'New label' })).toBeTruthy();+ finish();+ expect(await result).toBe('New name');+ expect(screen.queryByRole('dialog')).toBeNull();+ });++ it('cancel never saves, and reopening accepts a fresh name', async () => {+ render(() => <ImperativeDialogHost />);+ const onConfirm = vi.fn(async () => {});+ const props = {+ title: 'New label',+ body: 'Private',+ confirmLabel: 'Create label',+ onConfirm,+ };+ const first = promptLabelName(props);+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(await first).toBeUndefined();+ expect(onConfirm).not.toHaveBeenCalled();+ const next = promptLabelName(props);+ const input = screen.getByRole('textbox', {+ name: 'Label name',+ }) as HTMLInputElement;+ expect(input.value).toBe('');+ fireEvent.input(input, { target: { value: 'Second group' } });+ fireEvent.submit(input.closest('form')!);+ expect(await next).toBe('Second group');+ expect(onConfirm).toHaveBeenCalledWith('Second group');+ });+});diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.tsxnew file mode 100644index 0000000000..ed1070b0ff--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelNameDialog.tsx@@ -0,0 +1,148 @@+import {+ Button,+ Dialog,+ Input,+ type ManagedDialogProps,+ type OpenDialogOptions,+ openDialog,+ Surface,+} from '@ui';+import { createSignal, type JSX, Show } from 'solid-js';++export type LabelNameDialogProps = {+ title: string;+ /** Explains the label's scope, shown under the title. */+ body: JSX.Element;+ confirmLabel: string;+ initialValue?: string;+ placeholder?: string;+ onConfirm: (name: string) => Promise<void>;+};++/** Longest accepted label name; mirrors the backend limit. */+const MAX_LABEL_NAME_LENGTH = 80;++function LabelNameDialog(+ props: ManagedDialogProps &+ LabelNameDialogProps & { onSubmit: (name: string) => void }+) {+ const [value, setValue] = createSignal(props.initialValue ?? '');+ const [pending, setPending] = createSignal(false);+ const [error, setError] = createSignal('');+ const trimmed = () => value().trim();+ const canSubmit = () =>+ trimmed().length > 0 && trimmed() !== (props.initialValue ?? '').trim();++ const submit = async (event: Event) => {+ event.preventDefault();+ if (!canSubmit() || pending()) return;+ const name = trimmed();+ setPending(true);+ setError('');+ try {+ await props.onConfirm(name);+ props.onSubmit(name);+ } catch (error) {+ setError(+ error instanceof Error+ ? error.message+ : 'Could not save label. Please try again.'+ );+ } finally {+ setPending(false);+ }+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!pending()) props.onOpenChange(open);+ }}+ class="w-[90%] max-w-100"+ visibleScrim+ >+ <Surface depth={2} class="rounded-xl text-ink">+ <form onSubmit={(event) => void submit(event)} aria-busy={pending()}>+ <div class="flex flex-col gap-3 px-5 py-4">+ <div class="flex flex-col gap-1">+ <Dialog.Title class="text-base font-semibold">+ {props.title}+ </Dialog.Title>+ <Dialog.Description+ as="div"+ class="text-sm leading-5 text-ink-muted"+ >+ {props.body}+ </Dialog.Description>+ </div>+ <Input+ aria-label="Label name"+ readOnly={pending()}+ onFocus={(event) => event.currentTarget.select()}+ placeholder={props.placeholder ?? 'Label name'}+ value={value()}+ maxLength={MAX_LABEL_NAME_LENGTH}+ onInput={(event) => setValue(event.currentTarget.value)}+ />+ <Show when={error()}>+ <p role="alert" class="text-sm text-failure">+ {error()}+ </p>+ </Show>+ </div>+ <div class="flex items-center justify-end gap-2 px-5 py-3">+ <Button+ type="button"+ variant="ghost"+ depth={2}+ class="rounded-lg"+ disabled={pending()}+ onClick={() => props.onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ variant="accent"+ depth={2}+ class="rounded-lg"+ disabled={!canSubmit() || pending()}+ >+ {pending() ? 'Saving…' : props.confirmLabel}+ </Button>+ </div>+ </form>+ </Surface>+ </Dialog>+ );+}++/**+ * Ask for a label name in a dialog that explains who can see the label.+ * Resolves with the trimmed name, or `undefined` when dismissed.+ */+export async function promptLabelName(+ props: LabelNameDialogProps,+ options?: OpenDialogOptions+): Promise<string | undefined> {+ let result: string | undefined;++ const handle = openDialog(+ (managed: ManagedDialogProps & LabelNameDialogProps) => (+ <LabelNameDialog+ {...managed}+ onOpenChange={(open) => !open && managed.onOpenChange(false)}+ onSubmit={(name) => {+ result = name;+ managed.onOpenChange(false);+ }}+ />+ ),+ props,+ options+ );++ await handle.closed;+ return result;+}diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsxnew file mode 100644index 0000000000..2fdf3ffe99--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.test.tsx@@ -0,0 +1,124 @@+import type { ChannelEntity } from '@entity';+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import {+ type ComponentProps,+ createSignal,+ type ParentProps,+ type Setter,+ splitProps,+} from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ChannelLabelMenuItems, ChannelsCreateMenu } from './ChannelLabelRows';++const rail = vi.hoisted(() => ({+ channelTagsEnabled: (): boolean => false,+ labelsAvailable: () => true,+ labels: () => [+ { id: 'label', name: 'Cached label', channelIds: ['channel'] },+ ],+ createLabel: vi.fn(),+ createSmartTag: vi.fn(),+ setChannelLabel: vi.fn(),+}));+const openNewChannelModal = vi.hoisted(() => vi.fn());++vi.mock('./ChannelsRailContext', () => ({ useChannelsRail: () => rail }));+vi.mock('./hooks/useChannelRailState', () => ({}));+vi.mock('./ChannelRailItems', () => ({}));+vi.mock('@channel/CreateChannelModal', () => ({ openNewChannelModal }));+vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@app/components/view-shell', () => ({+ ViewSidebar: {+ Control: (+ props: ComponentProps<'button'> & {+ label: string;+ variant?: string;+ size?: string;+ }+ ) => {+ const [local, rest] = splitProps(props, ['label', 'variant', 'size']);+ return <button {...rest} aria-label={local.label} />;+ },+ },+}));+vi.mock('@ui', async () => ({+ ...(await import('@app/components/ui/components/Dropdown')),+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+}));+vi.mock('@core/component/ContextMenu', () => ({+ ContextMenuContent: (props: ParentProps) => <div>{props.children}</div>,+ MenuItem: (props: { text: string; onClick?: () => void }) => (+ <button onClick={props.onClick}>{props.text}</button>+ ),+ MenuSeparator: () => <hr />,+ SubTrigger: (props: { text: string }) => <span>{props.text}</span>,+}));+vi.mock('@kobalte/core/context-menu', () => ({+ ContextMenu: {+ Sub: (props: ParentProps) => props.children,+ RadioGroup: (props: ParentProps) => props.children,+ },+}));++let setEnabled: Setter<boolean>;+beforeEach(() => {+ [rail.channelTagsEnabled, setEnabled] = createSignal(false);+ vi.clearAllMocks();+ vi.stubGlobal('scrollTo', vi.fn());+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe('channel tag flag in rail menus', () => {+ it('keeps direct channel creation available and removes an open label menu when disabled', async () => {+ render(() => <ChannelsCreateMenu />);++ fireEvent.click(screen.getByRole('button', { name: 'Create channel' }));+ expect(openNewChannelModal).toHaveBeenCalledOnce();+ expect(screen.queryByRole('menu')).toBeNull();++ setEnabled(true);+ fireEvent.keyDown(+ screen.getByRole('button', { name: 'Create channel or label' }),+ { key: 'ArrowDown' }+ );+ expect(+ await screen.findByRole('menuitem', { name: 'New label' })+ ).toBeTruthy();+ expect(+ screen.getByRole('menuitem', { name: 'New smart label' })+ ).toBeTruthy();++ setEnabled(false);+ expect(screen.queryByRole('menu')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Create channel' }));+ expect(openNewChannelModal).toHaveBeenCalledTimes(2);+ expect(rail.createLabel).not.toHaveBeenCalled();+ expect(rail.createSmartTag).not.toHaveBeenCalled();+ });++ it('hides cached label actions when the flag changes without remounting', () => {+ const channel = {+ id: 'channel',+ channelType: 'public',+ } as ChannelEntity;+ render(() => <ChannelLabelMenuItems channel={channel} />);++ expect(screen.queryByText('Move to label')).toBeNull();+ expect(screen.queryByText('Cached label')).toBeNull();++ setEnabled(true);+ expect(screen.getByText('Move to label')).toBeTruthy();+ expect(screen.getByText('Cached label')).toBeTruthy();+ expect(screen.getByText('Ungroup from “Cached label”')).toBeTruthy();++ setEnabled(false);+ expect(screen.queryByText('Move to label')).toBeNull();+ expect(screen.queryByText('Cached label')).toBeNull();+ expect(screen.queryByText('Ungroup from “Cached label”')).toBeNull();+ expect(rail.setChannelLabel).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsxnew file mode 100644index 0000000000..fca1d91dbf--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx@@ -0,0 +1,310 @@+import { ViewSidebar } from '@app/components/view-shell';+import { openNewChannelModal } from '@channel/CreateChannelModal';+import {+ ContextMenuContent,+ MenuItem,+ MenuSeparator,+ SubTrigger,+} from '@core/component/ContextMenu';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import type { ChannelEntity } from '@entity';+import { ContextMenu } from '@kobalte/core/context-menu';+import CaretDownIcon from '@phosphor/caret-down.svg';+import ChecksIcon from '@phosphor/checks.svg';+import DotsThreeIcon from '@phosphor/dots-three.svg';+import FilterIcon from '@phosphor/funnel-simple.svg';+import HashIcon from '@phosphor/hash.svg';+import PencilSimpleIcon from '@phosphor/pencil-simple.svg';+import PlusIcon from '@phosphor/plus.svg';+import TagIcon from '@phosphor/tag.svg';+import TagSimpleIcon from '@phosphor/tag-simple.svg';+import TrashIcon from '@phosphor/trash.svg';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import { createDroppable } from '@thisbeyond/solid-dnd';+import { cn, Dropdown } from '@ui';+import { type Component, For, type JSX, Show } from 'solid-js';+import { isDirectMessage } from '../../utils';+import { isPrimaryMouseDown } from './ChannelRailItems';+import {+ type ChannelLabelDropData,+ rowKeyForLabel,+ useChannelsRail,+} from './ChannelsRailContext';+import { useChannelRailLabelState } from './hooks/useChannelRailState';++type MenuIcon = Component<JSX.SvgSVGAttributes<SVGSVGElement>>;++/** A dropdown row in the house style: muted icon, muted label. */+function MenuRow(props: {+ icon: MenuIcon;+ label: string;+ disabled?: boolean;+ onSelect: () => void;+}) {+ return (+ <Dropdown.Item disabled={props.disabled} onSelect={props.onSelect}>+ <span class="flex size-3.5 shrink-0 items-center justify-center text-ink-muted">+ <props.icon class="size-3.5" />+ </span>+ <span class="flex-1 truncate text-ink-muted">{props.label}</span>+ </Dropdown.Item>+ );+}++/** Count pill used by section headings, reused so labels read the same way. */+function UnreadPill(props: { count: number }) {+ return (+ <Show when={props.count > 0}>+ <span class="flex h-4 min-w-4 shrink-0 items-center justify-center rounded-full bg-accent px-1 text-xs font-medium leading-none tabular-nums text-accent-contrast">+ {props.count}+ </span>+ </Show>+ );+}++/**+ * A label heading inside the Channels section: the name, how many of+ * its channels are unread, a `···` menu, and the disclosure caret. Clicking+ * the row toggles it, like a section heading; the state is per user. Edits+ * explain their scope in a dialog, so the menu stays plain.+ */+export function ChannelLabelRow(props: { label: ChannelLabel }) {+ const rail = useChannelsRail();+ const state = useChannelRailLabelState(() => props.label);+ const droppable = createDroppable(+ `${rail.railId}:channel-label:label:${props.label.id}`,+ {+ dragType: 'channel-label-target',+ dndScope: rail.railId,+ target: {+ kind: props.label.rule ? 'smart-tag' : 'label',+ labelId: props.label.id,+ },+ isDropTargetDisabled: () => !rail.labelsAvailable(),+ } satisfies ChannelLabelDropData+ );++ const isDropTarget = () => {+ const target = rail.activeDropTarget();+ return target?.kind === 'label' && target.labelId === props.label.id;+ };++ return (+ <div+ ref={droppable.ref}+ class={cn(+ 'group/channel-label relative min-w-0 rounded-lg pb-0.5',+ isDropTarget() && 'bg-selected'+ )}+ >+ <ViewSidebar.Item+ as="div"+ id={state().domId}+ role="treeitem"+ tabIndex={-1}+ title={+ props.label.rule+ ? `Name contains “${props.label.rule.contains}”`+ : props.label.name+ }+ aria-expanded={state().open}+ class={cn(+ 'pr-15 font-medium',+ !isTouchDevice() && state().focused && 'bg-hover text-ink'+ )}+ onMouseDown={(event) => {+ if (!isPrimaryMouseDown(event)) return;+ event.preventDefault();+ rail.activateRow(rowKeyForLabel(props.label.id), event);+ }}+ >+ <span class="min-w-0 flex-1 truncate">{props.label.name}</span>+ <UnreadPill count={state().unreadCount} />+ </ViewSidebar.Item>+ <span class="absolute right-(--sidebar-action-inset) top-1/2 flex -translate-y-1/2 items-center gap-0.5">+ <Dropdown placement="bottom-end">+ <Dropdown.Trigger+ as={ViewSidebar.Control}+ variant="ghost"+ size="icon-sm"+ label={`Options for ${props.label.name}`}+ class="opacity-0 transition-opacity group-hover/channel-label:opacity-100 focus-visible:opacity-100 data-expanded:opacity-100 touch:opacity-100"+ onMouseDown={(event: MouseEvent) => event.stopPropagation()}+ >+ <DotsThreeIcon class="size-3.5" />+ </Dropdown.Trigger>+ <Dropdown.Content+ class="min-w-44"+ onCloseAutoFocus={(event) => {+ if (document.querySelector('[role="dialog"]'))+ event.preventDefault();+ }}+ >+ <Dropdown.Group>+ <MenuRow+ icon={PencilSimpleIcon}+ label={props.label.rule ? 'Edit smart label' : 'Rename'}+ onSelect={() =>+ void (props.label.rule+ ? rail.editSmartTag(props.label)+ : rail.renameLabel(props.label))+ }+ />+ <MenuRow+ icon={ChecksIcon}+ label="Mark all as read"+ disabled={state().unreadCount === 0}+ onSelect={() => rail.markLabelRead(props.label)}+ />+ </Dropdown.Group>+ <Dropdown.Separator class="my-1 h-px border-0 bg-edge-muted" />+ <Dropdown.Group>+ <MenuRow+ icon={TrashIcon}+ label={props.label.rule ? 'Delete smart label' : 'Delete label'}+ onSelect={() => void rail.deleteLabel(props.label)}+ />+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ <ViewSidebar.Control+ label={`${state().open ? 'Collapse' : 'Expand'} ${props.label.name}`}+ aria-expanded={state().open}+ onMouseDown={(event) => event.stopPropagation()}+ onClick={() => rail.toggleLabel(props.label.id)}+ >+ <CaretDownIcon+ class={cn(+ 'size-3 transition-transform -rotate-90',+ state().open && 'rotate-0'+ )}+ />+ </ViewSidebar.Control>+ </span>+ </div>+ );+}++/** The Channels section's create action: a channel, or a label. */+export function ChannelsCreateMenu() {+ const rail = useChannelsRail();++ return (+ <Show+ when={rail.channelTagsEnabled()}+ fallback={+ <ViewSidebar.Control+ label="Create channel"+ onClick={openNewChannelModal}+ >+ <PlusIcon class="size-3.5" />+ </ViewSidebar.Control>+ }+ >+ <Dropdown placement="bottom-end">+ <Dropdown.Trigger+ as={ViewSidebar.Control}+ variant="ghost"+ size="icon-sm"+ label="Create channel or label"+ >+ <PlusIcon class="size-3.5" />+ </Dropdown.Trigger>+ <Dropdown.Content+ class="min-w-44"+ onCloseAutoFocus={(event) => {+ if (document.querySelector('[role="dialog"]'))+ event.preventDefault();+ }}+ >+ <Dropdown.Group>+ <MenuRow+ icon={HashIcon}+ label="New channel"+ onSelect={openNewChannelModal}+ />+ <MenuRow+ icon={TagIcon}+ label="New label"+ disabled={!rail.labelsAvailable()}+ onSelect={() => void rail.createLabel([])}+ />+ <MenuRow+ icon={FilterIcon}+ label="New smart label"+ disabled={!rail.labelsAvailable()}+ onSelect={() => void rail.createSmartTag()}+ />+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ </Show>+ );+}++/**+ * "Move to label" for a channel's context menu. Includes empty labels.+ */+export function ChannelLabelMenuItems(props: { channel: ChannelEntity }) {+ const rail = useChannelsRail();+ const currentLabel = () =>+ rail+ .labels()+ .find(+ (label) => !label.rule && label.channelIds.includes(props.channel.id)+ );++ return (+ <Show+ when={+ rail.channelTagsEnabled() &&+ !isDirectMessage(props.channel) &&+ rail.labelsAvailable()+ }+ >+ <Show when={currentLabel()}>+ {(label) => (+ <MenuItem+ icon={TagSimpleIcon}+ text={`Ungroup from “${label().name}”`}+ onClick={() => rail.setChannelLabel(props.channel.id, undefined)}+ />+ )}+ </Show>+ <ContextMenu.Sub>+ <SubTrigger+ icon={TagIcon}+ text={currentLabel() ? 'Move to label' : 'Add to label'}+ />+ <ContextMenuContent submenu class="w-56 text-xs text-ink-muted">+ {/* Kobalte radio items only work inside a RadioGroup. */}+ <ContextMenu.RadioGroup+ value={currentLabel()?.id ?? ''}+ onChange={(labelId) =>+ rail.setChannelLabel(props.channel.id, labelId)+ }+ >+ <For each={rail.labels().filter((label) => !label.rule)}>+ {(label) => (+ <MenuItem+ selectorType="radio"+ value={label.id}+ groupValue={currentLabel()?.id ?? ''}+ text={label.name}+ />+ )}+ </For>+ </ContextMenu.RadioGroup>+ <Show when={rail.labels().some((label) => !label.rule)}>+ <MenuSeparator />+ </Show>+ <MenuItem+ icon={PlusIcon}+ text="New label…"+ onClick={() => void rail.createLabel([props.channel.id])}+ />+ </ContextMenuContent>+ </ContextMenu.Sub>+ </Show>+ );+}diff --git a/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsx b/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsxindex 1151005f4a..3f2515ff3c 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelRailItems.tsx@@ -21,7 +21,7 @@ import PhoneCallIcon from '@phosphor-fill/phone-call-fill.svg';import PhoneIncomingIcon from '@phosphor-fill/phone-incoming-fill.svg';import { getBotDisplayName } from '@queries/messages/message-sender';import { Button, cn, Tooltip } from '@ui';-import { Match, type ParentProps, Show, Switch } from 'solid-js';+import { type JSX, Match, type ParentProps, Show, Switch } from 'solid-js';import { formatDetailedTimestamp, isDirectMessage } from '../../utils';import { rowKeyForChannel, useChannelsRail } from './ChannelsRailContext';@@ -59,6 +59,8 @@ export function ChannelRailItemContextMenu(props: ParentProps<{channel: ChannelEntity;class?: string;+ /** Rail-specific items shown after the entity actions. */+ extraItems?: JSX.Element;}>) {const rail = useChannelsRail();@@ -74,6 +76,7 @@ export function ChannelRailItemContextMenu(selectedEntities={() => []}viewContext={CHANNEL_ACTION_VIEW_CONTEXT}class={props.class}+ extraItems={props.extraItems}onOpenChange={(open) => {if (!open) return;diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsxindex 5e30715be6..de4f635004 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx@@ -9,40 +9,67 @@ import {useViewTabHotkeys,} from '@app/components/view-shell';import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { favoriteSplitContent } from '@app/util/favorites';+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { useSplitLayout } from '@components/app/split-layout/layout';import {useSplitPanelOrThrow,withSplitPanelOwner,} from '@components/app/split-layout/layoutUtils';+import { toast } from '@core/component/Toast/Toast';+import { enableChannelTags } from '@core/constant/featureFlags';import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';import { debouncedDependent } from '@core/util/debounce';+import { thrownResultErrorHasCode } from '@core/util/result';import { type ChannelEntity, isChannelEntity, type WithSearch } from '@entity';+import { notificationIsRead } from '@entity/utils/notification';+import {+ useChannelLabelsQuery,+ useCreateChannelLabelMutation,+ useDeleteChannelLabelMutation,+ useRenameChannelLabelMutation,+ useSetChannelLabelMutation,+} from '@queries/channel-labels/channel-labels';import { useFavoritesData } from '@queries/favorites/favorites';import { useSearchSoupQuery } from '@queries/soup/search';import type { EntityFilters } from '@service-search/generated/models';-import type { Favorite } from '@service-storage/generated/schemas/favorite';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';import { debounce } from '@solid-primitives/scheduled';+import { useDragDropContext } from '@thisbeyond/solid-dnd';+import { confirmDialog } from '@ui';import {createEffect,createMemo,createSignal,createUniqueId,+ getOwner,onCleanup,} from 'solid-js';import type { VirtualizerHandle } from 'virtua/solid';import { useChannelsView } from '../../channels-view-context';+import { resolveSmartTagMemberships } from '../../core/smart-tags';import {type ChannelsSourceScope,type ChannelsSources,deduplicateChannels,+ useChannelsByIdsQuery,} from '../../queries';import type {ChannelsQueryScope,ChannelsRailSection,ChannelsTab,} from '../../types';+import { isDirectMessage } from '../../utils';+import {+ buildChannelRailRows,+ buildChannelSectionRows,+} from './build-channel-rail-rows';+import { promptLabelName } from './ChannelLabelNameDialog';import {+ type ChannelLabelDragData,+ type ChannelLabelDropData,+ type ChannelLabelDropTarget,type ChannelRailActivationMetadata,type ChannelRailRow,type ChannelsRailContext,@@ -50,17 +77,24 @@ import {domIdForRow,rowKeyForChannel,rowKeyForFavorite,+ rowKeyForLabel,rowKeyForSection,} from './ChannelsRailContext';import { ExpandedChannelsRail } from './ExpandedChannelsRail';+import { promptSmartTag } from './SmartTagDialog';++export { buildChannelRailRows } from './build-channel-rail-rows';+import { useChannelCalls } from './hooks/useChannelCalls';import { useChannelRailActivity } from './hooks/useChannelRailActivity';const CHANNEL_RAIL_SECTIONS: ChannelsRailSection[] = ['favorites',+ 'unread','channels','direct_messages',];+const LABEL_KEY_PREFIX = 'label:';const BROWSE_QUERY_SCOPES = ['channels', 'direct_messages'] as const;const CHANNEL_TAB_IDS: ChannelsTab[] = ['browse', 'recents'];const DM_LOADING_PREVIEW_OFFSET = 80;@@ -75,98 +109,22 @@ export type ChannelsRailProps = {onSearchOpenChange: (open: boolean) => void;};-type ChannelRailItemsByScope = Record<- ChannelsQueryScope,- readonly ChannelEntity[]-> & {- favorites: readonly Favorite[];-};--export function buildChannelRailRows(- tab: ChannelsTab,- expandedGroups: Record<ChannelsRailSection, boolean>,- items: ChannelRailItemsByScope-): ChannelRailRow[] {- if (tab === 'recents') {- return items.recents.map((channel, localIndex) => ({- kind: 'conversation',- id: `channel:${channel.id}`,- scope: 'recents',- localIndex,- channel,- }));- }-- const rows: ChannelRailRow[] = [];- if (items.favorites.length > 0) {- rows.push({- kind: 'section',- id: 'section:favorites',- group: 'favorites',- });- if (expandedGroups.favorites) {- rows.push(- ...items.favorites.map(- (favorite): ChannelRailRow => ({- kind: 'favorite',- id: rowKeyForFavorite(favorite),- group: 'favorites',- favorite,- })- )- );- }- }-- rows.push({- kind: 'section',- id: 'section:channels',- group: 'channels',- });- if (expandedGroups.channels) {- rows.push(- ...items.channels.map(- (channel, localIndex): ChannelRailRow => ({- kind: 'conversation',- id: `channel:${channel.id}`,- group: 'channels',- scope: 'channels',- localIndex,- channel,- })- )- );- }-- rows.push({- kind: 'section',- id: 'section:direct_messages',- group: 'direct_messages',- });- if (expandedGroups.direct_messages) {- rows.push(- ...items.direct_messages.map(- (channel, localIndex): ChannelRailRow => ({- kind: 'conversation',- id: `channel:${channel.id}`,- group: 'direct_messages',- scope: 'direct_messages',- localIndex,- channel,- })- )- );- }-- return rows;-}-export function ChannelsRail(props: ChannelsRailProps) {- const { state, setGroupOpen, setSelectedChannelId, setSortBy, setTab } =- useChannelsView();+ const channelTagsFlag = useFeatureFlag(enableChannelTags);+ const channelTagsEnabled = () => channelTagsFlag().enabled;+ const {+ state,+ setGroupOpen,+ setLabelOpen,+ setSelectedChannelId,+ setSortBy,+ setTab,+ } = useChannelsView();const panel = useSplitPanelOrThrow();const layout = useSplitLayout();+ const owner = getOwner();+ const notificationSource = useGlobalNotificationSource();const favoritesData = useFavoritesData({ entityType: ['channel'] });@@ -290,10 +248,95 @@ export function ChannelsRail(props: ChannelsRailProps) {}};- const channelActivity = useChannelRailActivity(channels, channelCalls);+ // Shared or private labels; channel membership is always viewer-relative.+ const labelsQuery = useChannelLabelsQuery();+ const labels = createMemo<readonly ChannelLabel[]>(() =>+ resolveSmartTagMemberships(+ channelTagsEnabled() && labelsQuery.isSuccess+ ? labelsQuery.data.labels+ : [],+ channels()+ )+ );+ const labelsAvailable = () => channelTagsEnabled() && labelsQuery.isSuccess;+ const labelsUnavailableReason = () => {+ if (labelsQuery.isSuccess) return '';+ if (labelsQuery.isPending) return 'Loading labels…';+ const error = labelsQuery.error;+ if (+ thrownResultErrorHasCode(error, 'UNAUTHORIZED') ||+ thrownResultErrorHasCode(error, 'FORBIDDEN')+ ) {+ return 'You do not have access to these labels.';+ }+ if (thrownResultErrorHasCode(error, 'NOT_FOUND')) {+ return 'Channel labels are not available on this server yet.';+ }+ return 'Channel labels are unavailable right now.';+ };++ // A labelled channel renders under its label even before the paginated+ // Channels source reaches it, so fetch the ones the sources have not loaded.+ const labelledChannelIds = createMemo(() => [+ ...new Set(labels().flatMap((label) => label.channelIds)),+ ]);+ const missingLabelledIds = createMemo(() => {+ const loaded = new Set(channels().map((channel) => channel.id));+ return labelledChannelIds().filter((id) => !loaded.has(id));+ });+ const labelledChannelsQuery = useChannelsByIdsQuery(missingLabelledIds);+ const labelledChannels = createMemo<ChannelEntity[]>((previous) => {+ if (!channelTagsEnabled()) return [];+ if (!labelledChannelsQuery.isEnabled || labelledChannelsQuery.isLoading)+ return previous;+ return deduplicateChannels([+ (labelledChannelsQuery.data?.entities ?? []).filter(isChannelEntity),+ previous,+ ]);+ }, []);++ const allChannels = createMemo(() =>+ deduplicateChannels([channels(), labelledChannels()])+ );+ const channelsById = createMemo(+ () => new Map(allChannels().map((channel) => [channel.id, channel]))+ );++ const channelActivity = useChannelRailActivity(allChannels, channelCalls);const favorites = createMemo(() => favoritesData()?.favorites ?? []);+ const isLabelOpen = (labelId: string) =>+ !state.collapsedLabels.includes(labelId);++ const channelSectionRows = createMemo(() =>+ buildChannelSectionRows({+ labels: labels(),+ channels: deduplicateChannels([+ props.sources.channels.items(),+ labelledChannels(),+ ]),+ channelsById: channelsById(),+ isLabelOpen,+ })+ );++ // The Unread section is channels only; DMs keep their own section.+ const unreadChannels = createMemo(() =>+ channelActivity+ .unreadChannelOrder()+ .map((id) => channelsById().get(id))+ .filter(+ (channel): channel is ChannelEntity =>+ channel !== undefined && !isDirectMessage(channel)+ )+ );++ const labelUnreadCount = (label: ChannelLabel) => {+ const unread = channelActivity.unreadChannelIds();+ return label.channelIds.filter((id) => unread.has(id)).length;+ };+const visibleRows = createMemo(() => {if (props.searchOpen) {return searchResults().map(@@ -307,12 +350,18 @@ export function ChannelsRail(props: ChannelsRailProps) {);}- return buildChannelRailRows(state.tab, state.expandedGroups, {- favorites: favorites(),- channels: props.sources.channels.items(),- direct_messages: props.sources.direct_messages.items(),- recents: props.sources.recents.items(),- });+ return buildChannelRailRows(+ state.tab,+ state.expandedGroups,+ {+ favorites: favorites(),+ unread: unreadChannels(),+ channels: props.sources.channels.items(),+ direct_messages: props.sources.direct_messages.items(),+ recents: props.sources.recents.items(),+ },+ channelSectionRows()+ );});const list = withSplitPanelOwner(listOwnedSlotName('controller'), () =>@@ -323,7 +372,11 @@ export function ChannelsRail(props: ChannelsRailProps) {initialFocusKey:state.selectedChannelId === undefined? undefined- : rowKeyForChannel(state.selectedChannelId),+ : visibleRows().find(+ (row) =>+ row.kind === 'conversation' &&+ row.channel.id === state.selectedChannelId+ )?.id,onActivate: ({ item, metadata }) => {previewAfterNavigation.clear();const openInNewSplit =@@ -334,6 +387,11 @@ export function ChannelsRail(props: ChannelsRailProps) {return;}+ if (item.kind === 'label') {+ setLabelOpen(item.label.id, !isLabelOpen(item.label.id));+ return;+ }+if (item.kind === 'favorite' &&item.favorite.entityType !== 'channel'@@ -366,8 +424,9 @@ export function ChannelsRail(props: ChannelsRailProps) {const row = list.items.at(index);if (!row) return;- if (row.kind === 'conversation') {- const virtualizer = virtualizers()[row.scope];+ if (row.kind === 'conversation' || row.kind === 'label') {+ const virtualizer =+ virtualizers()[row.kind === 'label' ? 'channels' : row.scope];if (virtualizer) {virtualizer.scrollToIndex(row.localIndex, options);return;@@ -379,11 +438,13 @@ export function ChannelsRail(props: ChannelsRailProps) {? listRoot(): row.kind === 'favorite'? sectionScrollRoots().favorites- : row.kind === 'conversation' && row.group- ? sectionScrollRoots()[row.group]- : state.tab === 'recents'- ? listRoot()- : undefined;+ : row.kind === 'unread'+ ? sectionScrollRoots().unread+ : row.kind === 'conversation' && row.group+ ? sectionScrollRoots()[row.group]+ : state.tab === 'recents'+ ? listRoot()+ : undefined;if (!element || !scrollRoot) return;const elementBounds = element.getBoundingClientRect();@@ -397,16 +458,21 @@ export function ChannelsRail(props: ChannelsRailProps) {};const scrollScopeToSelectedOrStart = (scope: ChannelsQueryScope) => {- const items = props.sources[scope].items();+ // The Channels section renders label headings between channels, so its+ // indexes come from the rendered rows rather than the source.+ const rendered =+ scope === 'channels'+ ? channelSectionRows().map((row) =>+ row.kind === 'conversation' ? row.channel.id : undefined+ )+ : props.sources[scope].items().map((channel) => channel.id);- const selectedIndex = items.findIndex(- (channel) => channel.id === state.selectedChannelId- );+ const selectedIndex = rendered.indexOf(state.selectedChannelId ?? '');const targetIndex = selectedIndex >= 0 ? selectedIndex : 0;const virtualizer = virtualizers()[scope];- if (virtualizer && items.length > 0) {+ if (virtualizer && rendered.length > 0) {virtualizer.scrollToIndex(targetIndex, {align: selectedIndex >= 0 ? 'nearest' : 'start',});@@ -524,7 +590,11 @@ export function ChannelsRail(props: ChannelsRailProps) {if (direction !== 1 || row?.kind !== 'conversation') return true;const source = props.sources[row.scope];- if (row.localIndex < source.items().length - 1) return true;+ const renderedCount =+ row.scope === 'channels'+ ? channelSectionRows().length+ : source.items().length;+ if (row.localIndex < renderedCount - 1) return true;if (!source.isLoadingMore()) {if (!source.hasMore()) return true;@@ -562,7 +632,7 @@ export function ChannelsRail(props: ChannelsRailProps) {previewAfterNavigation.clear();const row = event.result?.item;- if (row?.kind === 'conversation') {+ if (row?.kind === 'conversation' || row?.kind === 'unread') {previewAfterNavigation(row.channel.id);} else if (row?.kind === 'favorite' &&@@ -576,13 +646,27 @@ export function ChannelsRail(props: ChannelsRailProps) {createMetadata: (intent) => ({ newSplit: intent === 'alternate' }),alternateDescription: 'Open in new split',},+ // Labels disclose like sections: `h`/`l` on a label heading or one of+ // its channels collapse or expand that label; anywhere else, the section.disclosure: {- getKey: (row) => row.group,- isExpanded: (group) =>- state.expandedGroups[group as ChannelsRailSection],- setExpanded: (group, expanded) =>- setGroupOpen(group as ChannelsRailSection, expanded),- getFocusKey: (group) => rowKeyForSection(group as ChannelsRailSection),+ getKey: (row) =>+ row.kind === 'label'+ ? row.id+ : row.kind === 'conversation' && row.labelId+ ? rowKeyForLabel(row.labelId)+ : row.group,+ isExpanded: (key) =>+ key.startsWith(LABEL_KEY_PREFIX)+ ? isLabelOpen(key.slice(LABEL_KEY_PREFIX.length))+ : state.expandedGroups[key as ChannelsRailSection],+ setExpanded: (key, expanded) =>+ key.startsWith(LABEL_KEY_PREFIX)+ ? setLabelOpen(key.slice(LABEL_KEY_PREFIX.length), expanded)+ : setGroupOpen(key as ChannelsRailSection, expanded),+ getFocusKey: (key) =>+ key.startsWith(LABEL_KEY_PREFIX)+ ? rowKeyForLabel(key.slice(LABEL_KEY_PREFIX.length))+ : rowKeyForSection(key as ChannelsRailSection),},}));@@ -590,10 +674,13 @@ export function ChannelsRail(props: ChannelsRailProps) {const jumpToSection = (offset: 1 | -1) => {const currentGroup = list.focus.item()?.group;- const sections =- favorites().length > 0- ? CHANNEL_RAIL_SECTIONS- : CHANNEL_RAIL_SECTIONS.filter((section) => section !== 'favorites');+ const sections = CHANNEL_RAIL_SECTIONS.filter((section) =>+ section === 'favorites'+ ? favorites().length > 0+ : section === 'unread'+ ? unreadChannels().length > 0+ : true+ );const currentIndex = currentGroup ? sections.indexOf(currentGroup) : -1;const origin = currentIndex === -1 ? (offset === 1 ? -1 : 0) : currentIndex;@@ -638,6 +725,285 @@ export function ChannelsRail(props: ChannelsRailProps) {});};+ // Explain shared versus private scope before creating or changing labels.+ const createLabelMutation = useCreateChannelLabelMutation();+ const renameLabelMutation = useRenameChannelLabelMutation();+ const deleteLabelMutation = useDeleteChannelLabelMutation();+ const setChannelLabelMutation = useSetChannelLabelMutation();++ const errorMessage = (error: unknown, fallback: string) => {+ if (+ thrownResultErrorHasCode(error, 'UNAUTHORIZED') ||+ thrownResultErrorHasCode(error, 'FORBIDDEN')+ ) {+ return 'You do not have access to these labels.';+ }+ const message = error instanceof Error ? error.message : '';+ return message || fallback;+ };+ const channelName = (channelId: string) => {+ const name = channelsById().get(channelId)?.name;+ return name ? `#${name}` : 'the channel';+ };++ const sharedLabels = () =>+ labelsQuery.isSuccess && Boolean(labelsQuery.data.teamId);+ const labelScopeDescription = () =>+ sharedLabels()+ ? 'Labels are shared with everyone on your team.'+ : 'Labels are private to your account.';++ const createLabel = async (channelIds: string[]) => {+ if (!channelTagsEnabled()) return;+ if (!labelsAvailable()) {+ toast.failure(labelsUnavailableReason());+ return;+ }+ const names = channelIds+ .map((id) => channelsById().get(id)?.name)+ .filter((name): name is string => Boolean(name))+ .map((name) => `#${name}`);+ const grouping =+ names.length > 1+ ? ` It will start with ${names.slice(0, -1).join(', ')} and ${names.at(-1)}.`+ : names.length === 1+ ? ` It will start with ${names[0]}.`+ : '';+ const name = await promptLabelName(+ {+ title: 'New label',+ body: `${labelScopeDescription()}${grouping}`,+ confirmLabel: 'Create label',+ onConfirm: async (name) => {+ if (!channelTagsEnabled())+ throw new Error('Channel tags are disabled.');+ const created = await createLabelMutation.mutateAsync({+ name,+ channelIds,+ });+ setGroupOpen('channels', true);+ setLabelOpen(created.id, true);+ },+ },+ { owner }+ );+ if (!name) return;+ toast.success(+ channelIds.length > 1+ ? `Grouped ${channelIds.length} channels under “${name}”`+ : `Created “${name}”`+ );+ };++ const createSmartTag = async () => {+ if (!channelTagsEnabled()) return;+ if (!labelsAvailable()) {+ toast.failure(labelsUnavailableReason());+ return;+ }+ await promptSmartTag(+ {+ scopeDescription: labelScopeDescription(),+ onConfirm: async (name, rule) => {+ if (!channelTagsEnabled())+ throw new Error('Channel tags are disabled.');+ const created = await createLabelMutation.mutateAsync({+ name,+ rule,+ channelIds: [],+ });+ setGroupOpen('channels', true);+ setLabelOpen(created.id, true);+ toast.success(`Created “${name}”`);+ },+ },+ { owner }+ );+ };++ const editSmartTag = async (label: ChannelLabel) => {+ if (!channelTagsEnabled() || !label.rule) return;+ await promptSmartTag(+ {+ scopeDescription: labelScopeDescription(),+ initial: { name: label.name, rule: label.rule },+ onConfirm: async (name, rule) => {+ if (!channelTagsEnabled())+ throw new Error('Channel tags are disabled.');+ await renameLabelMutation.mutateAsync({+ labelId: label.id,+ name,+ rule,+ });+ toast.success(`Updated “${name}”`);+ },+ },+ { owner }+ );+ };++ const renameLabel = async (label: ChannelLabel) => {+ if (!channelTagsEnabled()) return;+ const name = await promptLabelName(+ {+ title: 'Rename label',+ body: labelScopeDescription(),+ confirmLabel: 'Rename',+ initialValue: label.name,+ onConfirm: async (name) => {+ if (!channelTagsEnabled())+ throw new Error('Channel tags are disabled.');+ await renameLabelMutation.mutateAsync({ labelId: label.id, name });+ },+ },+ { owner }+ );+ if (!name || name === label.name) return;+ toast.success(`Renamed to “${name}”`);+ };++ const deleteLabel = async (label: ChannelLabel) => {+ if (!channelTagsEnabled()) return;+ const channelsText = label.rule+ ? 'Channels stop appearing in this smart label. Other labels are unchanged.'+ : label.channelCount === 0+ ? 'It has no channels in it.'+ : label.channelCount === 1+ ? 'Its 1 channel goes back to the main Channels list.'+ : `Its ${label.channelCount} channels go back to the main Channels list.`;+ const confirmed = await confirmDialog(+ {+ title: `Delete “${label.name}”?`,+ body: `${labelScopeDescription()} ${channelsText} Nobody loses access to a channel.`,+ confirmLabel: sharedLabels() ? 'Delete for everyone' : 'Delete label',+ cancelLabel: 'Cancel',+ tone: 'danger',+ },+ { owner }+ );+ if (!confirmed || !channelTagsEnabled()) return;+ try {+ await deleteLabelMutation.mutateAsync({ labelId: label.id });+ toast.success(`Deleted “${label.name}”`);+ } catch (error) {+ toast.failure(errorMessage(error, 'Failed to delete label'));+ }+ };++ const setChannelLabel = (channelId: string, labelId: string | undefined) => {+ if (!channelTagsEnabled()) return;+ const from = labels().find(+ (label) => !label.rule && label.channelIds.includes(channelId)+ );+ const to = labelId+ ? labels().find((label) => label.id === labelId)+ : undefined;+ if (to?.rule || from?.id === labelId) return;+ if (labelId) setLabelOpen(labelId, true);+ setChannelLabelMutation.mutate(+ { channelId, labelId },+ {+ onSuccess: () => {+ if (to) {+ toast.success(`Moved ${channelName(channelId)} to “${to.name}”`);+ } else if (from) {+ toast.success(+ `Removed ${channelName(channelId)} from “${from.name}”`+ );+ }+ },+ onError: (error) =>+ toast.failure(errorMessage(error, 'Failed to move channel')),+ }+ );+ };++ const markLabelRead = (label: ChannelLabel) => {+ if (!channelTagsEnabled()) return;+ const channelIds = new Set(label.channelIds);+ const unread = notificationSource+ .notifications()+ .filter(+ (notification) =>+ notification.entity_type === 'channel' &&+ channelIds.has(notification.entity_id) &&+ !notificationIsRead(notification)+ );+ if (unread.length > 0) void notificationSource.bulkMarkAsRead(unread);+ };++ // Drops are resolved here rather than per row so a channel dragged from+ // anywhere in the section lands the same way.+ const [dndState, dndActions] = useDragDropContext() ?? [];+ // The highlight follows the whole target (a label with all its rows), not+ // the row under the cursor, so rows read this instead of their own state.+ const activeDropTarget = (): ChannelLabelDropTarget | undefined => {+ if (!channelTagsEnabled()) return undefined;+ const drag = dndState?.active.draggable?.data as+ | ChannelLabelDragData+ | undefined;+ if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId)+ return undefined;+ const drop = dndState?.active.droppable?.data as+ | ChannelLabelDropData+ | undefined;+ if (+ drop?.dragType !== 'channel-label-target' ||+ drop.dndScope !== listDomId+ )+ return undefined;+ if (drop.target.kind === 'smart-tag') return undefined;+ if (+ drop.target.kind === 'channel' &&+ drop.target.channelId === drag.channelId+ )+ return undefined;+ if (drop.target.kind === 'label' && drop.target.labelId === drag.labelId)+ return undefined;+ if (drop.target.kind === 'unlabelled' && !drag.labelId) return undefined;+ return drop.target;+ };+ dndActions?.onDragEnd(({ draggable, droppable }) => {+ if (!channelTagsEnabled()) return;+ const drag = draggable?.data as ChannelLabelDragData | undefined;+ if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId)+ return;+ // With labels unavailable every target reports itself disabled, so the+ // drag ends on nothing; say why rather than silently doing nothing.+ if (!labelsAvailable()) {+ toast.failure(labelsUnavailableReason());+ return;+ }+ if (!droppable) return;+ const drop = droppable.data as ChannelLabelDropData | undefined;+ if (+ drop?.dragType !== 'channel-label-target' ||+ drop.dndScope !== listDomId+ )+ return;++ const target = drop.target;+ if (target.kind === 'smart-tag') return;+ if (target.kind === 'label') {+ if (drag.labelId !== target.labelId) {+ setChannelLabel(drag.channelId, target.labelId);+ }+ return;+ }+ if (target.kind === 'unlabelled') {+ if (drag.labelId) setChannelLabel(drag.channelId, undefined);+ return;+ }+ if (target.channelId === drag.channelId) return;+ // Dragging a labelled channel onto the plain list takes it out of its+ // label; dropping one plain channel on another starts a label with both.+ if (drag.labelId) {+ setChannelLabel(drag.channelId, undefined);+ return;+ }+ void createLabel([drag.channelId, target.channelId]);+ });+const registerVirtualizer = (scope: ChannelsSourceScope,handle: VirtualizerHandle@@ -665,6 +1031,23 @@ export function ChannelsRail(props: ChannelsRailProps) {selectedChannelId: () => state.selectedChannelId,isGroupOpen: (group) => state.expandedGroups[group],toggleGroup: (group) => setGroupOpen(group, !state.expandedGroups[group]),+ channelTagsEnabled,+ labels,+ labelsAvailable,+ labelsUnavailableReason,+ isLabelOpen,+ toggleLabel: (labelId) => setLabelOpen(labelId, !isLabelOpen(labelId)),+ channelSectionRows,+ unreadChannels,+ labelUnreadCount,+ createLabel,+ createSmartTag,+ editSmartTag,+ renameLabel,+ deleteLabel,+ setChannelLabel,+ activeDropTarget,+ markLabelRead,sortBy: (group) => state.sortBy[group],setSortBy,registerRootRef: setListRoot,diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.tsindex 62d4c42123..9fda4c6b88 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts@@ -1,6 +1,7 @@import type { ListController } from '@app/components/list';import { createAssertedContextProvider } from '@core/context/createContext';import type { ChannelEntity } from '@entity';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';import type { Favorite } from '@service-storage/generated/schemas/favorite';import type { ContextProviderProps } from '@solid-primitives/context';import type { Accessor } from 'solid-js';@@ -28,17 +29,76 @@ export type ChannelRailRow =group: 'favorites';favorite: Favorite;}+ | {+ /** A channel in the flat Unread list; the same channel also has a `conversation` row. */+ kind: 'unread';+ id: `unread:${string}`;+ group: 'unread';+ localIndex: number;+ channel: ChannelEntity;+ }+ | {+ /** A team channel label heading inside the Channels section. */+ kind: 'label';+ id: `label:${string}`;+ group: 'channels';+ /** Index in the Channels section's rendered rows (labels and channels). */+ localIndex: number;+ label: ChannelLabel;+ }| {kind: 'conversation';id: `channel:${string}`;group?: ChannelsGroup;scope: ChannelsSourceScope;+ /**+ * Index in the scope's rendered list. For `channels` that list mixes+ * label headings and channels, so it is not an index into the source.+ */localIndex: number;channel: ChannelEntity;+ /** The label this row is nested under, when any. */+ labelId?: string;};-export const rowKeyForChannel = (channelId: string) =>- `channel:${channelId}` as const;+/**+ * One rendered row of the Channels section: a label heading or a channel,+ * nested (`labelId` set) or in the plain list below the labels.+ */+export type ChannelSectionRow =+ | { kind: 'label'; label: ChannelLabel }+ | { kind: 'conversation'; channel: ChannelEntity; labelId?: string };++/** Payload of a channel row being dragged to or out of a label (solid-dnd). */+export type ChannelLabelDragData = {+ dragType: 'channel-label';+ dndScope: string;+ channelId: string;+ /** The label the channel is currently in, when any. */+ labelId?: string;+ /** Shown by the global drag overlay. */+ name: string;+ iconType: 'channel';+};++/** Where a dragged channel may land. */+export type ChannelLabelDropTarget =+ | { kind: 'label'; labelId: string }+ | { kind: 'smart-tag'; labelId: string }+ | { kind: 'channel'; channelId: string }+ | { kind: 'unlabelled' };++/** Payload of a drop target in the Channels section (solid-dnd). */+export type ChannelLabelDropData = {+ dragType: 'channel-label-target';+ dndScope: string;+ target: ChannelLabelDropTarget;+ /** Read by the `pointerWithin` collision detector. */+ isDropTargetDisabled: () => boolean;+};++export const rowKeyForChannel = (channelId: string, labelId?: string) =>+ `channel:${channelId}${labelId ? `:label:${labelId}` : ''}` as const;export const rowKeyForFavorite = (favorite: Favorite) =>`favorite:${favorite.entityType}:${favorite.entityId}` as const;@@ -46,6 +106,11 @@ export const rowKeyForFavorite = (favorite: Favorite) =>export const rowKeyForSection = (group: ChannelsRailSection) =>`section:${group}` as const;+export const rowKeyForLabel = (labelId: string) => `label:${labelId}` as const;++export const rowKeyForUnread = (channelId: string) =>+ `unread:${channelId}` as const;+export const domIdForRow = (railId: string, rowId: string) =>`${railId}-${rowId}`;@@ -64,6 +129,39 @@ export type ChannelsRailContext = {selectedChannelId: Accessor<string | undefined>;isGroupOpen: (group: ChannelsRailSection) => boolean;toggleGroup: (group: ChannelsRailSection) => void;+ /** Whether channel labels and smart tags are enabled for this user. */+ channelTagsEnabled: Accessor<boolean>;+ /** Every label in the authorized scope, including empty labels. */+ labels: Accessor<readonly ChannelLabel[]>;+ /** Whether labels can be used after loading successfully. */+ labelsAvailable: Accessor<boolean>;+ /** Why labels are unavailable, for the create menu and refused drops. */+ labelsUnavailableReason: Accessor<string>;+ isLabelOpen: (labelId: string) => boolean;+ toggleLabel: (labelId: string) => void;+ /** The Channels section's rendered rows: label headings and channels. */+ channelSectionRows: Accessor<readonly ChannelSectionRow[]>;+ /** Channels with unread activity, newest first, for the Unread section. */+ unreadChannels: Accessor<readonly ChannelEntity[]>;+ /** Number of channels in the label with unread activity. */+ labelUnreadCount: (label: ChannelLabel) => number;+ /**+ * Create a label holding `channelIds`, after asking for a name in a dialog+ * that states the team-wide effect. Resolves once the request settles.+ */+ createSmartTag: () => Promise<void>;+ editSmartTag: (label: ChannelLabel) => Promise<void>;+ createLabel: (channelIds: string[]) => Promise<void>;+ /** Rename after asking for the new name in a dialog; applies to the whole team. */+ renameLabel: (label: ChannelLabel) => Promise<void>;+ /** Delete after the user confirms; applies to the whole team. */+ deleteLabel: (label: ChannelLabel) => Promise<void>;+ /** Move a channel into a label, or out of any label (`undefined`). */+ setChannelLabel: (channelId: string, labelId: string | undefined) => void;+ /** Where a dragged channel would land right now, for highlighting the whole target. */+ activeDropTarget: Accessor<ChannelLabelDropTarget | undefined>;+ /** Mark every unread notification in the label's visible channels read. */+ markLabelRead: (label: ChannelLabel) => void;sortBy: (group: ChannelsGroup) => ChannelListSort;setSortBy: (group: ChannelsGroup, sort: ChannelListSort) => void;registerRootRef: (element: HTMLDivElement) => void;diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsxindex 03cf24cf03..bba5c31b8a 100644--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailSection.tsx@@ -135,10 +135,12 @@ function CollapsibleSectionHeader(props: {focused: boolean;focusWithin: boolean;class?: string;+ ref?: (element: HTMLElement) => void;children: JSX.Element;}) {return (<WorkspaceSection.Header+ ref={props.ref}class={cn('w-full rounded-lg text-xs leading-5 font-medium text-ink-muted transition-colors group-hover/sidebar-section:text-ink',props.focused && 'bg-hover text-ink-muted',diff --git a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsxindex cd68511b54..b3670098b1 100644--- a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx+++ b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx@@ -14,19 +14,30 @@ import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';import SortIcon from '@phosphor/sort-ascending.svg';import XIcon from '@phosphor/x.svg';import type { Favorite } from '@service-storage/generated/schemas/favorite';+import {+ createDraggable,+ createDroppable,+ useDragDropContext,+} from '@thisbeyond/solid-dnd';import { cn, Dropdown, EmptyStatePanel, Hotkey, Tabs, Tooltip } from '@ui';import {type Accessor,createSignal,For,+ type JSX,Match,Show,Switch,} from 'solid-js';-import { Virtualizer } from 'virtua/solid';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';import type { ChannelListSort, ChannelsGroup } from '../../types';import { channelMentionsUser, formatDetailedTimestamp } from '../../utils';import { ChannelsEmptyState } from '../ChannelsEmptyState';+import {+ ChannelLabelMenuItems,+ ChannelLabelRow,+ ChannelsCreateMenu,+} from './ChannelLabelRows';import {ChannelAvatar,ChannelCallIndicator,@@ -38,9 +49,14 @@ import {isPrimaryMouseDown,} from './ChannelRailItems';import {+ type ChannelLabelDragData,+ type ChannelLabelDropData,+ type ChannelRailRow,+ type ChannelSectionRow,domIdForRow,rowKeyForChannel,rowKeyForFavorite,+ rowKeyForUnread,useChannelsRail,} from './ChannelsRailContext';import {@@ -56,6 +72,7 @@ import {useChannelRailItemState,useChannelRailScopeState,useChannelRailSectionState,+ useChannelRailUnreadState,useChannelRailVirtualizer,} from './hooks/useChannelRailState';@@ -183,82 +200,263 @@ function FavoriteOption(props: { favorite: Favorite }) {);}-function ChannelOption(props: { channel: ChannelEntity }) {+/**+ * Drag a channel between labels. Registered once per Channels-section row: a+ * row is the drag source, and also a drop target that means "into this row's+ * label" (or "group these two" when the row is in no label).+ */+function createChannelLabelDnd(props: {+ channel: ChannelEntity;+ rowId: string;+ labelId: () => string | undefined;+ /** Drops are refused while the team's labels are unavailable. */+ disabled: () => boolean;+}) {const rail = useChannelsRail();- const item = useChannelRailItemState(() => props.channel.id);+ const draggable = createDraggable(+ `${rail.railId}:channel-label:drag:${props.rowId}`,+ {+ dragType: 'channel-label',+ dndScope: rail.railId,+ channelId: props.channel.id,+ get labelId() {+ return rail+ .labels()+ .find(+ (label) =>+ !label.rule && label.channelIds.includes(props.channel.id)+ )?.id;+ },+ name: props.channel.name,+ iconType: 'channel',+ } satisfies ChannelLabelDragData+ );+ const droppable = createDroppable(+ `${rail.railId}:channel-label:channel:${props.rowId}`,+ {+ dragType: 'channel-label-target',+ dndScope: rail.railId,+ get target() {+ const labelId = props.labelId();+ const label = rail.labels().find((label) => label.id === labelId);+ return labelId+ ? {+ kind: label?.rule ? ('smart-tag' as const) : ('label' as const),+ labelId,+ }+ : { kind: 'channel' as const, channelId: props.channel.id };+ },+ isDropTargetDisabled: props.disabled,+ } satisfies ChannelLabelDropData+ );+ return { draggable, droppable };+}++function ChannelOption(props: {+ channel: ChannelEntity;+ /** The list row this option stands for; defaults to the channel's own row. */+ rowId?: ChannelRailRow['id'];+ /** Nest under a label heading, with the branch rail. */+ labelId?: string;+ /** Keep the timestamp visible instead of revealing it on hover. */+ alwaysShowTimestamp?: boolean;+ /** Make the row draggable between labels (Channels section only). */+ draggable?: boolean;+}) {+ const rail = useChannelsRail();+ const rowId = () => props.rowId ?? rowKeyForChannel(props.channel.id);+ const item = useChannelRailItemState(() => props.channel.id, rowId);const timestamp = () =>props.channel.latestRootMessage?.createdAt ?? props.channel.updatedAt;+ // Whether a row participates in drag and drop is fixed per mount.+ const dnd = props.draggable+ ? createChannelLabelDnd({+ channel: props.channel,+ rowId: rowId(),+ labelId: () => props.labelId,+ disabled: () => !rail.labelsAvailable(),+ })+ : undefined;++ // Selection belongs to a click, never the press that starts a drag.+ let didDrag = false;+ const [, dragActions] = useDragDropContext() ?? [];+ dragActions?.onDragStart(({ draggable }) => {+ if (+ draggable.data.dndScope === rail.railId &&+ draggable.data.channelId === props.channel.id+ )+ didDrag = true;+ });++ // A plain row highlights alone (dropping on it groups the two); a row in a+ // label is highlighted as part of its whole label by ChannelsSectionRows.+ const isGroupingTarget = () => {+ const target = rail.activeDropTarget();+ return target?.kind === 'channel' && target.channelId === props.channel.id;+ };return (- <ChannelRailItemContextMenu channel={props.channel} class="block w-full">- <ViewSidebar.Item- as="div"- id={item().domId}- role="treeitem"- tabIndex={-1}- class={cn(- 'group/channel-option relative',- !item().selected &&- !isTouchDevice() &&- item().focused &&- 'bg-hover text-ink'- )}- active={item().selected && !isTouchDevice()}- aria-current={item().selected ? 'page' : undefined}- onMouseDown={(event) => {- if (!isPrimaryMouseDown(event)) return;- rail.activateRow(rowKeyForChannel(props.channel.id), event);- }}+ <div+ ref={(element) => {+ dnd?.draggable.ref(element);+ dnd?.droppable.ref(element);+ }}+ {...(dnd?.draggable.dragActivators ?? {})}+ onPointerDown={() => {+ didDrag = false;+ }}+ class={cn(+ 'min-w-0',+ props.draggable && 'pb-0.5',+ props.labelId !== undefined &&+ 'relative pl-(--sidebar-icon-slot) before:pointer-events-none before:absolute before:inset-y-0 before:left-(--sidebar-local-rail) before:w-px before:-translate-x-1/2 before:bg-edge-muted',+ isGroupingTarget() &&+ 'rounded-lg bg-selected ring-1 ring-inset ring-accent',+ dnd?.draggable.isActiveDraggable && 'opacity-50'+ )}+ >+ <ChannelRailItemContextMenu+ channel={props.channel}+ class="block w-full"+ extraItems={<ChannelLabelMenuItems channel={props.channel} />}>- <ViewSidebar.Icon>- <ChannelAvatar channel={props.channel} />- </ViewSidebar.Icon>- <span class="min-w-0 flex-1 truncate">{props.channel.name}</span>- <span class="flex shrink-0 items-center gap-2">- <ChannelMutedIndicator muted={item().muted} />- <ChannelCallIndicator- status={item().incomingCallId ? undefined : item().callStatus}- />- <Show when={item().unread}>- <span- aria-label="Unread"- class="size-2 shrink-0 rounded-full bg-accent"+ <ViewSidebar.Item+ as="div"+ id={item().domId}+ role="treeitem"+ tabIndex={-1}+ class={cn(+ 'group/channel-option relative',+ !item().selected &&+ !isTouchDevice() &&+ item().focused &&+ 'bg-hover text-ink'+ )}+ active={item().selected && !isTouchDevice()}+ aria-current={item().selected ? 'page' : undefined}+ onClick={(event) => {+ if (!isPrimaryMouseDown(event) || didDrag) return;+ rail.activateRow(rowId(), event);+ }}+ >+ <ViewSidebar.Icon>+ <ChannelAvatar channel={props.channel} />+ </ViewSidebar.Icon>+ <span class="min-w-0 flex-1 truncate">{props.channel.name}</span>+ <span class="flex shrink-0 items-center gap-2">+ <ChannelMutedIndicator muted={item().muted} />+ <ChannelCallIndicator+ status={item().incomingCallId ? undefined : item().callStatus}/>- </Show>- <Show when={!item().incomingCallId && timestamp()}>- {(value) => (- <span class="relative hidden shrink-0 group-hover/channel-option:block touch:hidden">+ <Show when={item().unread}>+ <span+ aria-label="Unread"+ class="size-2 shrink-0 rounded-full bg-accent"+ />+ </Show>+ <Show when={!item().incomingCallId && timestamp()}>+ {(value) => (<span- aria-hidden="true"- class="invisible whitespace-nowrap text-xs font-light"- >- <Entity.Timestamp- entity={props.channel}- overrideTimeStamp={value()}- />- </span>- <Tooltip- label={formatDetailedTimestamp(value())}- placement="top"- class="absolute inset-0 flex items-center"+ class={cn(+ 'relative shrink-0',+ props.alwaysShowTimestamp+ ? 'block'+ : 'hidden group-hover/channel-option:block touch:hidden'+ )}>- <span class="whitespace-nowrap text-xs font-light text-ink-extra-muted">+ <span+ aria-hidden="true"+ class="invisible whitespace-nowrap text-xs font-light"+ ><Entity.Timestampentity={props.channel}overrideTimeStamp={value()}/></span>- </Tooltip>- </span>+ <Tooltip+ label={formatDetailedTimestamp(value())}+ placement="top"+ class="absolute inset-0 flex items-center"+ >+ <span class="whitespace-nowrap text-xs font-light text-ink-extra-muted">+ <Entity.Timestamp+ entity={props.channel}+ overrideTimeStamp={value()}+ />+ </span>+ </Tooltip>+ </span>+ )}+ </Show>+ </span>+ <IncomingCallActions+ callId={item().incomingCallId}+ channelId={props.channel.id}+ />+ </ViewSidebar.Item>+ </ChannelRailItemContextMenu>+ </div>+ );+}++/**+ * Channels with unread activity, newest notification first, so nothing gets+ * lost in the stable label groups below. Hidden when nothing is unread.+ */+function ExpandedUnreadSection() {+ const rail = useChannelsRail();+ const section = useChannelRailUnreadState();++ return (+ <Show when={section().items.length > 0}>+ <CollapsibleSection.Root open={section().open} sizing="content">+ <CollapsibleSection.Header+ focused={section().focused}+ focusWithin={section().containsFocus}+ >+ <button+ id={section().domId}+ type="button"+ role="treeitem"+ tabIndex={-1}+ class="relative flex h-full min-w-0 flex-1 items-center gap-1 rounded-xl px-2 text-left outline-none"+ aria-expanded={section().open}+ onMouseDown={(event) => {+ if (!isPrimaryMouseDown(event)) return;+ event.preventDefault();+ rail.toggleGroup('unread');+ }}+ >+ <span class="min-w-0 truncate">Unread</span>+ <CaretDownIcon+ class={cn(+ 'size-2.5 shrink-0 opacity-0 transition-[opacity,rotate] duration-200 motion-reduce:transition-none group-hover/sidebar-section:opacity-100',+ !section().open && '-rotate-90 opacity-100'+ )}+ />+ <span class="flex h-4 min-w-4 items-center justify-center rounded-full bg-accent px-1 text-xs font-medium leading-none tabular-nums text-accent-contrast">+ {section().items.length}+ </span>+ </button>+ </CollapsibleSection.Header>+ <CollapsibleSection.Content+ open={section().open}+ contentRef={(element) => rail.registerScrollRef('unread', element)}+ class="flex min-h-0 flex-col gap-0.5"+ >+ <For each={section().items}>+ {(channel) => (+ <ChannelOption+ channel={channel}+ rowId={rowKeyForUnread(channel.id)}+ alwaysShowTimestamp+ />)}- </Show>- </span>- <IncomingCallActions- callId={item().incomingCallId}- channelId={props.channel.id}- />- </ViewSidebar.Item>- </ChannelRailItemContextMenu>+ </For>+ </CollapsibleSection.Content>+ </CollapsibleSection.Root>+ </Show>);}@@ -459,9 +657,129 @@ function ExpandedSearchResults(props: { search: ChannelRailSearch }) {);}+const labelRowOf = (row: ChannelSectionRow) =>+ row.kind === 'label' ? row : undefined;+const channelRowOf = (row: ChannelSectionRow) =>+ row.kind === 'conversation' ? row : undefined;++/**+ * The Channels section body: an optional "new label" draft, then one+ * virtualized list of label headings and channels. Dropping a dragged channel+ * on the list itself, outside any row, takes it out of its label.+ */+function ChannelsSectionRows(props: {+ rows: readonly ChannelSectionRow[];+ registerVirtualizer: (handle?: VirtualizerHandle) => void;+ scrollRoot: HTMLDivElement | undefined;+ keepMounted: number[] | undefined;+ onScroll: (offset?: number) => void;+ emptyLabel: string;+ children: JSX.Element;+}) {+ const rail = useChannelsRail();+ const droppable = createDroppable(`${rail.railId}:channel-label:unlabelled`, {+ dragType: 'channel-label-target',+ dndScope: rail.railId,+ target: { kind: 'unlabelled' },+ isDropTargetDisabled: () => !rail.labelsAvailable(),+ } satisfies ChannelLabelDropData);+ const isUnlabelledTarget = () =>+ rail.activeDropTarget()?.kind === 'unlabelled';+ // Rows of the label the cursor is over form one highlighted block: the+ // heading rounds the top, the last row rounds the bottom, and the 2px row+ // gap is painted too so the block reads as one shape.+ const groupHighlight = (row: ChannelSectionRow, index: number) => {+ const target = rail.activeDropTarget();+ if (target?.kind !== 'label') return undefined;+ const labelId = row.kind === 'label' ? row.label.id : row.labelId;+ if (labelId !== target.labelId) return undefined;+ const next = props.rows[index + 1];+ const isLast =+ next === undefined ||+ (next.kind === 'label' ? next.label.id : next.labelId) !== labelId;+ return cn(+ 'bg-selected',+ row.kind === 'label' && 'rounded-t-lg',+ isLast && 'rounded-b-lg'+ );+ };++ return (+ <div ref={droppable.ref} class="flex min-h-full flex-col">+ <Show+ when={props.rows.length > 0}+ fallback={+ <div class="px-2 py-2 text-xs text-ink-extra-muted">+ {props.emptyLabel}+ </div>+ }+ >+ <Virtualizer+ ref={props.registerVirtualizer}+ data={props.rows}+ scrollRef={props.scrollRoot}+ itemSize={34}+ bufferSize={240}+ keepMounted={props.keepMounted}+ onScroll={props.onScroll}+ >+ {(row, index) => (+ <div class={groupHighlight(row, index())}>+ <Switch>+ <Match when={labelRowOf(row)}>+ {(labelRow) => <ChannelLabelRow label={labelRow().label} />}+ </Match>+ <Match when={channelRowOf(row)}>+ {(channelRow) => (+ <ChannelOption+ channel={channelRow().channel}+ labelId={channelRow().labelId}+ rowId={rowKeyForChannel(+ channelRow().channel.id,+ channelRow().labelId+ )}+ draggable+ />+ )}+ </Match>+ </Switch>+ </div>+ )}+ </Virtualizer>+ {props.children}+ </Show>+ <div+ class={cn(+ 'min-h-8 flex-1 rounded-lg px-2 py-2 text-xs text-ink-muted',+ isUnlabelledTarget() && 'bg-selected ring-1 ring-inset ring-accent'+ )}+ >+ <Show when={isUnlabelledTarget()}>Remove from label</Show>+ </div>+ </div>+ );+}++/** Register the heading only while tags are enabled, so disabling removes it. */+function ChannelHeadingDropTarget(props: { element: HTMLElement }) {+ const rail = useChannelsRail();+ const droppable = createDroppable(+ `${rail.railId}:channel-label:unlabelled-heading`,+ {+ dragType: 'channel-label-target',+ dndScope: rail.railId,+ target: { kind: 'unlabelled' },+ isDropTargetDisabled: () => !rail.labelsAvailable(),+ } satisfies ChannelLabelDropData+ );+ droppable.ref(props.element);+ return null;+}+function ExpandedGroupSection(props: { config: GroupConfig }) {const rail = useChannelsRail();const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();+ const [headerElement, setHeaderElement] = createSignal<HTMLElement>();const { state: section } = useChannelRailSectionState(() => props.config.group);@@ -479,7 +797,24 @@ function ExpandedGroupSection(props: { config: GroupConfig }) {<CollapsibleSection.Headerfocused={section().focused}focusWithin={section().containsFocus}+ class={cn(+ rail.channelTagsEnabled() &&+ props.config.group === 'channels' &&+ rail.activeDropTarget()?.kind === 'unlabelled' &&+ 'bg-selected ring-1 ring-inset ring-accent'+ )}+ ref={setHeaderElement}>+ <Show+ when={+ rail.channelTagsEnabled() &&+ props.config.group === 'channels' &&+ headerElement()+ }+ keyed+ >+ {(element) => <ChannelHeadingDropTarget element={element} />}+ </Show><buttonid={section().domId}type="button"@@ -511,10 +846,17 @@ function ExpandedGroupSection(props: { config: GroupConfig }) {group={props.config.group}label={props.config.label}/>- <CreateRailAction- label={props.config.createLabel}- onClick={props.config.onCreate}- />+ <Show+ when={props.config.group === 'channels'}+ fallback={+ <CreateRailAction+ label={props.config.createLabel}+ onClick={props.config.onCreate}+ />+ }+ >+ <ChannelsCreateMenu />+ </Show></div></CollapsibleSection.Header><CollapsibleSection.Content@@ -526,15 +868,47 @@ function ExpandedGroupSection(props: { config: GroupConfig }) {><Switch><Match- when={section().source.isLoading() && section().items.length === 0}+ when={+ section().source.isLoading() &&+ section().items.length === 0 &&+ (section().rows?.length ?? 0) === 0+ }><RailListLoading /></Match><Match- when={section().source.error() && section().items.length === 0}+ when={+ section().source.error() &&+ section().items.length === 0 &&+ (section().rows?.length ?? 0) === 0+ }><RailListError retry={section().source.refresh} /></Match>+ <Match when={rail.channelTagsEnabled() && section().rows}>+ {(rows) => (+ <ChannelsSectionRows+ rows={rows()}+ registerVirtualizer={pagination.registerVirtualizer}+ scrollRoot={scrollRoot()}+ keepMounted={section().keepMounted}+ onScroll={pagination.loadMoreNearEnd}+ emptyLabel={props.config.emptyLabel}+ >+ <Show when={section().source.isLoadingMore()}>+ <RailListLoadingMore variant="channel" />+ </Show>+ <Show+ when={+ section().source.error() &&+ !section().source.isLoadingMore()+ }+ >+ <RailListError retry={section().source.refresh} compact />+ </Show>+ </ChannelsSectionRows>+ )}+ </Match><Match when={section().items.length > 0}><Virtualizerref={pagination.registerVirtualizer}@@ -579,6 +953,7 @@ function ExpandedBrowse() {DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES);const hasItems = () =>+ rail.labels().length > 0 ||rail.favorites().length > 0 ||rail.sources.channels.items().length > 0 ||rail.sources.direct_messages.items().length > 0;@@ -596,6 +971,7 @@ function ExpandedBrowse() {<Match when={true}><ViewSidebar.Content class="h-full overflow-hidden"><ExpandedFavoritesSection />+ <ExpandedUnreadSection />{/* The groups split the height left after favorites between them.Their half-height caps resolve against this column, not thewhole sidebar, so favorites is never squeezed out. */}@@ -616,7 +992,11 @@ function RecentConversationCard(props: { channel: ChannelEntity }) {const item = useChannelRailItemState(() => props.channel.id);return (- <ChannelRailItemContextMenu channel={props.channel} class="block w-full">+ <ChannelRailItemContextMenu+ channel={props.channel}+ class="block w-full"+ extraItems={<ChannelLabelMenuItems channel={props.channel} />}+ ><ConversationCardid={item().domId}class="border-b border-edge-muted"diff --git a/apps/web/src/features/channels-view/components/rail/SmartTagDialog.test.tsx b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.test.tsxnew file mode 100644index 0000000000..485cd84b67--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.test.tsx@@ -0,0 +1,174 @@+import { ImperativeDialogHost } from '@app/components/ui/components/ImperativeDialog';+import { queryClient } from '@queries/client';+import type { SmartTagPreview } from '@service-storage/generated/schemas/smartTagPreview';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { QueryClientProvider } from '@tanstack/solid-query';+import { type Ok, ok } from 'neverthrow';+import type { ComponentProps, ParentProps } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { promptSmartTag } from './SmartTagDialog';++const fetchPreview = vi.hoisted(() => vi.fn());+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: true }),+}));+vi.mock('@service-storage/client', () => ({+ storageServiceClient: { channelLabels: { preview: fetchPreview } },+}));+vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return {+ queryClient: new QueryClient({+ defaultOptions: { queries: { retry: false } },+ }),+ };+});+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));+vi.mock('@ui', async () => ({+ ...(await import('@app/components/ui/components/ImperativeDialog')),+ ...(await import('@app/components/ui/components/Dialog')),+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ Layer: (props: ParentProps) => props.children,+ Surface: (props: ParentProps) => <div>{props.children}</div>,+ Input: (props: ComponentProps<'input'>) => <input {...props} />,+ Button: (props: ComponentProps<'button'>) => (+ <button type={props.type} disabled={props.disabled} onClick={props.onClick}>+ {props.children}+ </button>+ ),+}));++beforeEach(() => {+ vi.stubGlobal('scrollTo', vi.fn());+ fetchPreview.mockReset();+ render(() => (+ <QueryClientProvider client={queryClient}>+ <ImperativeDialogHost />+ </QueryClientProvider>+ ));+});+afterEach(() => {+ cleanup();+ queryClient.clear();+ vi.unstubAllGlobals();+});+const input = (label: string, value: string) =>+ fireEvent.input(screen.getByRole('textbox', { name: label }), {+ target: { value },+ });++describe('smart label dialog', () => {+ it('previews matches as the pattern changes, with bounded results and an overflow count', async () => {+ fetchPreview.mockImplementation(async (rule) =>+ ok(+ rule.contains === 'support'+ ? {+ channels: Array.from({ length: 5 }, (_, index) => ({+ id: `${index}`,+ name: `Support ${index}`,+ })),+ totalCount: 12,+ }+ : { channels: [{ id: 'sales', name: 'Sales team' }], totalCount: 1 }+ )+ );+ const onConfirm = vi.fn(async () => {});+ const result = promptSmartTag({ scopeDescription: 'Private', onConfirm });+ expect(fetchPreview).not.toHaveBeenCalled();+ input('Label name', 'Support');+ input('Name contains', 'support');+ await screen.findByText('+7 more channels matched');+ expect(screen.getAllByRole('listitem')).toHaveLength(5);+ input('Name contains', 'sales');+ await screen.findByText('Sales team');+ expect(screen.queryByText('Support 0')).toBeNull();+ expect(screen.queryByText('+7 more channels matched')).toBeNull();+ input('Name contains', '');+ expect(+ screen.queryByRole('region', { name: 'Matched channels' })+ ).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ await result;+ expect(onConfirm).not.toHaveBeenCalled();+ });++ it('ignores an old preview response after the user changes the pattern', async () => {+ let resolveFirst!: (value: Ok<SmartTagPreview, unknown>) => void;+ fetchPreview+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirst = resolve;+ })+ )+ .mockResolvedValueOnce(+ ok({ channels: [{ id: 'b', name: 'Latest match' }], totalCount: 1 })+ );+ const result = promptSmartTag({+ scopeDescription: 'Private',+ onConfirm: async () => {},+ });+ input('Name contains', 'first');+ await waitFor(() => expect(fetchPreview).toHaveBeenCalledTimes(1));+ input('Name contains', 'second');+ await screen.findByText('Latest match');+ resolveFirst(+ ok({ channels: [{ id: 'a', name: 'Stale match' }], totalCount: 1 })+ );+ await waitFor(() => expect(screen.queryByText('Stale match')).toBeNull());+ expect(screen.getByText('Latest match')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ await result;+ });++ it('allows a rule-only edit, retains both fields on failure, and waits for the successful retry', async () => {+ fetchPreview.mockResolvedValue(ok({ channels: [], totalCount: 0 }));+ let finish!: () => void;+ const onConfirm = vi+ .fn()+ .mockRejectedValueOnce(new Error('Could not save'))+ .mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finish = resolve;+ })+ );+ const result = promptSmartTag({+ scopeDescription: 'Shared',+ initial: {+ name: 'Support',+ rule: { attribute: 'name', contains: 'old' },+ },+ onConfirm,+ });+ input('Name contains', ' new ');+ fireEvent.click(screen.getByRole('button', { name: 'Save smart label' }));+ await screen.findByRole('alert');+ expect(+ (screen.getByRole('textbox', { name: 'Label name' }) as HTMLInputElement)+ .value+ ).toBe('Support');+ expect(+ (+ screen.getByRole('textbox', {+ name: 'Name contains',+ }) as HTMLInputElement+ ).value+ ).toBe(' new ');+ fireEvent.click(screen.getByRole('button', { name: 'Save smart label' }));+ expect(screen.getByRole('dialog')).toBeTruthy();+ expect(onConfirm).toHaveBeenLastCalledWith('Support', {+ attribute: 'name',+ contains: 'new',+ });+ finish();+ await result;+ expect(screen.queryByRole('dialog')).toBeNull();+ });+});diff --git a/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsx b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsxnew file mode 100644index 0000000000..93e7ca2954--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.tsx@@ -0,0 +1,246 @@+import FilterIcon from '@phosphor/funnel-simple.svg';+import HashIcon from '@phosphor/hash.svg';+import XIcon from '@phosphor/x.svg';+import { useSmartTagPreviewQuery } from '@queries/channel-labels/channel-labels';+import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';+import {+ Button,+ Dialog,+ Input,+ type ManagedDialogProps,+ type OpenDialogOptions,+ openDialog,+ Surface,+} from '@ui';+import { createSignal, For, Show } from 'solid-js';++export type SmartTagDialogProps = {+ scopeDescription: string;+ initial?: { name: string; rule: ChannelLabelRule };+ onConfirm: (name: string, rule: ChannelLabelRule) => Promise<void>;+};++function SmartTagDialog(props: SmartTagDialogProps & ManagedDialogProps) {+ const [name, setName] = createSignal(props.initial?.name ?? '');+ const [pattern, setPattern] = createSignal(+ props.initial?.rule.contains ?? ''+ );+ const [saving, setSaving] = createSignal(false);+ const [error, setError] = createSignal('');+ const trimmedPattern = () => pattern().trim();+ const preview = useSmartTagPreviewQuery(trimmedPattern);+ const data = () => (preview.isSuccess ? preview.data : undefined);+ const matches = () => data()?.channels ?? [];+ const totalCount = () => data()?.totalCount ?? 0;+ const overflowCount = () => totalCount() - matches().length;+ const canSubmit = () =>+ name().trim().length > 0 &&+ trimmedPattern().length > 0 &&+ (!props.initial ||+ name().trim() !== props.initial.name ||+ trimmedPattern() !== props.initial.rule.contains);++ const submit = async (event: SubmitEvent) => {+ event.preventDefault();+ if (!canSubmit() || saving()) return;+ setSaving(true);+ setError('');+ try {+ await props.onConfirm(name().trim(), {+ attribute: 'name',+ contains: trimmedPattern(),+ });+ props.onOpenChange(false);+ } catch (error) {+ setError(+ error instanceof Error+ ? error.message+ : 'Could not save smart label. Please try again.'+ );+ } finally {+ setSaving(false);+ }+ };++ return (+ <Dialog+ open={props.open}+ onOpenChange={(open) => {+ if (!saving()) props.onOpenChange(open);+ }}+ >+ <Surface+ depth={2}+ class="flex max-h-[75dvh] flex-col gap-4 overflow-y-auto rounded-xl bg-dialog p-4 text-ink"+ >+ <form+ class="flex shrink-0 flex-col gap-4"+ onSubmit={(event) => void submit(event)}+ aria-busy={saving()}+ >+ <div class="flex items-center justify-between gap-2">+ <div class="flex items-center gap-2 px-2 text-ink-muted">+ <FilterIcon class="size-4" aria-hidden="true" />+ <Dialog.Title class="text-sm font-medium">+ {props.initial ? 'Edit smart label' : 'New smart label'}+ </Dialog.Title>+ </div>+ <Button+ type="button"+ label="Close"+ size="icon-composer"+ tabIndex={-1}+ disabled={saving()}+ onClick={() => props.onOpenChange(false)}+ >+ <XIcon />+ </Button>+ </div>+ <div class="flex flex-col gap-4 px-2">+ <div class="flex flex-col gap-2">+ <label>+ <span class="sr-only">Label name</span>+ <Input+ variant="bare"+ class="h-9 px-0 text-xl/7"+ value={name()}+ onInput={(event) => setName(event.currentTarget.value)}+ onFocus={(event) => event.currentTarget.select()}+ maxLength={80}+ placeholder="Smart label name"+ readOnly={saving()}+ />+ </label>+ <Dialog.Description class="sr-only">+ {props.scopeDescription} Matching channels are grouped+ automatically by name, ignoring capitalization.+ </Dialog.Description>+ </div>+ <div class="flex flex-col gap-2">+ <label class="flex flex-wrap items-center gap-x-3 gap-y-2 text-sm text-ink-muted focus-within:text-ink">+ <span class="shrink-0">Name contains</span>+ <Input+ variant="bare"+ class="min-w-40 flex-1 px-0 text-sm"+ value={pattern()}+ onInput={(event) => setPattern(event.currentTarget.value)}+ maxLength={200}+ placeholder="e.g. support"+ readOnly={saving()}+ />+ </label>+ </div>+ <Show when={error()}>+ <p role="alert" class="text-sm text-failure">+ {error()}+ </p>+ </Show>+ </div>+ <div class="flex items-center justify-end gap-3">+ <Button+ type="button"+ variant="ghost"+ depth={3}+ disabled={saving()}+ onClick={() => props.onOpenChange(false)}+ >+ Cancel+ </Button>+ <Button+ type="submit"+ variant={canSubmit() ? 'accent' : 'ghost'}+ depth={3}+ class="rounded-lg border-0 not-touch:h-[33.75px] not-touch:rounded-full not-touch:px-[15px]"+ disabled={!canSubmit() || saving()}+ >+ {saving()+ ? 'Saving…'+ : props.initial+ ? 'Save smart label'+ : 'Create smart label'}+ </Button>+ </div>+ </form>+ <Show when={trimmedPattern()}>+ <section+ aria-label="Matched channels"+ aria-live="polite"+ class="flex shrink-0 flex-col gap-0.5 text-sm"+ >+ <div class="flex items-center gap-1.5 px-2 py-1 text-xs font-medium text-ink-muted">+ <HashIcon class="size-3.5 shrink-0" aria-hidden="true" />+ <span>Matched channels</span>+ <Show when={data()}>+ <span class="tabular-nums">{totalCount()}</span>+ </Show>+ </div>+ <Show+ when={!preview.isPending}+ fallback={+ <p class="px-2 py-2 text-xs text-ink-muted">+ Matching channels…+ </p>+ }+ >+ <Show+ when={!preview.isError}+ fallback={+ <div class="flex items-center justify-between gap-2 px-2 py-1 text-xs text-ink-muted">+ <span>Could not load matches.</span>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => void preview.refetch()}+ >+ Retry+ </Button>+ </div>+ }+ >+ <Show+ when={totalCount()}+ fallback={+ <p class="px-2 py-2 text-xs text-ink-muted">+ No channels match yet.+ </p>+ }+ >+ <ul class="flex max-h-48 flex-col overflow-y-auto scrollbar-hidden">+ <For each={matches()}>+ {(channel) => (+ <li+ class="flex min-w-0 items-center gap-2 px-2 py-2"+ title={channel.name}+ >+ <HashIcon+ class="size-4 shrink-0 text-ink-muted"+ aria-hidden="true"+ />+ <span class="truncate">{channel.name}</span>+ </li>+ )}+ </For>+ </ul>+ <Show when={overflowCount() > 0}>+ <p class="px-2 py-2 text-xs text-ink-muted">+ +{overflowCount()} more channels matched+ </p>+ </Show>+ </Show>+ </Show>+ </Show>+ </section>+ </Show>+ </Surface>+ </Dialog>+ );+}++export async function promptSmartTag(+ props: SmartTagDialogProps,+ options?: OpenDialogOptions+): Promise<void> {+ const handle = openDialog(SmartTagDialog, props, options);+ await handle.closed;+}diff --git a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.tsnew file mode 100644index 0000000000..c1636aaded--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.test.ts@@ -0,0 +1,300 @@+import type { ChannelEntity } from '@entity';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import { describe, expect, it } from 'vitest';+import {+ buildChannelRailRows,+ buildChannelSectionRows,+} from './build-channel-rail-rows';++function channel(id: string, name = id): ChannelEntity {+ return {+ id,+ name,+ type: 'channel',+ ownerId: 'alice',+ channelType: 'public',+ } as unknown as ChannelEntity;+}++function label(+ id: string,+ name: string,+ channelIds: string[],+ sortOrder = 0+): ChannelLabel {+ return {+ id,+ teamId: 'team',+ name,+ sortOrder,+ channelIds,+ channelCount: channelIds.length,+ createdAt: '2026-09-18T00:00:00Z',+ updatedAt: '2026-09-18T00:00:00Z',+ };+}++const zeta = channel('zeta', 'zeta-support');+const acme = channel('acme', 'acme-support');+const globex = channel('globex', 'Globex-support');+const deals = channel('deals', 'deal-desk');+const hidden = channel('hidden', 'not-mine');++const byId = new Map([zeta, acme, globex, deals].map((c) => [c.id, c]));++describe('buildChannelSectionRows', () => {+ it('lists labels in team order with their channels A→Z, then the plain list in source order', () => {+ const rows = buildChannelSectionRows({+ labels: [+ label('l1', 'Enterprise', ['zeta', 'globex', 'acme'], 0),+ label('l2', 'Onboarding', ['deals'], 1),+ ],+ // Source order is by activity; labelled channels must not repeat below.+ channels: [deals, zeta, acme],+ channelsById: byId,+ isLabelOpen: () => true,+ });++ expect(+ rows.map((row) =>+ row.kind === 'label'+ ? `label:${row.label.name}`+ : `${row.labelId ?? '-'}:${row.channel.id}`+ )+ ).toEqual([+ 'label:Enterprise',+ 'l1:acme',+ 'l1:globex',+ 'l1:zeta',+ 'label:Onboarding',+ 'l2:deals',+ ]);+ });++ it('keeps unlabelled channels below the labels in source order', () => {+ const rows = buildChannelSectionRows({+ labels: [label('l1', 'Enterprise', ['acme'])],+ channels: [deals, zeta, acme],+ channelsById: byId,+ isLabelOpen: () => true,+ });++ expect(+ rows.map((row) => (row.kind === 'label' ? 'L' : row.channel.id))+ ).toEqual(['L', 'acme', 'deals', 'zeta']);+ });++ it('hides a collapsed label’s channels but keeps its heading', () => {+ const rows = buildChannelSectionRows({+ labels: [label('l1', 'Enterprise', ['acme', 'zeta'])],+ channels: [deals],+ channelsById: byId,+ isLabelOpen: () => false,+ });++ expect(rows).toEqual([+ { kind: 'label', label: expect.objectContaining({ id: 'l1' }) },+ { kind: 'conversation', channel: deals },+ ]);+ });++ it('keeps empty labels and labels with no visible channels as drop targets', () => {+ const rows = buildChannelSectionRows({+ labels: [+ label('empty', 'Empty', []),+ label('l1', 'Theirs', ['hidden']),+ label('l2', 'Mine', ['acme']),+ ],+ channels: [acme],+ channelsById: byId,+ isLabelOpen: () => true,+ });++ expect(+ rows.map((row) => (row.kind === 'label' ? row.label.id : 'c'))+ ).toEqual(['empty', 'l1', 'l2', 'c']);+ expect(+ rows.some((row) => row.kind === 'conversation' && row.channel === hidden)+ ).toBe(false);+ });+});++describe('buildChannelRailRows', () => {+ const expanded = {+ favorites: true,+ unread: true,+ channels: true,+ direct_messages: true,+ };++ it('puts the unread section between favorites and channels, newest first', () => {+ const rows = buildChannelRailRows(+ 'browse',+ expanded,+ {+ favorites: [],+ unread: [zeta, acme],+ channels: [acme, zeta],+ direct_messages: [],+ recents: [],+ },+ buildChannelSectionRows({+ labels: [],+ channels: [acme, zeta],+ channelsById: byId,+ isLabelOpen: () => true,+ })+ );++ expect(rows.map((row) => row.id)).toEqual([+ 'section:unread',+ 'unread:zeta',+ 'unread:acme',+ 'section:channels',+ 'channel:acme',+ 'channel:zeta',+ 'section:direct_messages',+ ]);+ });++ it('skips the unread section when nothing is unread and honours its collapse', () => {+ const items = {+ favorites: [],+ unread: [] as ChannelEntity[],+ channels: [],+ direct_messages: [],+ recents: [],+ };+ expect(+ buildChannelRailRows('browse', expanded, items, []).map((row) => row.id)+ ).toEqual(['section:channels', 'section:direct_messages']);++ expect(+ buildChannelRailRows(+ 'browse',+ { ...expanded, unread: false },+ { ...items, unread: [acme] },+ []+ ).map((row) => row.id)+ ).toEqual([+ 'section:unread',+ 'section:channels',+ 'section:direct_messages',+ ]);+ });++ it('gives label headings and nested channels indexes into the rendered section', () => {+ const sectionRows = buildChannelSectionRows({+ labels: [label('l1', 'Enterprise', ['acme'])],+ channels: [deals],+ channelsById: byId,+ isLabelOpen: () => true,+ });+ const rows = buildChannelRailRows(+ 'browse',+ expanded,+ {+ favorites: [],+ unread: [],+ channels: [deals],+ direct_messages: [],+ recents: [],+ },+ sectionRows+ );++ expect(rows.slice(1, 4)).toEqual([+ expect.objectContaining({ kind: 'label', id: 'label:l1', localIndex: 0 }),+ expect.objectContaining({+ kind: 'conversation',+ id: 'channel:acme:label:l1',+ localIndex: 1,+ labelId: 'l1',+ scope: 'channels',+ }),+ expect.objectContaining({+ kind: 'conversation',+ id: 'channel:deals',+ localIndex: 2,+ labelId: undefined,+ }),+ ]);+ });++ it('leaves the recent tab as a flat list', () => {+ const rows = buildChannelRailRows(+ 'recents',+ expanded,+ {+ favorites: [],+ unread: [acme],+ channels: [acme],+ direct_messages: [],+ recents: [zeta, acme],+ },+ []+ );+ expect(rows.map((row) => row.id)).toEqual(['channel:zeta', 'channel:acme']);+ });+});++it('renders a channel in every matching smart tag with unique navigation IDs, excluding it from ungrouped even when collapsed', () => {+ const labels = [+ {+ ...label('smart-1', 'Support', ['acme', 'zeta']),+ rule: { attribute: 'name' as const, contains: 'support' },+ },+ {+ ...label('smart-2', 'Acme', ['acme']),+ rule: { attribute: 'name' as const, contains: 'acme' },+ },+ label('manual', 'Manual', ['acme']),+ ];+ const sections = buildChannelSectionRows({+ labels,+ channels: [acme, zeta, deals],+ channelsById: byId,+ isLabelOpen: () => true,+ });+ expect(+ sections.filter(+ (row) => row.kind === 'conversation' && row.channel.id === 'acme'+ )+ ).toHaveLength(3);+ expect(+ sections+ .filter((row) => row.kind === 'conversation' && !row.labelId)+ .map((row) => row.kind === 'conversation' && row.channel.id)+ ).toEqual(['deals']);+ const rows = buildChannelRailRows(+ 'browse',+ { favorites: true, unread: true, channels: true, direct_messages: true },+ {+ favorites: [],+ unread: [],+ channels: [acme, zeta, deals],+ direct_messages: [],+ recents: [],+ },+ sections+ );+ expect(new Set(rows.map((row) => row.id)).size).toBe(rows.length);+ expect(+ rows+ .filter((row) => row.kind === 'conversation' && row.channel.id === 'acme')+ .map((row) => row.id)+ ).toEqual([+ 'channel:acme:label:smart-1',+ 'channel:acme:label:smart-2',+ 'channel:acme:label:manual',+ ]);+ const collapsed = buildChannelSectionRows({+ labels,+ channels: [acme, zeta, deals],+ channelsById: byId,+ isLabelOpen: () => false,+ });+ expect(collapsed.filter((row) => row.kind === 'conversation')).toEqual([+ { kind: 'conversation', channel: deals },+ ]);+});diff --git a/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.tsnew file mode 100644index 0000000000..6ceecb2454--- /dev/null+++ b/apps/web/src/features/channels-view/components/rail/build-channel-rail-rows.ts@@ -0,0 +1,180 @@+import type { ChannelEntity } from '@entity';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import type { Favorite } from '@service-storage/generated/schemas/favorite';+import type {+ ChannelsQueryScope,+ ChannelsRailSection,+ ChannelsTab,+} from '../../types';+import {+ type ChannelRailRow,+ type ChannelSectionRow,+ rowKeyForChannel,+ rowKeyForFavorite,+ rowKeyForLabel,+ rowKeyForUnread,+} from './ChannelsRailContext';++export type ChannelRailItemsByScope = Record<+ ChannelsQueryScope,+ readonly ChannelEntity[]+> & {+ favorites: readonly Favorite[];+ /** Channels with unread activity, newest first. Empty hides the section. */+ unread: readonly ChannelEntity[];+};++const compareChannelName = (left: ChannelEntity, right: ChannelEntity) =>+ left.name.localeCompare(right.name, undefined, { sensitivity: 'base' }) ||+ left.id.localeCompare(right.id);++/**+ * Lay out the Channels section: each label in saved order with the+ * channels the user can see in it (A→Z, the same for everyone), then the+ * channels in no label in the section's own sort. Empty labels stay visible as drop targets; a collapsed label hides its channels.+ *+ * Labelled channels come from `channelsById` because the paginated source+ * may not have reached them yet; anything unlabelled comes from `channels`+ * in source order.+ */+export function buildChannelSectionRows(options: {+ labels: readonly ChannelLabel[];+ channels: readonly ChannelEntity[];+ channelsById: ReadonlyMap<string, ChannelEntity>;+ isLabelOpen: (labelId: string) => boolean;+}): ChannelSectionRow[] {+ const rows: ChannelSectionRow[] = [];+ const labelled = new Set<string>();++ for (const label of options.labels) {+ const visible = label.channelIds+ .map((id) => options.channelsById.get(id))+ .filter((channel): channel is ChannelEntity => channel !== undefined)+ .sort(compareChannelName);++ for (const channel of visible) labelled.add(channel.id);+ rows.push({ kind: 'label', label });+ if (!options.isLabelOpen(label.id)) continue;+ for (const channel of visible) {+ rows.push({ kind: 'conversation', channel, labelId: label.id });+ }+ }++ for (const channel of options.channels) {+ if (labelled.has(channel.id)) continue;+ rows.push({ kind: 'conversation', channel });+ }++ return rows;+}++/**+ * The keyboard-navigable rows of the All tab (or the flat Recent list), in+ * visual order. Collapsed sections contribute only their heading.+ */+export function buildChannelRailRows(+ tab: ChannelsTab,+ expandedGroups: Record<ChannelsRailSection, boolean>,+ items: ChannelRailItemsByScope,+ channelSectionRows: readonly ChannelSectionRow[]+): ChannelRailRow[] {+ if (tab === 'recents') {+ return items.recents.map((channel, localIndex) => ({+ kind: 'conversation',+ id: `channel:${channel.id}`,+ scope: 'recents',+ localIndex,+ channel,+ }));+ }++ const rows: ChannelRailRow[] = [];+ if (items.favorites.length > 0) {+ rows.push({+ kind: 'section',+ id: 'section:favorites',+ group: 'favorites',+ });+ if (expandedGroups.favorites) {+ rows.push(+ ...items.favorites.map(+ (favorite): ChannelRailRow => ({+ kind: 'favorite',+ id: rowKeyForFavorite(favorite),+ group: 'favorites',+ favorite,+ })+ )+ );+ }+ }++ if (items.unread.length > 0) {+ rows.push({ kind: 'section', id: 'section:unread', group: 'unread' });+ if (expandedGroups.unread) {+ rows.push(+ ...items.unread.map(+ (channel, localIndex): ChannelRailRow => ({+ kind: 'unread',+ id: rowKeyForUnread(channel.id),+ group: 'unread',+ localIndex,+ channel,+ })+ )+ );+ }+ }++ rows.push({+ kind: 'section',+ id: 'section:channels',+ group: 'channels',+ });+ if (expandedGroups.channels) {+ rows.push(+ ...channelSectionRows.map(+ (row, localIndex): ChannelRailRow =>+ row.kind === 'label'+ ? {+ kind: 'label',+ id: rowKeyForLabel(row.label.id),+ group: 'channels',+ localIndex,+ label: row.label,+ }+ : {+ kind: 'conversation',+ id: rowKeyForChannel(row.channel.id, row.labelId),+ group: 'channels',+ scope: 'channels',+ localIndex,+ channel: row.channel,+ labelId: row.labelId,+ }+ )+ );+ }++ rows.push({+ kind: 'section',+ id: 'section:direct_messages',+ group: 'direct_messages',+ });+ if (expandedGroups.direct_messages) {+ rows.push(+ ...items.direct_messages.map(+ (channel, localIndex): ChannelRailRow => ({+ kind: 'conversation',+ id: `channel:${channel.id}`,+ group: 'direct_messages',+ scope: 'direct_messages',+ localIndex,+ channel,+ })+ )+ );+ }++ return rows;+}diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailActivity.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailActivity.tsindex 07be22b4ee..c0d94336a8 100644--- a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailActivity.ts+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailActivity.ts@@ -41,6 +41,9 @@ export function useChannelRailActivity(const notificationActivity = createMemo(() => {const unreadChannelIds = new Set<string>();+ // Channels with unread activity, newest unread notification first; the+ // notifications are already sorted newest-first so first sight wins.+ const unreadChannelOrder: string[] = [];const unreadNotificationIds = new Set<string>();const unreadCounts: Record<ChannelsGroup, number> = {channels: 0,@@ -64,6 +67,8 @@ export function useChannelRailActivity(notification.entity_id);unreadChannelIds.add(notification.entity_id);+ if (isFirstUnreadForChannel)+ unreadChannelOrder.push(notification.entity_id);unreadNotificationIds.add(notification.id);const channel = channelsById().get(notification.entity_id);@@ -85,6 +90,7 @@ export function useChannelRailActivity(return {latestTargets,unreadChannelIds,+ unreadChannelOrder,unreadNotificationIds,unreadCounts,};@@ -216,6 +222,8 @@ export function useChannelRailActivity(targetChannelId,targetLabel,unreadChannelIds: () => notificationActivity().unreadChannelIds,+ /** Channel ids with unread activity, newest unread notification first. */+ unreadChannelOrder: () => notificationActivity().unreadChannelOrder,unreadCount: (group: ChannelsGroup) =>notificationActivity().unreadCounts[group],};diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.tsindex eed3d001d4..ea972967db 100644--- a/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelRailState.ts@@ -1,27 +1,34 @@import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { isMutedItem } from '@entity/utils/notification';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';import type { Favorite } from '@service-storage/generated/schemas/favorite';import { type Accessor, createMemo, createSignal, onCleanup } from 'solid-js';import type { VirtualizerHandle } from 'virtua/solid';import type { ChannelsSourceScope } from '../../../queries';import type { ChannelsGroup, ChannelsQueryScope } from '../../../types';import {+ type ChannelRailRow,domIdForRow,rowKeyForChannel,rowKeyForFavorite,+ rowKeyForLabel,rowKeyForSection,useChannelsRail,} from '../ChannelsRailContext';const LOAD_MORE_THRESHOLD = 300;-export function useChannelRailItemState(channelId: Accessor<string>) {+export function useChannelRailItemState(+ channelId: Accessor<string>,+ /** The row this item renders as; defaults to the channel's own row. */+ rowKey: Accessor<ChannelRailRow['id']> = () => rowKeyForChannel(channelId())+) {const rail = useChannelsRail();const notificationSource = useGlobalNotificationSource();return createMemo(() => {const id = channelId();- const rowId = rowKeyForChannel(id);+ const rowId = rowKey();return {domId: domIdForRow(rail.railId, rowId),@@ -78,9 +85,15 @@ export function useChannelRailScopeState(scope: Accessor<ChannelsQueryScope>) {const currentScope = scope();const source = rail.sources[currentScope];const items = source.items();+ // The Channels section renders label headings between its channels, so+ // its virtualizer indexes come from those rows, not the source.+ const rows =+ currentScope === 'channels' ? rail.channelSectionRows() : undefined;const focusedRow = rail.list.focus.item();const focusedIndex =- focusedRow?.kind === 'conversation' && focusedRow.scope === currentScope+ (focusedRow?.kind === 'conversation' &&+ focusedRow.scope === currentScope) ||+ (focusedRow?.kind === 'label' && currentScope === 'channels')? focusedRow.localIndex: -1;const targetChannelId =@@ -90,13 +103,20 @@ export function useChannelRailScopeState(scope: Accessor<ChannelsQueryScope>) {const activityIndex =targetChannelId === undefined? -1- : items.findIndex((channel) => channel.id === targetChannelId);+ : rows+ ? rows.findIndex(+ (row) =>+ row.kind === 'conversation' &&+ row.channel.id === targetChannelId+ )+ : items.findIndex((channel) => channel.id === targetChannelId);const keepMounted = [...new Set([focusedIndex, activityIndex])].filter((index) => index >= 0);return {items,+ rows,source,focusedIndex,activityIndex,@@ -172,3 +192,39 @@ export function useChannelRailSectionState(group: Accessor<ChannelsGroup>) {return { state };}++export function useChannelRailLabelState(label: Accessor<ChannelLabel>) {+ const rail = useChannelsRail();++ return createMemo(() => {+ const current = label();+ const rowId = rowKeyForLabel(current.id);+ const focusedRow = rail.list.focus.item();++ return {+ domId: domIdForRow(rail.railId, rowId),+ open: rail.isLabelOpen(current.id),+ focused: rail.list.focus.key() === rowId,+ containsFocus:+ focusedRow?.kind === 'conversation' &&+ focusedRow.labelId === current.id,+ unreadCount: rail.labelUnreadCount(current),+ };+ });+}++export function useChannelRailUnreadState() {+ const rail = useChannelsRail();++ return createMemo(() => {+ const rowId = rowKeyForSection('unread');++ return {+ items: rail.unreadChannels(),+ open: rail.isGroupOpen('unread'),+ focused: rail.list.focus.key() === rowId,+ containsFocus: rail.list.focus.item()?.group === 'unread',+ domId: domIdForRow(rail.railId, rowId),+ };+ });+}diff --git a/apps/web/src/features/channels-view/core/smart-tags.test.ts b/apps/web/src/features/channels-view/core/smart-tags.test.tsnew file mode 100644index 0000000000..221b15e269--- /dev/null+++ b/apps/web/src/features/channels-view/core/smart-tags.test.ts@@ -0,0 +1,66 @@+import type { ChannelEntity } from '@entity';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import { describe, expect, it } from 'vitest';+import {+ channelMatchesSmartTag,+ resolveSmartTagMemberships,+} from './smart-tags';++const channel = (id: string, name: string, channelType = 'public') =>+ ({+ id,+ name,+ channelType,+ type: 'channel',+ }) as ChannelEntity;+const rule = { attribute: 'name' as const, contains: 'support' };+const label = (id: string, channelIds: string[]): ChannelLabel => ({+ id,+ name: id,+ channelIds,+ channelCount: channelIds.length,+ sortOrder: 0,+ createdAt: '',+ updatedAt: '',+ rule,+});++describe('smart tag matching', () => {+ it('matches literal substrings ignoring case, excluding DMs and empty patterns', () => {+ expect(channelMatchesSmartTag(channel('a', 'Acme SUPPORT'), rule)).toBe(+ true+ );+ expect(+ channelMatchesSmartTag(channel('a', 'support', 'direct_message'), rule)+ ).toBe(false);+ expect(+ channelMatchesSmartTag(channel('a', '100%_support'), {+ attribute: 'name',+ contains: '%_',+ })+ ).toBe(true);+ expect(+ channelMatchesSmartTag(channel('a', 'any'), {+ attribute: 'name',+ contains: '%',+ })+ ).toBe(false);+ expect(+ channelMatchesSmartTag(channel('a', 'any'), {+ attribute: 'name',+ contains: '',+ })+ ).toBe(false);+ });++ it('updates loaded memberships on channel rename while retaining matches beyond loaded pages', () => {+ const manual = { ...label('manual', ['renamed']), rule: null };+ const result = resolveSmartTagMemberships(+ [label('smart', ['unloaded', 'renamed']), manual],+ [channel('renamed', 'Sales'), channel('new', 'New Support')]+ );+ expect(result[0].channelIds).toEqual(['unloaded', 'new']);+ expect(result[0].channelCount).toBe(2);+ expect(result[1]).toBe(manual);+ });+});diff --git a/apps/web/src/features/channels-view/core/smart-tags.ts b/apps/web/src/features/channels-view/core/smart-tags.tsnew file mode 100644index 0000000000..788d36d348--- /dev/null+++ b/apps/web/src/features/channels-view/core/smart-tags.ts@@ -0,0 +1,35 @@+import type { ChannelEntity } from '@entity';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';++export function channelMatchesSmartTag(+ channel: ChannelEntity,+ rule: ChannelLabelRule+): boolean {+ return (+ channel.channelType !== 'direct_message' &&+ rule.contains.length > 0 &&+ channel.name.toLowerCase().includes(rule.contains.toLowerCase())+ );+}++/** Keep server matches beyond loaded pages, while reflecting live channel-name updates. */+export function resolveSmartTagMemberships(+ labels: readonly ChannelLabel[],+ channels: readonly ChannelEntity[]+): ChannelLabel[] {+ const loadedIds = new Set(channels.map((channel) => channel.id));+ return labels.map((label) => {+ const rule = label.rule;+ if (!rule) return label;+ const channelIds = [+ ...new Set([+ ...label.channelIds.filter((id) => !loadedIds.has(id)),+ ...channels+ .filter((channel) => channelMatchesSmartTag(channel, rule))+ .map((channel) => channel.id),+ ]),+ ];+ return { ...label, channelIds, channelCount: channelIds.length };+ });+}diff --git a/apps/web/src/features/channels-view/persistence.ts b/apps/web/src/features/channels-view/persistence.tsindex ad859234f3..cc6785a65b 100644--- a/apps/web/src/features/channels-view/persistence.ts+++ b/apps/web/src/features/channels-view/persistence.ts@@ -38,6 +38,7 @@ const channelsExpandedGroupsSchema = z.preprocess(},z.object({favorites: z.boolean().default(true),+ unread: z.boolean().default(true),channels: z.boolean().default(true),direct_messages: z.boolean().default(true),})@@ -52,9 +53,11 @@ const channelsEntryStateSchemaWithDefaults = z.object({selectedChannelId: z.string().optional(),expandedGroups: channelsExpandedGroupsSchema.default({favorites: true,+ unread: true,channels: true,direct_messages: true,}),+ collapsedLabels: z.array(z.string()).default([]),});type ChannelsEntryState = z.infer<typeof channelsEntryStateSchemaWithDefaults>;@@ -66,9 +69,11 @@ const DEFAULT_CHANNELS_ENTRY_STATE = {selectedChannelId: undefined,expandedGroups: {favorites: true,+ unread: true,channels: true,direct_messages: true,},+ collapsedLabels: [],} satisfies ChannelsEntryState;const channelsPreferencesSchema = z.object({@@ -107,6 +112,7 @@ function selectEntryState(state: ChannelsViewState): ChannelsEntryState {? {}: { selectedChannelId: state.selectedChannelId }),expandedGroups: state.expandedGroups,+ collapsedLabels: state.collapsedLabels,};}@@ -123,6 +129,7 @@ function restoreChannelsEntryState(mobileTab: restored.mobileTab,selectedChannelId: restored.selectedChannelId,expandedGroups: restored.expandedGroups,+ collapsedLabels: restored.collapsedLabels,};}diff --git a/apps/web/src/features/channels-view/queries.ts b/apps/web/src/features/channels-view/queries.tsindex fa9ae56e93..7016dbbd60 100644--- a/apps/web/src/features/channels-view/queries.ts+++ b/apps/web/src/features/channels-view/queries.ts@@ -11,7 +11,7 @@ import {type SoupAstParams,useSoupAstItemsQuery,} from '@queries/soup/items';-import { type Accessor, createMemo } from 'solid-js';+import { type Accessor, createEffect, createMemo } from 'solid-js';import type {ChannelListSort,ChannelsGroup,@@ -112,6 +112,50 @@ export function channelByIdQueryArgs(channelId: string): SoupAstItemsQueryArgs {};}+/**+ * Fetch specific channels by id, for labelled channels the paginated Channels+ * source has not reached yet. Page through the requested IDs independently+ * of the main list so broad smart tags include all their matched channels.+ */+export function channelsByIdsQueryArgs(+ channelIds: readonly string[]+): SoupAstItemsQueryArgs {+ return {+ params: {+ ...CHANNELS_QUERY_PARAMS,+ limit: Math.min(500, Math.max(1, channelIds.length)),+ sort_method: 'created_at',+ },+ body: compileToAst(+ queryStateFrom(+ defineQueryFilters({+ include: { channelId: [...channelIds] },+ })+ )+ ),+ };+}++export function useChannelsByIdsQuery(channelIds: Accessor<readonly string[]>) {+ const query = useSoupAstItemsQuery(+ () => channelsByIdsQueryArgs(channelIds()),+ () => ({ enabled: channelIds().length > 0, staleTime: 30_000 })+ );+ // Drive the external paginated query until all requested matches are loaded.+ createEffect(() => {+ if (+ !query.isEnabled ||+ query.isLoading ||+ query.isFetching ||+ query.error ||+ !query.hasNextPage+ )+ return;+ void query.fetchNextPage();+ });+ return query;+}+export function deduplicateChannels(collections: readonly (readonly ChannelEntity[])[]): ChannelEntity[] {diff --git a/apps/web/src/features/channels-view/types.ts b/apps/web/src/features/channels-view/types.tsindex 736c5eba2a..ccf99ce3dd 100644--- a/apps/web/src/features/channels-view/types.ts+++ b/apps/web/src/features/channels-view/types.ts@@ -4,7 +4,11 @@ export type ChannelsGroup = 'channels' | 'direct_messages';export type ChannelListSort = 'viewed_at' | 'updated_at' | 'created_at';-export type ChannelsRailSection = 'favorites' | ChannelsGroup;+/**+ * Collapsible sections of the All tab. `unread` is the flat, newest-first list+ * of channels with unread activity that sits above `channels`.+ */+export type ChannelsRailSection = 'favorites' | 'unread' | ChannelsGroup;export type ChannelsQueryScope = ChannelsGroup | 'recents';@@ -13,6 +17,11 @@ export type ChannelsViewState = {mobileTab: ChannelsQueryScope;selectedChannelId?: string;expandedGroups: Record<ChannelsRailSection, boolean>;+ /**+ * Channel labels this user has collapsed. Labels themselves are team data;+ * only the open/closed state is personal, so it is stored by label id.+ */+ collapsedLabels: string[];sortBy: Record<ChannelsGroup, ChannelListSort>;asideWidth: number;};diff --git a/apps/web/src/features/soup/SoupEntityContextMenu.tsx b/apps/web/src/features/soup/SoupEntityContextMenu.tsxindex 9f4f43f87b..03ceb11da3 100644--- a/apps/web/src/features/soup/SoupEntityContextMenu.tsx+++ b/apps/web/src/features/soup/SoupEntityContextMenu.tsx@@ -3,7 +3,7 @@ import {type EntityActionViewContext,makeAddTagAction,} from '@app/features/next-soup/actions';-import { ContextMenuContent } from '@core/component/ContextMenu';+import { ContextMenuContent, MenuSeparator } from '@core/component/ContextMenu';import { touchHandler } from '@core/directive/touchHandler';import { isMobile } from '@core/mobile/isMobile';import type { EntityData } from '@entity';@@ -20,6 +20,7 @@ import {type Accessor,createSignal,type FlowComponent,+ type JSX,Match,Show,Switch,@@ -36,6 +37,11 @@ interface SoupEntityContextMenuProps {/** Use a div trigger when the row already renders its own button. */as?: 'div';onOpenChange?: (open: boolean) => void;+ /**+ * View-specific items appended after the entity actions, separated from+ * them. Desktop only: the mobile long-press drawer shows the actions alone.+ */+ extraItems?: JSX.Element;}function RowTagPicker(props: {@@ -134,6 +140,10 @@ export const SoupEntityContextMenu: FlowComponent<: undefined}/>+ <Show when={props.extraItems}>+ <MenuSeparator />+ {props.extraItems}+ </Show></ContextMenuContent></Show></ContextMenu.Portal>diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 16abade66e..54129426bd 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -628,6 +628,13 @@ export const enableTagTeamSharing = defineFlag({default: onInDev,});+// Manual and smart channel labels, including their queries and drag/drop UI.+// Off until PostHog enables them; override with VITE_ENABLE_CHANNEL_TAGS.+export const enableChannelTags = defineFlag({+ key: 'enable-channel-tags',+ env: 'ENABLE_CHANNEL_TAGS',+});+// The "Activity" section in the entity side panel: the entity's recent// activity timeline from the GraphQL activity log (who did what, when).// Purely additive — when off, the section never mounts and no activitydiff --git a/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx b/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsxnew file mode 100644index 0000000000..a603318653--- /dev/null+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx@@ -0,0 +1,123 @@+import type { ChannelLabelsList } from '@service-storage/generated/schemas/channelLabelsList';+import { cleanup, render, waitFor } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { ok } from 'neverthrow';+import { createSignal } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ useChannelLabelsData,+ useChannelLabelsQuery,+ useSmartTagPreviewQuery,+} from './channel-labels';+import { channelLabelKeys } from './keys';++const mocks = vi.hoisted(() => ({+ enabled: (): boolean => false,+ list: vi.fn(),+ preview: vi.fn(),+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: mocks.enabled() }),+}));+vi.mock('@service-storage/client', () => ({+ storageServiceClient: {+ channelLabels: { list: mocks.list, preview: mocks.preview },+ },+}));+vi.mock('../client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return { queryClient: new QueryClient() };+});++const labels: ChannelLabelsList = {+ labels: [+ {+ id: 'support',+ name: 'Support',+ channelIds: ['channel-1'],+ channelCount: 1,+ sortOrder: 0,+ createdAt: '2026-09-22T00:00:00Z',+ updatedAt: '2026-09-22T00:00:00Z',+ },+ ],+};+let client: QueryClient;++beforeEach(() => {+ mocks.list.mockReset().mockResolvedValue(ok(labels));+ mocks.preview+ .mockReset()+ .mockResolvedValue(ok({ channels: [], totalCount: 0 }));+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+});+afterEach(() => {+ cleanup();+ client.clear();+});++describe('channel tag query rollout', () => {+ it('does not fetch while disabled and hides cached labels when switched off', async () => {+ const [enabled, setEnabled] = createSignal(false);+ mocks.enabled = enabled;+ client.setQueryData(channelLabelKeys.list.queryKey, labels);+ let data!: ReturnType<typeof useChannelLabelsData>;+ let query!: ReturnType<typeof useChannelLabelsQuery>;+ const Probe = () => {+ data = useChannelLabelsData();+ query = useChannelLabelsQuery();+ return null;+ };+ render(() => (+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>+ ));++ expect(query.isEnabled).toBe(false);+ expect(data()).toBeUndefined();+ await client.invalidateQueries({+ queryKey: channelLabelKeys.list.queryKey,+ });+ expect(mocks.list).not.toHaveBeenCalled();++ setEnabled(true);+ await waitFor(() => expect(mocks.list).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(data()).toEqual(labels.labels));++ setEnabled(false);+ await waitFor(() => expect(query.isEnabled).toBe(false));+ expect(data()).toBeUndefined();+ await client.invalidateQueries({+ queryKey: channelLabelKeys.list.queryKey,+ });+ expect(mocks.list).toHaveBeenCalledTimes(1);+ expect(client.getQueryData(channelLabelKeys.list.queryKey)).toEqual(labels);+ });++ it('only previews smart tags while enabled', async () => {+ const [enabled, setEnabled] = createSignal(false);+ const [pattern, setPattern] = createSignal('support');+ mocks.enabled = enabled;+ let preview!: ReturnType<typeof useSmartTagPreviewQuery>;+ const Probe = () => {+ preview = useSmartTagPreviewQuery(pattern);+ return null;+ };+ render(() => (+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>+ ));++ expect(preview.isEnabled).toBe(false);+ expect(mocks.preview).not.toHaveBeenCalled();+ setEnabled(true);+ await waitFor(() => expect(mocks.preview).toHaveBeenCalledTimes(1));+ setEnabled(false);+ setPattern('sales');+ await waitFor(() => expect(preview.isEnabled).toBe(false));+ await client.invalidateQueries({ queryKey: channelLabelKeys._def });+ expect(mocks.preview).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/web/src/lib/queries/channel-labels/channel-labels.ts b/apps/web/src/lib/queries/channel-labels/channel-labels.tsnew file mode 100644index 0000000000..1f0f56aab2--- /dev/null+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.ts@@ -0,0 +1,206 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableChannelTags } from '@core/constant/featureFlags';+import { debouncedDependent } from '@core/util/debounce';+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';+import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';+import type { ChannelLabelsList } from '@service-storage/generated/schemas/channelLabelsList';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { queryClient } from '../client';+import { withCallbacks } from '../utils';+import { channelLabelKeys } from './keys';++export type { ChannelLabel };++/** Shared labels for team members; account-private labels otherwise. */+export function useChannelLabelsQuery() {+ const channelTagsFlag = useFeatureFlag(enableChannelTags);+ return useQuery(() => ({+ queryKey: channelLabelKeys.list.queryKey,+ enabled: channelTagsFlag().enabled,+ queryFn: async () =>+ await throwOnErr(() => storageServiceClient.channelLabels.list()),+ staleTime: 30_000,+ refetchInterval: (query) =>+ query.state.data?.labels.some((label) => label.rule) ? 30_000 : false,+ retry: false,+ }));+}++/** Non-suspending view of labels, undefined until successfully loaded. */+export function useChannelLabelsData(): Accessor<ChannelLabel[] | undefined> {+ const query = useChannelLabelsQuery();+ return () =>+ query.isEnabled && query.isSuccess ? query.data.labels : undefined;+}++export function invalidateChannelLabels() {+ return queryClient.invalidateQueries({+ queryKey: channelLabelKeys.list.queryKey,+ });+}++function writeLabels(update: (labels: ChannelLabel[]) => ChannelLabel[]) {+ queryClient.setQueryData<ChannelLabelsList>(+ channelLabelKeys.list.queryKey,+ (previous) =>+ previous ? { ...previous, labels: update(previous.labels) } : previous+ );+}++// Serialize writes, and publish only saved values. Temporary label IDs cannot+// be used as drop targets; snapshot rollback must not erase another saved edit.+const mutationScope = { id: 'channel-labels' };+async function cancelLabelFetch() {+ await queryClient.cancelQueries({ queryKey: channelLabelKeys.list.queryKey });+}++export function useSmartTagPreviewQuery(pattern: Accessor<string>) {+ const channelTagsFlag = useFeatureFlag(enableChannelTags);+ const debouncedPattern = debouncedDependent(pattern, 150);+ return useQuery(() => {+ const contains = pattern();+ return {+ queryKey: channelLabelKeys.preview(contains).queryKey,+ enabled:+ channelTagsFlag().enabled &&+ contains.length > 0 &&+ contains === debouncedPattern(),+ queryFn: async ({ signal }) =>+ await throwOnErr(() =>+ storageServiceClient.channelLabels.preview(+ { attribute: 'name', contains },+ signal+ )+ ),+ staleTime: 0,+ retry: false,+ };+ });+}++export type CreateChannelLabelArgs = {+ name: string;+ channelIds: string[];+ rule?: ChannelLabelRule;+};++export function useCreateChannelLabelMutation() {+ return useMutation(() => ({+ scope: mutationScope,+ mutationFn: async (args: CreateChannelLabelArgs) =>+ await throwOnErr(() => storageServiceClient.channelLabels.create(args)),+ ...withCallbacks<ChannelLabel, Error, CreateChannelLabelArgs>({+ onSuccess: async (created) => {+ await cancelLabelFetch();+ writeLabels((labels) =>+ labels+ .map((label) => {+ if (created.rule || label.rule) return label;+ const channelIds = label.channelIds.filter(+ (id) => !created.channelIds.includes(id)+ );+ return {+ ...label,+ channelIds,+ channelCount:+ label.channelCount -+ (label.channelIds.length - channelIds.length),+ };+ })+ .concat(created)+ );+ },+ onSettled: () => invalidateChannelLabels(),+ }),+ }));+}++export type RenameChannelLabelArgs = {+ labelId: string;+ name: string;+ rule?: ChannelLabelRule;+};+export function useRenameChannelLabelMutation() {+ return useMutation(() => ({+ scope: mutationScope,+ mutationFn: async (args: RenameChannelLabelArgs) =>+ await throwOnErr(() =>+ storageServiceClient.channelLabels.rename(args.labelId, {+ name: args.name,+ rule: args.rule,+ })+ ),+ ...withCallbacks<ChannelLabel, Error, RenameChannelLabelArgs>({+ onSuccess: async (renamed) => {+ await cancelLabelFetch();+ writeLabels((labels) =>+ labels.map((label) => (label.id === renamed.id ? renamed : label))+ );+ },+ onSettled: () => invalidateChannelLabels(),+ }),+ }));+}++export type DeleteChannelLabelArgs = { labelId: string };+export function useDeleteChannelLabelMutation() {+ return useMutation(() => ({+ scope: mutationScope,+ mutationFn: async (args: DeleteChannelLabelArgs) =>+ await throwOnErr(() =>+ storageServiceClient.channelLabels.remove(args.labelId)+ ),+ ...withCallbacks<void, Error, DeleteChannelLabelArgs>({+ onSuccess: async (_data, args) => {+ await cancelLabelFetch();+ writeLabels((labels) =>+ labels.filter((label) => label.id !== args.labelId)+ );+ },+ onSettled: () => invalidateChannelLabels(),+ }),+ }));+}++export type SetChannelLabelArgs = {+ channelId: string;+ labelId: string | undefined;+};+export function useSetChannelLabelMutation() {+ return useMutation(() => ({+ scope: mutationScope,+ mutationFn: async (args: SetChannelLabelArgs) =>+ await throwOnErr(() =>+ storageServiceClient.channelLabels.setChannelLabel(args.channelId, {+ labelId: args.labelId ?? null,+ })+ ),+ ...withCallbacks<void, Error, SetChannelLabelArgs>({+ onSuccess: async (_data, args) => {+ await cancelLabelFetch();+ writeLabels((labels) =>+ labels.map((label) => {+ if (label.rule) return label;+ const channelIds = label.channelIds.filter(+ (id) => id !== args.channelId+ );+ const removed = label.channelIds.length - channelIds.length;+ if (label.id === args.labelId) channelIds.push(args.channelId);+ return {+ ...label,+ channelIds,+ channelCount:+ label.channelCount -+ removed ++ (label.id === args.labelId ? 1 : 0),+ };+ })+ );+ },+ onSettled: () => invalidateChannelLabels(),+ }),+ }));+}diff --git a/apps/web/src/lib/queries/channel-labels/keys.ts b/apps/web/src/lib/queries/channel-labels/keys.tsnew file mode 100644index 0000000000..bcd5d215e8--- /dev/null+++ b/apps/web/src/lib/queries/channel-labels/keys.ts@@ -0,0 +1,6 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';++export const channelLabelKeys = createQueryKeys('channel-labels', {+ list: null,+ preview: (pattern: string) => [pattern],+});diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 1672c9b329..14d8ea3d52 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -45,12 +45,16 @@ import type { CalendarMentionPreviewResponse } from './generated/schemas/calendaimport type { CalendarOccurrenceResponse } from './generated/schemas/calendarOccurrenceResponse';import type { CallRecordPreview } from './generated/schemas/callRecordPreview';import type { ChannelJoinCodeResponse } from './generated/schemas/channelJoinCodeResponse';+import type { ChannelLabel } from './generated/schemas/channelLabel';+import type { ChannelLabelRule } from './generated/schemas/channelLabelRule';+import type { ChannelLabelsList } from './generated/schemas/channelLabelsList';import { ChannelType } from './generated/schemas/channelType';import {type CloudStorageItemType,CloudStorageItemType as CloudStorageItemTypeMap,} from './generated/schemas/cloudStorageItemType';import type { CreateAgentRequest } from './generated/schemas/createAgentRequest';+import type { CreateChannelLabelRequest } from './generated/schemas/createChannelLabelRequest';import type { CreateChannelRequest } from './generated/schemas/createChannelRequest';import type { CreateChannelResponse } from './generated/schemas/createChannelResponse';import type { CreateChannelScopedBotRequest } from './generated/schemas/createChannelScopedBotRequest';@@ -139,14 +143,17 @@ import type { Project } from './generated/schemas/project';import type { Reminder } from './generated/schemas/reminder';import type { RemindersList } from './generated/schemas/remindersList';import type { RemoveParticipantsRequest } from './generated/schemas/removeParticipantsRequest';+import type { RenameChannelLabelRequest } from './generated/schemas/renameChannelLabelRequest';import type { ReorderFavoritesRequest } from './generated/schemas/reorderFavoritesRequest';import type { ReorderPinRequest } from './generated/schemas/reorderPinRequest';import type { ReplaceCrmStagesRequest } from './generated/schemas/replaceCrmStagesRequest';import type { SaveDocumentResponseData } from './generated/schemas/saveDocumentResponseData';+import type { SetChannelLabelRequest } from './generated/schemas/setChannelLabelRequest';import type { SetChannelPictureRequest } from './generated/schemas/setChannelPictureRequest';import type { SetCompanyNameRequest } from './generated/schemas/setCompanyNameRequest';import type { SetContactNameRequest } from './generated/schemas/setContactNameRequest';import type { SharePermissionV2 } from './generated/schemas/sharePermissionV2';+import type { SmartTagPreview } from './generated/schemas/smartTagPreview';import type { SoupPage } from './generated/schemas/soupPage';import type { SyncServiceVersionID } from './generated/schemas/syncServiceVersionID';import type { TeamOutOfOfficeResponse } from './generated/schemas/teamOutOfOfficeResponse';@@ -2364,6 +2371,42 @@ export const storageServiceClient = {},},+ channelLabels: {+ async preview(rule: ChannelLabelRule, signal?: AbortSignal) {+ return await dssFetch<SmartTagPreview>('/channel-labels/preview', {+ method: 'POST',+ body: JSON.stringify(rule),+ signal,+ });+ },+ /** Every label of the caller's team; `channelIds` is limited to channels the caller is in. */+ async list() {+ return await dssFetch<ChannelLabelsList>('/channel-labels');+ },+ async create(params: CreateChannelLabelRequest) {+ return await dssFetch<ChannelLabel>('/channel-labels', {+ method: 'POST',+ body: JSON.stringify(params),+ });+ },+ async rename(labelId: string, params: RenameChannelLabelRequest) {+ return await dssFetch<ChannelLabel>(+ `/channel-labels/${encodeURIComponent(labelId)}`,+ { method: 'PATCH', body: JSON.stringify(params) }+ );+ },+ async remove(labelId: string) {+ return await dssFetch(`/channel-labels/${encodeURIComponent(labelId)}`, {+ method: 'DELETE',+ });+ },+ async setChannelLabel(channelId: string, params: SetChannelLabelRequest) {+ return await dssFetch(+ `/channel-labels/channels/${encodeURIComponent(channelId)}`,+ { method: 'PUT', body: JSON.stringify(params) }+ );+ },+ },favorites: {async getFavorites(params?: ListFavoritesParams) {const query = new URLSearchParams();diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.tsnew file mode 100644index 0000000000..2430911458--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabel.ts@@ -0,0 +1,35 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabelRuleProperty } from './channelLabelRuleProperty';+import type { ChannelLabelTeamId } from './channelLabelTeamId';++/**+ * A shared or account-private label grouping chat channels in the sidebar.++`channel_ids` is viewer-relative: it lists only the labelled channels the+requesting user participates in. `channel_count` counts every channel in+the label so clients can warn accurately before a delete.+ */+export interface ChannelLabel {+ /** All assignments for a manual label; visible matches for a smart tag. */+ channelCount: number;+ /** Channels in this label that the requesting user participates in. */+ channelIds: string[];+ /** When the label was created. */+ createdAt: string;+ /** Stable label id. */+ id: string;+ /** Display name, unique within the scope (case-insensitive). */+ name: string;+ rule?: ChannelLabelRuleProperty;+ /** Manual ordering value within the scope; lower sorts first. */+ sortOrder: number;+ /** Owning team, or `None` for account-private labels. */+ teamId?: ChannelLabelTeamId;+ /** When the label was last renamed or reordered. */+ updatedAt: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRule.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRule.tsnew file mode 100644index 0000000000..58dedc2e0d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRule.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabelRuleOneOf } from './channelLabelRuleOneOf';++/**+ * An attribute rule that automatically groups matching channels.+ */+export type ChannelLabelRule = ChannelLabelRuleOneOf;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleOneOf.tsnew file mode 100644index 0000000000..4d05087a0f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleOneOf.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabelRuleOneOfAttribute } from './channelLabelRuleOneOfAttribute';++/**+ * Case-insensitive, literal substring matching on the channel name.+ */+export type ChannelLabelRuleOneOf = {+ attribute: ChannelLabelRuleOneOfAttribute;+ /** The substring to find anywhere in the name. */+ contains: string;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleOneOfAttribute.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleOneOfAttribute.tsnew file mode 100644index 0000000000..2a85040e64--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleOneOfAttribute.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ChannelLabelRuleOneOfAttribute =+ (typeof ChannelLabelRuleOneOfAttribute)[keyof typeof ChannelLabelRuleOneOfAttribute];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ChannelLabelRuleOneOfAttribute = {+ name: 'name',+} as const;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleProperty.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleProperty.tsnew file mode 100644index 0000000000..5e48a60bf2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelRuleProperty.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabelRule } from './channelLabelRule';++export type ChannelLabelRuleProperty = null | ChannelLabelRule;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelTeamId.tsnew file mode 100644index 0000000000..9f03a401d4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Owning team, or `None` for account-private labels.+ */+export type ChannelLabelTeamId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelsList.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelsList.tsnew file mode 100644index 0000000000..5dc2ed1912--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelsList.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabel } from './channelLabel';+import type { ChannelLabelsListTeamId } from './channelLabelsListTeamId';++/**+ * The authorized scope's labels in manual order.+ */+export interface ChannelLabelsList {+ /** Every label of the scope, whether or not the caller sees channels in it. */+ labels: ChannelLabel[];+ /** Team scope, or `None` for private labels. */+ teamId?: ChannelLabelsListTeamId;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelsListTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelsListTeamId.tsnew file mode 100644index 0000000000..f3d1ed2e8d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelsListTeamId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Team scope, or `None` for private labels.+ */+export type ChannelLabelsListTeamId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelRequest.tsnew file mode 100644index 0000000000..0a351b8178--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelRequest.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CreateChannelLabelRequestRule } from './createChannelLabelRequestRule';++/**+ * Request body for creating a label.+ */+export interface CreateChannelLabelRequest {+ /** Channels to move into the new label. */+ channelIds?: string[];+ /** Display name; unique within the scope, case-insensitively. */+ name: string;+ rule?: CreateChannelLabelRequestRule;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelRequestRule.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelRequestRule.tsnew file mode 100644index 0000000000..39253a6f19--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelRequestRule.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabelRule } from './channelLabelRule';++export type CreateChannelLabelRequestRule = null | ChannelLabelRule;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.tsindex bcab674e0f..463576e13c 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts@@ -298,6 +298,14 @@ export * from './channelFiltersIsParticipant';export * from './channelFiltersOrgId';export * from './channelFiltersTeamId';export * from './channelJoinCodeResponse';+export * from './channelLabel';+export * from './channelLabelRule';+export * from './channelLabelRuleOneOf';+export * from './channelLabelRuleOneOfAttribute';+export * from './channelLabelRuleProperty';+export * from './channelLabelsList';+export * from './channelLabelsListTeamId';+export * from './channelLabelTeamId';export * from './channelMessage';export * from './channelMessageDeletedAt';export * from './channelMessageFilters';@@ -376,6 +384,8 @@ export * from './createBulkDocumentResponse';export * from './createBulkDocumentResponseData';export * from './createBulkDocumentResponseDataDocumentMetadata';export * from './createBulkDocumentResponseDataPresignedUrl';+export * from './createChannelLabelRequest';+export * from './createChannelLabelRequestRule';export * from './createChannelRequest';export * from './createChannelRequestName';export * from './createChannelRequestTeamId';@@ -1142,6 +1152,8 @@ export * from './reminderScheduleOneOfType';export * from './remindersList';export * from './remindersListNextCursor';export * from './removeParticipantsRequest';+export * from './renameChannelLabelRequest';+export * from './renameChannelLabelRequestRule';export * from './reorderFavoritesRequest';export * from './reorderPinRequest';export * from './replaceCrmStagesRequest';@@ -1167,6 +1179,8 @@ export * from './sessionSettledMetadata';export * from './sessionSettledMetadataLastTurn';export * from './sessionStoppedMetadata';export * from './sessionStoppedMetadataTurnInFlight';+export * from './setChannelLabelRequest';+export * from './setChannelLabelRequestLabelId';export * from './setChannelPictureRequest';export * from './setChannelPictureRequestProfilePictureId';export * from './setCompanyHiddenRequest';@@ -1204,6 +1218,8 @@ export * from './sharePermissionV2LinkShareAccessLevel';export * from './sharePermissionV2TeamShareAccessLevel';export * from './shortIdResponse';export * from './simpleMention';+export * from './smartTagChannelMatch';+export * from './smartTagPreview';export * from './soupAgentSessionSoupPropertiesField';export * from './soupAgentSessionSoupPropertiesFieldAllOf';export * from './soupAgentSessionSoupPropertiesFieldAllOfTwo';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.tsnew file mode 100644index 0000000000..116ed60f07--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequest.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { RenameChannelLabelRequestRule } from './renameChannelLabelRequestRule';++/**+ * Request body for renaming a label.+ */+export interface RenameChannelLabelRequest {+ /** New display name. */+ name: string;+ rule?: RenameChannelLabelRequestRule;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequestRule.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequestRule.tsnew file mode 100644index 0000000000..8a8094b35c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelRequestRule.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ChannelLabelRule } from './channelLabelRule';++export type RenameChannelLabelRequestRule = null | ChannelLabelRule;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelRequest.tsnew file mode 100644index 0000000000..3e4bd96388--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SetChannelLabelRequestLabelId } from './setChannelLabelRequestLabelId';++/**+ * Request body for moving a channel between labels.+ */+export interface SetChannelLabelRequest {+ /** The label to put the channel in, or `null` to remove it from its label. */+ labelId?: SetChannelLabelRequestLabelId;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelRequestLabelId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelRequestLabelId.tsnew file mode 100644index 0000000000..b5608cd186--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelRequestLabelId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The label to put the channel in, or `null` to remove it from its label.+ */+export type SetChannelLabelRequestLabelId = string | null;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/smartTagChannelMatch.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/smartTagChannelMatch.tsnew file mode 100644index 0000000000..278ee6ea85--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/smartTagChannelMatch.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A channel visible to the caller that matches a smart tag rule.+ */+export interface SmartTagChannelMatch {+ /** Channel id. */+ id: string;+ /** Channel display name. */+ name: string;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/smartTagPreview.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/smartTagPreview.tsnew file mode 100644index 0000000000..7093681775--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/smartTagPreview.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { SmartTagChannelMatch } from './smartTagChannelMatch';++/**+ * A bounded preview and the total number of visible channels matching a rule.+ */+export interface SmartTagPreview {+ /** First matches, in alphabetical order. */+ channels: SmartTagChannelMatch[];+ /** Number of matching channels the caller participates in, including overflow. */+ totalCount: number;+}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex a6fe41696f..f621a3f77d 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -2311,6 +2311,305 @@ export const ingestTranscriptBody = zod}).describe('A transcript segment from LiveKit Inference STT.');+/**+ * @summary List the caller's shared or private labels.+ */+export const listChannelLabelsResponse = zod+ .object({+ labels: zod+ .array(+ zod+ .object({+ channelCount: zod+ .number()+ .describe(+ 'All assignments for a manual label; visible matches for a smart tag.'+ ),+ channelIds: zod+ .array(zod.uuid())+ .describe(+ 'Channels in this label that the requesting user participates in.'+ ),+ createdAt: zod.iso+ .datetime({})+ .describe('When the label was created.'),+ id: zod.uuid().describe('Stable label id.'),+ name: zod+ .string()+ .describe(+ 'Display name, unique within the scope (case-insensitive).'+ ),+ rule: zod+ .union([+ zod.null(),+ zod+ .object({+ attribute: zod.enum(['name']),+ contains: zod+ .string()+ .describe('The substring to find anywhere in the name.'),+ })+ .describe(+ 'Case-insensitive, literal substring matching on the channel name.'+ )+ .describe(+ 'An attribute rule that automatically groups matching channels.'+ ),+ ])+ .optional(),+ sortOrder: zod+ .number()+ .describe(+ 'Manual ordering value within the scope; lower sorts first.'+ ),+ teamId: zod+ .uuid()+ .nullish()+ .describe('Owning team, or `None` for account-private labels.'),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the label was last renamed or reordered.'),+ })+ .describe(+ 'A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.'+ )+ )+ .describe(+ 'Every label of the scope, whether or not the caller sees channels in it.'+ ),+ teamId: zod+ .uuid()+ .nullish()+ .describe('Team scope, or `None` for private labels.'),+ })+ .describe("The authorized scope's labels in manual order.");++/**+ * @summary Create a label for the caller's authorized scope.+ */+export const createChannelLabelBody = zod+ .object({+ channelIds: zod+ .array(zod.uuid())+ .optional()+ .describe('Channels to move into the new label.'),+ name: zod+ .string()+ .describe('Display name; unique within the scope, case-insensitively.'),+ rule: zod+ .union([+ zod.null(),+ zod+ .object({+ attribute: zod.enum(['name']),+ contains: zod+ .string()+ .describe('The substring to find anywhere in the name.'),+ })+ .describe(+ 'Case-insensitive, literal substring matching on the channel name.'+ )+ .describe(+ 'An attribute rule that automatically groups matching channels.'+ ),+ ])+ .optional(),+ })+ .describe('Request body for creating a label.');++export const createChannelLabelResponse = zod+ .object({+ channelCount: zod+ .number()+ .describe(+ 'All assignments for a manual label; visible matches for a smart tag.'+ ),+ channelIds: zod+ .array(zod.uuid())+ .describe(+ 'Channels in this label that the requesting user participates in.'+ ),+ createdAt: zod.iso.datetime({}).describe('When the label was created.'),+ id: zod.uuid().describe('Stable label id.'),+ name: zod+ .string()+ .describe('Display name, unique within the scope (case-insensitive).'),+ rule: zod+ .union([+ zod.null(),+ zod+ .object({+ attribute: zod.enum(['name']),+ contains: zod+ .string()+ .describe('The substring to find anywhere in the name.'),+ })+ .describe(+ 'Case-insensitive, literal substring matching on the channel name.'+ )+ .describe(+ 'An attribute rule that automatically groups matching channels.'+ ),+ ])+ .optional(),+ sortOrder: zod+ .number()+ .describe('Manual ordering value within the scope; lower sorts first.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe('Owning team, or `None` for account-private labels.'),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the label was last renamed or reordered.'),+ })+ .describe(+ 'A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.'+ );++/**+ * @summary Move a channel into a label of the caller's authorized scope, or out of any label.+ */+export const setChannelLabelParams = zod.object({+ channel_id: zod.uuid().describe('The channel id.'),+});++export const setChannelLabelBody = zod+ .object({+ labelId: zod+ .uuid()+ .nullish()+ .describe(+ 'The label to put the channel in, or `null` to remove it from its label.'+ ),+ })+ .describe('Request body for moving a channel between labels.');++/**+ * @summary Preview visible channels matched by a smart tag, without creating it.+ */+export const previewSmartTagBody = zod+ .object({+ attribute: zod.enum(['name']),+ contains: zod+ .string()+ .describe('The substring to find anywhere in the name.'),+ })+ .describe('Case-insensitive, literal substring matching on the channel name.')+ .describe('An attribute rule that automatically groups matching channels.');++export const previewSmartTagResponse = zod+ .object({+ channels: zod+ .array(+ zod+ .object({+ id: zod.uuid().describe('Channel id.'),+ name: zod.string().describe('Channel display name.'),+ })+ .describe(+ 'A channel visible to the caller that matches a smart tag rule.'+ )+ )+ .describe('First matches, in alphabetical order.'),+ totalCount: zod+ .number()+ .describe(+ 'Number of matching channels the caller participates in, including overflow.'+ ),+ })+ .describe(+ 'A bounded preview and the total number of visible channels matching a rule.'+ );++/**+ * @summary Delete a label of the caller's authorized scope. Its channels return to the plain list.+ */+export const deleteChannelLabelParams = zod.object({+ label_id: zod.uuid().describe('The label id.'),+});++/**+ * @summary Rename a label of the caller's authorized scope.+ */+export const renameChannelLabelParams = zod.object({+ label_id: zod.uuid().describe('The label id.'),+});++export const renameChannelLabelBody = zod+ .object({+ name: zod.string().describe('New display name.'),+ rule: zod+ .union([+ zod.null(),+ zod+ .object({+ attribute: zod.enum(['name']),+ contains: zod+ .string()+ .describe('The substring to find anywhere in the name.'),+ })+ .describe(+ 'Case-insensitive, literal substring matching on the channel name.'+ )+ .describe(+ 'An attribute rule that automatically groups matching channels.'+ ),+ ])+ .optional(),+ })+ .describe('Request body for renaming a label.');++export const renameChannelLabelResponse = zod+ .object({+ channelCount: zod+ .number()+ .describe(+ 'All assignments for a manual label; visible matches for a smart tag.'+ ),+ channelIds: zod+ .array(zod.uuid())+ .describe(+ 'Channels in this label that the requesting user participates in.'+ ),+ createdAt: zod.iso.datetime({}).describe('When the label was created.'),+ id: zod.uuid().describe('Stable label id.'),+ name: zod+ .string()+ .describe('Display name, unique within the scope (case-insensitive).'),+ rule: zod+ .union([+ zod.null(),+ zod+ .object({+ attribute: zod.enum(['name']),+ contains: zod+ .string()+ .describe('The substring to find anywhere in the name.'),+ })+ .describe(+ 'Case-insensitive, literal substring matching on the channel name.'+ )+ .describe(+ 'An attribute rule that automatically groups matching channels.'+ ),+ ])+ .optional(),+ sortOrder: zod+ .number()+ .describe('Manual ordering value within the scope; lower sorts first.'),+ teamId: zod+ .uuid()+ .nullish()+ .describe('Owning team, or `None` for account-private labels.'),+ updatedAt: zod.iso+ .datetime({})+ .describe('When the label was last renamed or reordered.'),+ })+ .describe(+ 'A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.'+ );+/*** @summary Handler for `POST /channels`.*/diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 6034716949..0f0c4588cf 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -1861,6 +1861,458 @@}}},+ "/channel-labels": {+ "get": {+ "tags": ["channel_labels"],+ "summary": "List the caller's shared or private labels.",+ "operationId": "list_channel_labels",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabelsList"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["channel_labels"],+ "summary": "Create a label for the caller's authorized scope.",+ "operationId": "create_channel_label",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateChannelLabelRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabel"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channel-labels/channels/{channel_id}": {+ "put": {+ "tags": ["channel_labels"],+ "summary": "Move a channel into a label of the caller's authorized scope, or out of any label.",+ "operationId": "set_channel_label",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "The channel id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetChannelLabelRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channel-labels/preview": {+ "post": {+ "tags": ["channel_labels"],+ "summary": "Preview visible channels matched by a smart tag, without creating it.",+ "operationId": "preview_smart_tag",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabelRule"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SmartTagPreview"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channel-labels/{label_id}": {+ "delete": {+ "tags": ["channel_labels"],+ "summary": "Delete a label of the caller's authorized scope. Its channels return to the plain list.",+ "operationId": "delete_channel_label",+ "parameters": [+ {+ "name": "label_id",+ "in": "path",+ "description": "The label id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["channel_labels"],+ "summary": "Rename a label of the caller's authorized scope.",+ "operationId": "rename_channel_label",+ "parameters": [+ {+ "name": "label_id",+ "in": "path",+ "description": "The label id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RenameChannelLabelRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabel"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/channels": {"post": {"tags": ["channels"],@@ -17432,6 +17884,113 @@}}},+ "ChannelLabel": {+ "type": "object",+ "description": "A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.",+ "required": [+ "id",+ "name",+ "sortOrder",+ "channelIds",+ "channelCount",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "channelCount": {+ "type": "integer",+ "format": "int64",+ "description": "All assignments for a manual label; visible matches for a smart tag."+ },+ "channelIds": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Channels in this label that the requesting user participates in."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the label was created."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Stable label id."+ },+ "name": {+ "type": "string",+ "description": "Display name, unique within the scope (case-insensitive)."+ },+ "rule": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelLabelRule",+ "description": "Automatic membership rule, or `None` for a manually managed label."+ }+ ]+ },+ "sortOrder": {+ "type": "number",+ "format": "double",+ "description": "Manual ordering value within the scope; lower sorts first."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Owning team, or `None` for account-private labels."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the label was last renamed or reordered."+ }+ }+ },+ "ChannelLabelRule": {+ "oneOf": [+ {+ "type": "object",+ "description": "Case-insensitive, literal substring matching on the channel name.",+ "required": ["contains", "attribute"],+ "properties": {+ "attribute": {+ "type": "string",+ "enum": ["name"]+ },+ "contains": {+ "type": "string",+ "description": "The substring to find anywhere in the name."+ }+ }+ }+ ],+ "description": "An attribute rule that automatically groups matching channels."+ },+ "ChannelLabelsList": {+ "type": "object",+ "description": "The authorized scope's labels in manual order.",+ "required": ["labels"],+ "properties": {+ "labels": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ChannelLabel"+ },+ "description": "Every label of the scope, whether or not the caller sees channels in it."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team scope, or `None` for private labels."+ }+ }+ },"ChannelMentionedMetadata": {"type": "object","description": "Metadata for [`ChannelTopicEvent::Mentioned`].",@@ -18720,6 +19279,36 @@}}},+ "CreateChannelLabelRequest": {+ "type": "object",+ "description": "Request body for creating a label.",+ "required": ["name"],+ "properties": {+ "channelIds": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Channels to move into the new label."+ },+ "name": {+ "type": "string",+ "description": "Display name; unique within the scope, case-insensitively."+ },+ "rule": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelLabelRule",+ "description": "Automatic name-matching rule; omitted for manual labels or a name-only rename."+ }+ ]+ }+ }+ },"CreateChannelRequest": {"type": "object","description": "Request to create a channel.",@@ -26862,6 +27451,28 @@}}},+ "RenameChannelLabelRequest": {+ "type": "object",+ "description": "Request body for renaming a label.",+ "required": ["name"],+ "properties": {+ "name": {+ "type": "string",+ "description": "New display name."+ },+ "rule": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelLabelRule",+ "description": "Automatic name-matching rule; omitted for manual labels or a name-only rename."+ }+ ]+ }+ }+ },"ReorderFavoritesRequest": {"type": "object","description": "Request body for reordering favorites.",@@ -27177,6 +27788,17 @@}}},+ "SetChannelLabelRequest": {+ "type": "object",+ "description": "Request body for moving a channel between labels.",+ "properties": {+ "labelId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The label to put the channel in, or `null` to remove it from its label."+ }+ }+ },"SetChannelPictureRequest": {"type": "object","description": "Replace a channel's picture, or remove it by sending a null file id.",@@ -27497,6 +28119,41 @@}}},+ "SmartTagChannelMatch": {+ "type": "object",+ "description": "A channel visible to the caller that matches a smart tag rule.",+ "required": ["id", "name"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel id."+ },+ "name": {+ "type": "string",+ "description": "Channel display name."+ }+ }+ },+ "SmartTagPreview": {+ "type": "object",+ "description": "A bounded preview and the total number of visible channels matching a rule.",+ "required": ["channels", "totalCount"],+ "properties": {+ "channels": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/SmartTagChannelMatch"+ },+ "description": "First matches, in alphabetical order."+ },+ "totalCount": {+ "type": "integer",+ "format": "int64",+ "description": "Number of matching channels the caller participates in, including overflow."+ }+ }+ },"SoupAgentSession_SoupPropertiesField": {"allOf": [{diff --git a/crates/channel_labels/Cargo.toml b/crates/channel_labels/Cargo.tomlnew file mode 100644index 0000000000..e69c10b5f8--- /dev/null+++ b/crates/channel_labels/Cargo.toml@@ -0,0 +1,43 @@+[package]+edition = "2024"+name = "channel_labels"+publish = false+version = "0.1.0"++[features]+default = []+inbound = [+ "dep:axum",+ "dep:macro_authorization",+ "dep:model-error-response",+ "dep:utoipa",+ "entity_access/axum",+ "entity_access/inbound",+ "ports",+]+outbound = ["ports"]+ports = ["dep:tokio", "dep:tracing"]+postgres = ["dep:sqlx", "outbound"]++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true, optional = true }+chrono = { workspace = true, features = ["serde"] }+cowlike = { path = "../cowlike" }+entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }+macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = ["axum"] }+macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }+model-error-response = { path = "../model-error-response", optional = true }+serde = { workspace = true }+sqlx = { workspace = true, optional = true }+thiserror = { workspace = true }+tokio = { workspace = true, optional = true }+tracing = { workspace = true, optional = true }+utoipa = { workspace = true, optional = true }+uuid = { workspace = true, features = ["serde", "v7"] }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/channel_labels/src/domain.rs b/crates/channel_labels/src/domain.rsnew file mode 100644index 0000000000..b5a87b1e2d--- /dev/null+++ b/crates/channel_labels/src/domain.rs@@ -0,0 +1,5 @@+//! Domain layer: models, ports, and the channel labels service.++pub mod models;+pub mod ports;+pub mod service;diff --git a/crates/channel_labels/src/domain/models.rs b/crates/channel_labels/src/domain/models.rsnew file mode 100644index 0000000000..417eb118a9--- /dev/null+++ b/crates/channel_labels/src/domain/models.rs@@ -0,0 +1,243 @@+//! Domain models for channel labels.++use chrono::{DateTime, Utc};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// Longest accepted label name, in characters.+pub const MAX_LABEL_NAME_LEN: usize = 80;++/// Longest accepted substring for name matching.+pub const MAX_SMART_TAG_PATTERN_LEN: usize = 200;++/// An attribute rule that automatically groups matching channels.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(tag = "attribute", rename_all = "snake_case")]+pub enum ChannelLabelRule {+ /// Case-insensitive, literal substring matching on the channel name.+ Name {+ /// The substring to find anywhere in the name.+ contains: String,+ },+}++impl ChannelLabelRule {+ /// Substring for the currently supported name attribute.+ pub fn name_contains(&self) -> &str {+ match self {+ Self::Name { contains } => contains,+ }+ }+}++/// A channel visible to the caller that matches a smart tag rule.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct SmartTagChannelMatch {+ /// Channel id.+ pub id: Uuid,+ /// Channel display name.+ pub name: String,+}++/// A bounded preview and the total number of visible channels matching a rule.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SmartTagPreview {+ /// First matches, in alphabetical order.+ pub channels: Vec<SmartTagChannelMatch>,+ /// Number of matching channels the caller participates in, including overflow.+ pub total_count: i64,+}++/// A shared or account-private label grouping chat channels in the sidebar.+///+/// `channel_ids` is viewer-relative: it lists only the labelled channels the+/// requesting user participates in. `channel_count` counts every channel in+/// the label so clients can warn accurately before a delete.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct ChannelLabel {+ /// Stable label id.+ pub id: Uuid,+ /// Owning team, or `None` for account-private labels.+ pub team_id: Option<Uuid>,+ /// Display name, unique within the scope (case-insensitive).+ pub name: String,+ /// Automatic membership rule, or `None` for a manually managed label.+ pub rule: Option<ChannelLabelRule>,+ /// Manual ordering value within the scope; lower sorts first.+ pub sort_order: f64,+ /// Channels in this label that the requesting user participates in.+ pub channel_ids: Vec<Uuid>,+ /// All assignments for a manual label; visible matches for a smart tag.+ pub channel_count: i64,+ /// When the label was created.+ pub created_at: DateTime<Utc>,+ /// When the label was last renamed or reordered.+ pub updated_at: DateTime<Utc>,+}++/// The authorized scope's labels in manual order.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct ChannelLabelsList {+ /// Team scope, or `None` for private labels.+ pub team_id: Option<Uuid>,+ /// Every label of the scope, whether or not the caller sees channels in it.+ pub labels: Vec<ChannelLabel>,+}++/// A label to create, with the channels to put in it right away.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NewChannelLabel {+ /// Display name.+ pub name: String,+ /// Automatic membership rule; smart tags cannot have manual assignments.+ pub rule: Option<ChannelLabelRule>,+ /// Channels to move into the new label.+ pub channel_ids: Vec<Uuid>,+}++/// Result of persisting a new or renamed label.+#[derive(Debug, Clone, PartialEq)]+pub enum LabelWriteOutcome {+ /// The label as stored.+ Written(ChannelLabel),+ /// Another label of the scope already has this name.+ NameTaken,+ /// The label to rename does not exist in the scope.+ NotFound,+ /// A requested channel is missing, inaccessible, or a direct message.+ InvalidChannel(SetChannelLabelOutcome),+}++/// Result of changing which label a channel belongs to.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SetChannelLabelOutcome {+ /// The channel now carries the requested label (or none).+ Updated,+ /// No such channel, or the actor may not see it.+ ChannelNotFound,+ /// The target label does not exist in the scope.+ LabelNotFound,+ /// The channel kind cannot be labelled (direct messages).+ ChannelNotLabelable,+ /// Smart tag membership is determined by its rule, not manual assignments.+ SmartTagReadOnly,+}++/// Namespace in which channel labels and assignments are isolated.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ChannelLabelsScope {+ /// Labels shared by a verified team member.+ Team(Uuid),+ /// Labels private to the authenticated account.+ User(MacroUserIdStr<'static>),+}++impl ChannelLabelsScope {+ /// Stable persistence key for this namespace.+ pub fn key(&self) -> String {+ match self {+ Self::Team(id) => format!("team:{id}"),+ Self::User(id) => format!("user:{id}"),+ }+ }++ /// Team owning this namespace, if shared.+ pub fn team_id(&self) -> Option<Uuid> {+ match self {+ Self::Team(id) => Some(*id),+ Self::User(_) => None,+ }+ }++ /// Account owning this namespace, if private.+ pub fn owner_id(&self) -> Option<&str> {+ match self {+ Self::Team(_) => None,+ Self::User(id) => Some(id.as_ref()),+ }+ }+}++/// Authorized label namespace and the authenticated viewer.+#[derive(Debug)]+pub struct ChannelLabelsReceipt {+ scope: ChannelLabelsScope,+ user_id: MacroUserIdStr<'static>,+}++impl ChannelLabelsReceipt {+ /// Resolve shared labels from a verified team receipt, otherwise private+ /// labels from the authenticated identity. The receipt must belong to that identity.+ pub fn from_access(+ user_id: MacroUserIdStr<'static>,+ receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+ ) -> Result<Self, ChannelLabelsError> {+ let scope = match receipt {+ Some(receipt) => {+ if receipt.entity().entity_type != EntityType::Team+ || receipt+ .get_authenticated_user()+ .map_err(|_| ChannelLabelsError::Unauthorized)?+ != &user_id+ {+ return Err(ChannelLabelsError::Unauthorized);+ }+ let team_id = Uuid::parse_str(&receipt.entity().entity_id)+ .map_err(|_| ChannelLabelsError::Unauthorized)?;+ ChannelLabelsScope::Team(team_id)+ }+ None => ChannelLabelsScope::User(user_id.clone()),+ };+ Ok(Self { scope, user_id })+ }++ /// Authorized namespace for this call.+ pub fn scope(&self) -> &ChannelLabelsScope {+ &self.scope+ }++ /// Authenticated viewer making the call.+ pub fn user_id(&self) -> &MacroUserIdStr<'static> {+ &self.user_id+ }++ /// Test-only team receipt without an access check.+ #[cfg(test)]+ pub(crate) fn dangerously_internal(team_id: Uuid, user_id: &str) -> Self {+ Self {+ scope: ChannelLabelsScope::Team(team_id),+ user_id: MacroUserIdStr::try_from(user_id.to_owned()).expect("valid user id"),+ }+ }+}++/// Errors returned by the channel labels service.+#[derive(Debug, thiserror::Error)]+pub enum ChannelLabelsError {+ /// The label or channel could not be found in the scope.+ #[error("{0}")]+ NotFound(&'static str),+ /// Another label of the scope already uses this name.+ #[error("a label named \"{0}\" already exists")]+ NameTaken(String),+ /// The request was invalid.+ #[error("{0}")]+ BadRequest(String),+ /// The caller is not an authenticated member of the scope.+ #[error("you do not have access to these labels")]+ Unauthorized,+ /// Any other internal error.+ #[error(transparent)]+ Internal(#[from] anyhow::Error),+}diff --git a/crates/channel_labels/src/domain/ports.rs b/crates/channel_labels/src/domain/ports.rsnew file mode 100644index 0000000000..9087025c55--- /dev/null+++ b/crates/channel_labels/src/domain/ports.rs@@ -0,0 +1,139 @@+//! Ports (trait contracts) for the channel labels domain.++use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use crate::domain::models::{+ ChannelLabel, ChannelLabelRule, ChannelLabelsError, ChannelLabelsReceipt, ChannelLabelsScope,+ LabelWriteOutcome, NewChannelLabel, SetChannelLabelOutcome, SmartTagPreview,+};++/// Outbound persistence port for channel labels.+pub trait ChannelLabelsRepo: Send + Sync + 'static {+ /// The error type returned by repository operations.+ type Err: Send + std::fmt::Debug;++ /// Every label of the scope in manual order. `channel_ids` on each label+ /// is restricted to channels `viewer` participates in. Manual counts include+ /// all assignments; smart counts include only the viewer's active matches.+ /// Smart memberships are evaluated from current attributes, including matches+ /// already present in another smart tag or manual label.+ fn list_labels(+ &self,+ scope: &ChannelLabelsScope,+ viewer: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Vec<ChannelLabel>, Self::Err>> + Send;++ /// One label of the scope, viewer-relative like [`Self::list_labels`].+ fn get_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ viewer: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<Option<ChannelLabel>, Self::Err>> + Send;++ /// Append a label to the scope's list. `name` is already trimmed and+ /// validated. Creation and all channel assignments must commit atomically.+ /// The viewer must actively participate in every requested non-DM channel;+ /// invalid channels must leave the label and all assignments unchanged.+ /// A validated smart rule is persisted without any manual assignments.+ fn create_label(+ &self,+ scope: &ChannelLabelsScope,+ name: &str,+ channel_ids: &[Uuid],+ viewer: &MacroUserIdStr<'_>,+ rule: Option<&ChannelLabelRule>,+ ) -> impl Future<Output = Result<LabelWriteOutcome, Self::Err>> + Send;++ /// Rename a label of the scope. `name` and any supplied rule are validated.+ /// Omitted rules preserve the existing rule; only smart tags receive updates.+ fn rename_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ name: &str,+ viewer: &MacroUserIdStr<'_>,+ rule: Option<&ChannelLabelRule>,+ ) -> impl Future<Output = Result<LabelWriteOutcome, Self::Err>> + Send;++ /// Delete a label of the scope; its channels become unlabelled.+ ///+ /// Returns `true` when a row was removed.+ fn delete_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;++ /// Put `channel_id` into `label_id` (or into no label when `None`).+ ///+ /// The actor must actively participate in the non-DM channel. A label must+ /// belong to the authorized scope; other scopes must remain unchanged.+ /// Smart tags reject manual assignment with `SmartTagReadOnly`.+ fn set_channel_label(+ &self,+ scope: &ChannelLabelsScope,+ channel_id: Uuid,+ label_id: Option<Uuid>,+ actor: &MacroUserIdStr<'_>,+ ) -> impl Future<Output = Result<SetChannelLabelOutcome, Self::Err>> + Send;++ /// Preview a validated rule using only the viewer's active non-DM memberships.+ /// Match literal substrings case-insensitively; return at most `limit` names+ /// and the full visible count. The same rule determines smart tag membership.+ fn preview_smart_tag(+ &self,+ viewer: &MacroUserIdStr<'_>,+ rule: &ChannelLabelRule,+ limit: u16,+ ) -> impl Future<Output = Result<SmartTagPreview, Self::Err>> + Send;+}++/// Inbound service port: the channel labels API used by drivers.+pub trait ChannelLabelsService: Send + Sync + 'static {+ /// Every label of the caller's authorized scope, in manual order, with the channels+ /// the caller can see.+ fn list_labels(+ &self,+ receipt: &ChannelLabelsReceipt,+ ) -> impl Future<Output = Result<Vec<ChannelLabel>, ChannelLabelsError>> + Send;++ /// Create a label for the caller's authorized scope and move the given channels into it.+ fn create_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ label: NewChannelLabel,+ ) -> impl Future<Output = Result<ChannelLabel, ChannelLabelsError>> + Send;++ /// Rename a label of the caller's authorized scope.+ fn rename_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ label_id: Uuid,+ name: String,+ rule: Option<ChannelLabelRule>,+ ) -> impl Future<Output = Result<ChannelLabel, ChannelLabelsError>> + Send;++ /// Delete a label of the caller's authorized scope; its channels return to the plain list.+ fn delete_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ label_id: Uuid,+ ) -> impl Future<Output = Result<(), ChannelLabelsError>> + Send;++ /// Move a channel into a label of the caller's authorized scope, or out of any label.+ fn set_channel_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ channel_id: Uuid,+ label_id: Option<Uuid>,+ ) -> impl Future<Output = Result<(), ChannelLabelsError>> + Send;++ /// Preview an automatic grouping rule without creating a tag.+ fn preview_smart_tag(+ &self,+ receipt: &ChannelLabelsReceipt,+ rule: ChannelLabelRule,+ ) -> impl Future<Output = Result<SmartTagPreview, ChannelLabelsError>> + Send;+}diff --git a/crates/channel_labels/src/domain/service.rs b/crates/channel_labels/src/domain/service.rsnew file mode 100644index 0000000000..1932b26022--- /dev/null+++ b/crates/channel_labels/src/domain/service.rs@@ -0,0 +1,238 @@+//! Channel labels service implementation.++#[cfg(test)]+mod test;++use uuid::Uuid;++use crate::domain::models::{+ ChannelLabel, ChannelLabelRule, ChannelLabelsError, ChannelLabelsReceipt, LabelWriteOutcome,+ MAX_LABEL_NAME_LEN, MAX_SMART_TAG_PATTERN_LEN, NewChannelLabel, SetChannelLabelOutcome,+ SmartTagPreview,+};+use crate::domain::ports::{ChannelLabelsRepo, ChannelLabelsService};++/// Concrete channel labels service backed by a [`ChannelLabelsRepo`].+#[derive(Debug, Clone)]+pub struct ChannelLabelsServiceImpl<R> {+ repo: R,+}++impl<R> ChannelLabelsServiceImpl<R>+where+ R: ChannelLabelsRepo,+ anyhow::Error: From<R::Err>,+{+ /// Create a service backed by the provided repository.+ pub fn new(repo: R) -> Self {+ Self { repo }+ }++ async fn apply_channel_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ channel_id: Uuid,+ label_id: Option<Uuid>,+ ) -> Result<(), ChannelLabelsError> {+ let outcome = self+ .repo+ .set_channel_label(receipt.scope(), channel_id, label_id, receipt.user_id())+ .await+ .map_err(anyhow::Error::from)?;+ channel_write_result(outcome)+ }+}++fn channel_write_result(outcome: SetChannelLabelOutcome) -> Result<(), ChannelLabelsError> {+ match outcome {+ SetChannelLabelOutcome::Updated => Ok(()),+ SetChannelLabelOutcome::ChannelNotFound => {+ Err(ChannelLabelsError::NotFound("channel not found"))+ }+ SetChannelLabelOutcome::LabelNotFound => {+ Err(ChannelLabelsError::NotFound("label not found"))+ }+ SetChannelLabelOutcome::ChannelNotLabelable => Err(ChannelLabelsError::BadRequest(+ "direct messages cannot be added to a label".to_string(),+ )),+ SetChannelLabelOutcome::SmartTagReadOnly => Err(ChannelLabelsError::BadRequest(+ "smart tag membership is determined by its rule".to_string(),+ )),+ }+}++/// Normalise a requested label name, rejecting blank or oversized input.+fn validate_name(name: &str) -> Result<String, ChannelLabelsError> {+ let trimmed = name.trim();+ if trimmed.is_empty() {+ return Err(ChannelLabelsError::BadRequest(+ "label name must not be empty".to_string(),+ ));+ }+ if trimmed.chars().count() > MAX_LABEL_NAME_LEN {+ return Err(ChannelLabelsError::BadRequest(format!(+ "label name must be at most {MAX_LABEL_NAME_LEN} characters"+ )));+ }+ Ok(trimmed.to_string())+}++fn validate_rule(rule: ChannelLabelRule) -> Result<ChannelLabelRule, ChannelLabelsError> {+ match rule {+ ChannelLabelRule::Name { contains } => {+ let contains = contains.trim();+ if contains.is_empty() || contains.chars().count() > MAX_SMART_TAG_PATTERN_LEN {+ return Err(ChannelLabelsError::BadRequest(format!(+ "name pattern must be between 1 and {MAX_SMART_TAG_PATTERN_LEN} characters"+ )));+ }+ Ok(ChannelLabelRule::Name {+ contains: contains.to_string(),+ })+ }+ }+}++fn written(outcome: LabelWriteOutcome, name: &str) -> Result<ChannelLabel, ChannelLabelsError> {+ match outcome {+ LabelWriteOutcome::Written(label) => Ok(label),+ LabelWriteOutcome::NameTaken => Err(ChannelLabelsError::NameTaken(name.to_string())),+ LabelWriteOutcome::InvalidChannel(outcome) => {+ channel_write_result(outcome)?;+ Err(ChannelLabelsError::BadRequest(+ "invalid channel assignment".to_string(),+ ))+ }+ LabelWriteOutcome::NotFound => Err(ChannelLabelsError::NotFound("label not found")),+ }+}++impl<R> ChannelLabelsService for ChannelLabelsServiceImpl<R>+where+ R: ChannelLabelsRepo,+ anyhow::Error: From<R::Err>,+{+ #[tracing::instrument(err, skip(self))]+ async fn list_labels(+ &self,+ receipt: &ChannelLabelsReceipt,+ ) -> Result<Vec<ChannelLabel>, ChannelLabelsError> {+ Ok(self+ .repo+ .list_labels(receipt.scope(), receipt.user_id())+ .await+ .map_err(anyhow::Error::from)?)+ }++ #[tracing::instrument(err, skip(self))]+ async fn create_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ label: NewChannelLabel,+ ) -> Result<ChannelLabel, ChannelLabelsError> {+ let name = validate_name(&label.name)?;+ let rule = label.rule.map(validate_rule).transpose()?;+ if rule.is_some() && !label.channel_ids.is_empty() {+ return Err(ChannelLabelsError::BadRequest(+ "smart tags match channels automatically and cannot have manual assignments".into(),+ ));+ }+ let mut channel_ids = label.channel_ids;+ channel_ids.sort_unstable();+ channel_ids.dedup();+ written(+ self.repo+ .create_label(+ receipt.scope(),+ &name,+ &channel_ids,+ receipt.user_id(),+ rule.as_ref(),+ )+ .await+ .map_err(anyhow::Error::from)?,+ &name,+ )+ }++ #[tracing::instrument(err, skip(self))]+ async fn rename_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ label_id: Uuid,+ name: String,+ rule: Option<ChannelLabelRule>,+ ) -> Result<ChannelLabel, ChannelLabelsError> {+ let name = validate_name(&name)?;+ let rule = rule.map(validate_rule).transpose()?;+ if rule.is_some() {+ let existing = self+ .repo+ .get_label(receipt.scope(), label_id, receipt.user_id())+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(ChannelLabelsError::NotFound("label not found"))?;+ if existing.rule.is_none() {+ return Err(ChannelLabelsError::BadRequest(+ "only smart tags have editable rules".into(),+ ));+ }+ }+ written(+ self.repo+ .rename_label(+ receipt.scope(),+ label_id,+ &name,+ receipt.user_id(),+ rule.as_ref(),+ )+ .await+ .map_err(anyhow::Error::from)?,+ &name,+ )+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ label_id: Uuid,+ ) -> Result<(), ChannelLabelsError> {+ let removed = self+ .repo+ .delete_label(receipt.scope(), label_id)+ .await+ .map_err(anyhow::Error::from)?;+ if removed {+ Ok(())+ } else {+ Err(ChannelLabelsError::NotFound("label not found"))+ }+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_channel_label(+ &self,+ receipt: &ChannelLabelsReceipt,+ channel_id: Uuid,+ label_id: Option<Uuid>,+ ) -> Result<(), ChannelLabelsError> {+ self.apply_channel_label(receipt, channel_id, label_id)+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn preview_smart_tag(+ &self,+ receipt: &ChannelLabelsReceipt,+ rule: ChannelLabelRule,+ ) -> Result<SmartTagPreview, ChannelLabelsError> {+ let rule = validate_rule(rule)?;+ Ok(self+ .repo+ .preview_smart_tag(receipt.user_id(), &rule, 5)+ .await+ .map_err(anyhow::Error::from)?)+ }+}diff --git a/crates/channel_labels/src/domain/service/test.rs b/crates/channel_labels/src/domain/service/test.rsnew file mode 100644index 0000000000..da5a7cdaba--- /dev/null+++ b/crates/channel_labels/src/domain/service/test.rs@@ -0,0 +1,490 @@+use std::sync::{Arc, Mutex};++use chrono::Utc;+use macro_user_id::user_id::MacroUserIdStr;+use uuid::Uuid;++use super::ChannelLabelsServiceImpl;+use crate::domain::models::{+ ChannelLabel, ChannelLabelRule, ChannelLabelsError, ChannelLabelsReceipt, ChannelLabelsScope,+ LabelWriteOutcome, NewChannelLabel, SetChannelLabelOutcome, SmartTagPreview,+};+use crate::domain::ports::{ChannelLabelsRepo, ChannelLabelsService};++const USER_ID: &str = "macro|[email protected]";++#[derive(Clone, Debug, PartialEq)]+enum RepoCall {+ Create {+ scope: ChannelLabelsScope,+ channel_ids: Vec<Uuid>,+ name: String,+ rule: Option<ChannelLabelRule>,+ },+ Rename {+ label_id: Uuid,+ name: String,+ },+ Delete {+ label_id: Uuid,+ },+ SetChannelLabel {+ channel_id: Uuid,+ label_id: Option<Uuid>,+ },+}++#[derive(Clone, Default)]+struct FakeRepo {+ existing_rule: Option<ChannelLabelRule>,+ create_outcome: Option<LabelWriteOutcome>,+ rename_outcome: Option<LabelWriteOutcome>,+ delete_removed: bool,+ set_outcome: Option<SetChannelLabelOutcome>,+ calls: Arc<Mutex<Vec<RepoCall>>>,+}++impl FakeRepo {+ fn calls(&self) -> Vec<RepoCall> {+ self.calls.lock().expect("calls lock poisoned").clone()+ }++ fn record(&self, call: RepoCall) {+ self.calls.lock().expect("calls lock poisoned").push(call);+ }+}++#[derive(Debug, thiserror::Error)]+#[error("fake repository error")]+struct FakeErr;++fn label(team_id: Uuid, name: &str) -> ChannelLabel {+ ChannelLabel {+ id: Uuid::now_v7(),+ team_id: Some(team_id),+ name: name.to_string(),+ rule: None,+ sort_order: 0.0,+ channel_ids: Vec::new(),+ channel_count: 0,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ }+}++impl ChannelLabelsRepo for FakeRepo {+ type Err = FakeErr;++ async fn list_labels(+ &self,+ scope: &ChannelLabelsScope,+ _viewer: &MacroUserIdStr<'_>,+ ) -> Result<Vec<ChannelLabel>, Self::Err> {+ Ok(vec![label(+ scope.team_id().unwrap_or_default(),+ "Enterprise",+ )])+ }++ async fn get_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ _viewer: &MacroUserIdStr<'_>,+ ) -> Result<Option<ChannelLabel>, Self::Err> {+ let mut found = label(scope.team_id().unwrap_or_default(), "Reloaded");+ found.id = label_id;+ found.rule = self.existing_rule.clone();+ found.channel_count = 2;+ Ok(Some(found))+ }++ async fn create_label(+ &self,+ scope: &ChannelLabelsScope,+ name: &str,+ channel_ids: &[Uuid],+ _viewer: &MacroUserIdStr<'_>,+ rule: Option<&ChannelLabelRule>,+ ) -> Result<LabelWriteOutcome, Self::Err> {+ self.record(RepoCall::Create {+ scope: scope.clone(),+ channel_ids: channel_ids.to_vec(),+ name: name.to_string(),+ rule: rule.cloned(),+ });+ Ok(self.create_outcome.clone().unwrap_or_else(|| {+ LabelWriteOutcome::Written({+ let mut result = label(scope.team_id().unwrap_or_default(), name);+ result.rule = rule.cloned();+ result.team_id = scope.team_id();+ result.channel_ids = channel_ids.to_vec();+ result.channel_count = channel_ids.len() as i64;+ result+ })+ }))+ }++ async fn rename_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ name: &str,+ _viewer: &MacroUserIdStr<'_>,+ rule: Option<&ChannelLabelRule>,+ ) -> Result<LabelWriteOutcome, Self::Err> {+ let _ = rule;+ self.record(RepoCall::Rename {+ label_id,+ name: name.to_string(),+ });+ Ok(self.rename_outcome.clone().unwrap_or_else(|| {+ LabelWriteOutcome::Written(label(scope.team_id().unwrap_or_default(), name))+ }))+ }++ async fn delete_label(+ &self,+ _scope: &ChannelLabelsScope,+ label_id: Uuid,+ ) -> Result<bool, Self::Err> {+ self.record(RepoCall::Delete { label_id });+ Ok(self.delete_removed)+ }++ async fn set_channel_label(+ &self,+ _scope: &ChannelLabelsScope,+ channel_id: Uuid,+ label_id: Option<Uuid>,+ _actor: &MacroUserIdStr<'_>,+ ) -> Result<SetChannelLabelOutcome, Self::Err> {+ self.record(RepoCall::SetChannelLabel {+ channel_id,+ label_id,+ });+ Ok(self.set_outcome.unwrap_or(SetChannelLabelOutcome::Updated))+ }+ async fn preview_smart_tag(+ &self,+ _viewer: &MacroUserIdStr<'_>,+ _rule: &ChannelLabelRule,+ _limit: u16,+ ) -> Result<SmartTagPreview, Self::Err> {+ Ok(SmartTagPreview {+ channels: vec![],+ total_count: 0,+ })+ }+}++fn receipt() -> (Uuid, ChannelLabelsReceipt) {+ let team_id = Uuid::now_v7();+ (+ team_id,+ ChannelLabelsReceipt::dangerously_internal(team_id, USER_ID),+ )+}++#[tokio::test]+async fn create_trims_name_and_moves_channels_in() {+ let repo = FakeRepo::default();+ let service = ChannelLabelsServiceImpl::new(repo.clone());+ let (team_id, receipt) = receipt();+ let channels = vec![Uuid::now_v7(), Uuid::now_v7()];++ let created = service+ .create_label(+ &receipt,+ NewChannelLabel {+ rule: None,+ name: " Enterprise support ".to_string(),+ channel_ids: channels.clone(),+ },+ )+ .await+ .expect("label should be created");++ let calls = repo.calls();+ assert_eq!(+ calls[0],+ RepoCall::Create {+ scope: ChannelLabelsScope::Team(team_id),+ channel_ids: {+ let mut ids = channels.clone();+ ids.sort_unstable();+ ids+ },+ name: "Enterprise support".to_string(),+ rule: None,+ }+ );+ assert_eq!(+ calls.len(),+ 1,+ "creation and assignments are one atomic repository call"+ );+ assert_eq!(created.channel_count, 2);+}++#[tokio::test]+async fn create_rejects_blank_and_oversized_names_without_touching_the_repo() {+ let repo = FakeRepo::default();+ let service = ChannelLabelsServiceImpl::new(repo.clone());+ let (_, receipt) = receipt();++ for name in ["", " ", &"x".repeat(81)] {+ let error = service+ .create_label(+ &receipt,+ NewChannelLabel {+ rule: None,+ name: name.to_string(),+ channel_ids: Vec::new(),+ },+ )+ .await+ .expect_err("invalid name should be rejected");+ assert!(+ matches!(error, ChannelLabelsError::BadRequest(_)),+ "{error:?}"+ );+ }+ assert!(repo.calls().is_empty());+}++#[tokio::test]+async fn create_reports_a_taken_name() {+ let repo = FakeRepo {+ create_outcome: Some(LabelWriteOutcome::NameTaken),+ ..FakeRepo::default()+ };+ let service = ChannelLabelsServiceImpl::new(repo);+ let (_, receipt) = receipt();++ let error = service+ .create_label(+ &receipt,+ NewChannelLabel {+ rule: None,+ name: "SMB".to_string(),+ channel_ids: vec![Uuid::now_v7()],+ },+ )+ .await+ .expect_err("duplicate name should be rejected");+ assert!(matches!(error, ChannelLabelsError::NameTaken(name) if name == "SMB"));+}++#[tokio::test]+async fn rename_validates_and_maps_outcomes() {+ let (_, receipt) = receipt();+ let label_id = Uuid::now_v7();++ let service = ChannelLabelsServiceImpl::new(FakeRepo::default());+ let renamed = service+ .rename_label(&receipt, label_id, " Onboarding ".to_string(), None)+ .await+ .expect("rename should succeed");+ assert_eq!(renamed.name, "Onboarding");++ let service = ChannelLabelsServiceImpl::new(FakeRepo {+ rename_outcome: Some(LabelWriteOutcome::NotFound),+ ..FakeRepo::default()+ });+ let error = service+ .rename_label(&receipt, label_id, "Onboarding".to_string(), None)+ .await+ .expect_err("missing label should be reported");+ assert!(matches!(error, ChannelLabelsError::NotFound(_)));+}++#[tokio::test]+async fn delete_reports_missing_labels() {+ let (_, receipt) = receipt();+ let label_id = Uuid::now_v7();++ let service = ChannelLabelsServiceImpl::new(FakeRepo {+ delete_removed: true,+ ..FakeRepo::default()+ });+ service+ .delete_label(&receipt, label_id)+ .await+ .expect("delete should succeed");++ let service = ChannelLabelsServiceImpl::new(FakeRepo::default());+ let error = service+ .delete_label(&receipt, label_id)+ .await+ .expect_err("missing label should be reported");+ assert!(matches!(error, ChannelLabelsError::NotFound(_)));+}++#[tokio::test]+async fn set_channel_label_maps_repo_outcomes() {+ let (_, receipt) = receipt();+ let channel_id = Uuid::now_v7();++ let cases = [+ (SetChannelLabelOutcome::Updated, None),+ (SetChannelLabelOutcome::ChannelNotFound, Some("not found")),+ (SetChannelLabelOutcome::LabelNotFound, Some("not found")),+ (+ SetChannelLabelOutcome::ChannelNotLabelable,+ Some("bad request"),+ ),+ ];+ for (outcome, expected) in cases {+ let service = ChannelLabelsServiceImpl::new(FakeRepo {+ set_outcome: Some(outcome),+ ..FakeRepo::default()+ });+ let result = service.set_channel_label(&receipt, channel_id, None).await;+ match expected {+ None => assert!(result.is_ok(), "{outcome:?} should succeed"),+ Some("not found") => {+ assert!(+ matches!(result, Err(ChannelLabelsError::NotFound(_))),+ "{outcome:?}"+ )+ }+ Some(_) => {+ assert!(+ matches!(result, Err(ChannelLabelsError::BadRequest(_))),+ "{outcome:?}"+ )+ }+ }+ }+}++#[tokio::test]+async fn users_without_teams_create_private_labels() {+ let actor = MacroUserIdStr::try_from(USER_ID.to_owned()).unwrap();+ let receipt = ChannelLabelsReceipt::from_access(actor.clone(), None).unwrap();+ let repo = FakeRepo::default();+ let service = ChannelLabelsServiceImpl::new(repo.clone());+ let channel = Uuid::now_v7();+ let created = service+ .create_label(+ &receipt,+ NewChannelLabel {+ rule: None,+ name: "Private".into(),+ channel_ids: vec![channel, channel],+ },+ )+ .await+ .unwrap();+ assert_eq!(created.team_id, None);+ assert_eq!(created.channel_ids, vec![channel]);+ assert!(+ matches!(&repo.calls()[0], RepoCall::Create { scope: ChannelLabelsScope::User(id), .. } if id == &actor)+ );+}++#[test]+fn cannot_use_another_users_team_receipt() {+ let actor = MacroUserIdStr::try_from(USER_ID.to_owned()).unwrap();+ let other = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();+ let access =+ entity_access::domain::models::EntityAccessReceipt::dangerously_assert_authenticated_user(+ other,+ &Uuid::now_v7().to_string(),+ model_entity::EntityType::Team,+ );+ assert!(matches!(+ ChannelLabelsReceipt::from_access(actor, Some(access)),+ Err(ChannelLabelsError::Unauthorized)+ ));+}++#[tokio::test]+async fn smart_tags_validate_and_trim_rules_before_persistence() {+ let repo = FakeRepo::default();+ let service = ChannelLabelsServiceImpl::new(repo.clone());+ let (_, receipt) = receipt();+ for pattern in ["", " ", &"x".repeat(201)] {+ let rule = ChannelLabelRule::Name {+ contains: pattern.into(),+ };+ assert!(matches!(+ service.preview_smart_tag(&receipt, rule.clone()).await,+ Err(ChannelLabelsError::BadRequest(_))+ ));+ assert!(matches!(+ service+ .create_label(+ &receipt,+ NewChannelLabel {+ name: "Support".into(),+ rule: Some(rule),+ channel_ids: vec![],+ }+ )+ .await,+ Err(ChannelLabelsError::BadRequest(_))+ ));+ }+ assert!(repo.calls().is_empty());+ let rule = ChannelLabelRule::Name {+ contains: " Support ".into(),+ };+ assert!(matches!(+ service+ .create_label(+ &receipt,+ NewChannelLabel {+ name: "Support".into(),+ rule: Some(rule.clone()),+ channel_ids: vec![Uuid::now_v7()],+ }+ )+ .await,+ Err(ChannelLabelsError::BadRequest(_))+ ));+ let created = service+ .create_label(+ &receipt,+ NewChannelLabel {+ name: "Support".into(),+ rule: Some(rule),+ channel_ids: vec![],+ },+ )+ .await+ .unwrap();+ assert_eq!(+ created.rule,+ Some(ChannelLabelRule::Name {+ contains: "Support".into()+ })+ );+ assert_eq!(repo.calls().len(), 1);+}++#[tokio::test]+async fn rules_can_be_edited_only_on_existing_smart_tags() {+ let (_, receipt) = receipt();+ let rule = ChannelLabelRule::Name {+ contains: "new".into(),+ };+ let manual = ChannelLabelsServiceImpl::new(FakeRepo::default());+ assert!(matches!(+ manual+ .rename_label(&receipt, Uuid::now_v7(), "New".into(), Some(rule.clone()))+ .await,+ Err(ChannelLabelsError::BadRequest(_))+ ));+ let repo = FakeRepo {+ existing_rule: Some(rule.clone()),+ ..FakeRepo::default()+ };+ let smart = ChannelLabelsServiceImpl::new(repo.clone());+ smart+ .rename_label(&receipt, Uuid::now_v7(), "New".into(), Some(rule))+ .await+ .unwrap();+ assert_eq!(repo.calls().len(), 1);+}diff --git a/crates/channel_labels/src/inbound.rs b/crates/channel_labels/src/inbound.rsnew file mode 100644index 0000000000..859030c010--- /dev/null+++ b/crates/channel_labels/src/inbound.rs@@ -0,0 +1,3 @@+//! Driving adapters for channel labels.++pub mod axum_router;diff --git a/crates/channel_labels/src/inbound/axum_router.rs b/crates/channel_labels/src/inbound/axum_router.rsnew file mode 100644index 0000000000..a68aa82486--- /dev/null+++ b/crates/channel_labels/src/inbound/axum_router.rs@@ -0,0 +1,433 @@+//! Axum router for channel label endpoints.+//!+//! Every route authenticates the user and passes their optional verified team+//! receipt inward. The domain resolves team-shared or account-private scope.++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Path, State},+ http::StatusCode,+ response::IntoResponse,+ routing::{delete, get, patch, post, put},+};+use entity_access::{+ domain::{models::MemberTeamRole, ports::EntityAccessService},+ inbound::axum_extractors::OptionalMacroUserTeamExtractorV2,+};+use macro_authorization::{+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOnly,+};+use model_error_response::ErrorResponse;+use serde::Deserialize;+use uuid::Uuid;++use crate::domain::{+ models::{+ ChannelLabel, ChannelLabelRule, ChannelLabelsError, ChannelLabelsList,+ ChannelLabelsReceipt, NewChannelLabel, SmartTagPreview,+ },+ ports::ChannelLabelsService,+};++/// Router state for channel label endpoints.+pub struct ChannelLabelsRouterState<S, Eas, Auth> {+ service: Arc<S>,+ entity_access_service: Arc<Eas>,+ authorization_state: MacroAuthorizationState<Auth>,+}++impl<S, Eas, Auth> Clone for ChannelLabelsRouterState<S, Eas, Auth> {+ fn clone(&self) -> Self {+ Self {+ service: self.service.clone(),+ entity_access_service: self.entity_access_service.clone(),+ authorization_state: self.authorization_state.clone(),+ }+ }+}++impl<S, Eas, Auth> ChannelLabelsRouterState<S, Eas, Auth>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+{+ /// Create router state from shared service references and authorization state.+ pub fn new(+ service: Arc<S>,+ entity_access_service: Arc<Eas>,+ authorization_state: MacroAuthorizationState<Auth>,+ ) -> Self {+ Self {+ service,+ entity_access_service,+ authorization_state,+ }+ }+}++impl<S, Eas, Auth> FromRef<ChannelLabelsRouterState<S, Eas, Auth>> for Arc<Eas> {+ fn from_ref(state: &ChannelLabelsRouterState<S, Eas, Auth>) -> Self {+ state.entity_access_service.clone()+ }+}++impl<S, Eas, Auth> FromRef<ChannelLabelsRouterState<S, Eas, Auth>>+ for MacroAuthorizationState<Auth>+{+ fn from_ref(state: &ChannelLabelsRouterState<S, Eas, Auth>) -> Self {+ state.authorization_state.clone()+ }+}++/// Build the channel labels router.+///+/// Routes:+/// - `GET /` — list the caller's shared or private labels.+/// - `POST /` — create a label, optionally moving channels into it.+/// - `PATCH /{label_id}` — rename a label.+/// - `DELETE /{label_id}` — delete a label.+/// - `PUT /channels/{channel_id}` — move a channel into or out of a label.+pub fn channel_labels_router<S, Eas, Auth, T>(+ state: ChannelLabelsRouterState<S, Eas, Auth>,+) -> Router<T>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+ T: Send + Sync + 'static,+{+ Router::new()+ .route("/", get(list_channel_labels_handler::<S, Eas, Auth>))+ .route("/", post(create_channel_label_handler::<S, Eas, Auth>))+ .route("/preview", post(preview_smart_tag_handler::<S, Eas, Auth>))+ .route(+ "/{label_id}",+ patch(rename_channel_label_handler::<S, Eas, Auth>),+ )+ .route(+ "/{label_id}",+ delete(delete_channel_label_handler::<S, Eas, Auth>),+ )+ .route(+ "/channels/{channel_id}",+ put(set_channel_label_handler::<S, Eas, Auth>),+ )+ .with_state(state)+}++/// Request body for creating a label.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateChannelLabelRequest {+ /// Display name; unique within the scope, case-insensitively.+ pub name: String,+ /// Automatic name-matching rule; omitted for manual labels or a name-only rename.+ #[serde(default)]+ pub rule: Option<ChannelLabelRule>,+ /// Channels to move into the new label.+ #[serde(default)]+ pub channel_ids: Vec<Uuid>,+}++/// Request body for renaming a label.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct RenameChannelLabelRequest {+ /// New display name.+ pub name: String,+ /// Automatic name-matching rule; omitted for manual labels or a name-only rename.+ #[serde(default)]+ pub rule: Option<ChannelLabelRule>,+}++/// Request body for moving a channel between labels.+#[derive(Debug, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct SetChannelLabelRequest {+ /// The label to put the channel in, or `null` to remove it from its label.+ #[serde(default)]+ pub label_id: Option<Uuid>,+}++/// Path params naming a label.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[into_params(parameter_in = Path)]+pub struct ChannelLabelPathParams {+ /// The label id.+ pub label_id: Uuid,+}++/// Path params naming a channel.+#[derive(Debug, Deserialize, utoipa::IntoParams)]+#[into_params(parameter_in = Path)]+pub struct ChannelLabelChannelPathParams {+ /// The channel id.+ pub channel_id: Uuid,+}++/// List the caller's shared or private labels.+#[utoipa::path(+ get,+ tag = "channel_labels",+ operation_id = "list_channel_labels",+ path = "/channel-labels",+ responses(+ (status = 200, body = ChannelLabelsList),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn list_channel_labels_handler<S, Eas, Auth>(+ State(state): State<ChannelLabelsRouterState<S, Eas, Auth>>,+ access: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+ user: MacroAuthorizationExtractor<Auth, UserOnly>,+) -> Result<Json<ChannelLabelsList>, ChannelLabelsError>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let receipt = ChannelLabelsReceipt::from_access(+ user.authorization.macro_user_id,+ access.entity_access_receipt,+ )?;+ let labels = state.service.list_labels(&receipt).await?;+ Ok(Json(ChannelLabelsList {+ team_id: receipt.scope().team_id(),+ labels,+ }))+}++/// Create a label for the caller's authorized scope.+#[utoipa::path(+ post,+ tag = "channel_labels",+ operation_id = "create_channel_label",+ path = "/channel-labels",+ request_body = CreateChannelLabelRequest,+ responses(+ (status = 200, body = ChannelLabel),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 409, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn create_channel_label_handler<S, Eas, Auth>(+ State(state): State<ChannelLabelsRouterState<S, Eas, Auth>>,+ access: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+ user: MacroAuthorizationExtractor<Auth, UserOnly>,+ Json(req): Json<CreateChannelLabelRequest>,+) -> Result<Json<ChannelLabel>, ChannelLabelsError>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let receipt = ChannelLabelsReceipt::from_access(+ user.authorization.macro_user_id,+ access.entity_access_receipt,+ )?;+ let label = state+ .service+ .create_label(+ &receipt,+ NewChannelLabel {+ name: req.name,+ rule: req.rule,+ channel_ids: req.channel_ids,+ },+ )+ .await?;+ Ok(Json(label))+}++/// Rename a label of the caller's authorized scope.+#[utoipa::path(+ patch,+ tag = "channel_labels",+ operation_id = "rename_channel_label",+ path = "/channel-labels/{label_id}",+ params(ChannelLabelPathParams),+ request_body = RenameChannelLabelRequest,+ responses(+ (status = 200, body = ChannelLabel),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 409, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn rename_channel_label_handler<S, Eas, Auth>(+ State(state): State<ChannelLabelsRouterState<S, Eas, Auth>>,+ access: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+ user: MacroAuthorizationExtractor<Auth, UserOnly>,+ Path(params): Path<ChannelLabelPathParams>,+ Json(req): Json<RenameChannelLabelRequest>,+) -> Result<Json<ChannelLabel>, ChannelLabelsError>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let receipt = ChannelLabelsReceipt::from_access(+ user.authorization.macro_user_id,+ access.entity_access_receipt,+ )?;+ let label = state+ .service+ .rename_label(&receipt, params.label_id, req.name, req.rule)+ .await?;+ Ok(Json(label))+}++/// Delete a label of the caller's authorized scope. Its channels return to the plain list.+#[utoipa::path(+ delete,+ tag = "channel_labels",+ operation_id = "delete_channel_label",+ path = "/channel-labels/{label_id}",+ params(ChannelLabelPathParams),+ responses(+ (status = 204),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn delete_channel_label_handler<S, Eas, Auth>(+ State(state): State<ChannelLabelsRouterState<S, Eas, Auth>>,+ access: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+ user: MacroAuthorizationExtractor<Auth, UserOnly>,+ Path(params): Path<ChannelLabelPathParams>,+) -> Result<StatusCode, ChannelLabelsError>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let receipt = ChannelLabelsReceipt::from_access(+ user.authorization.macro_user_id,+ access.entity_access_receipt,+ )?;+ state+ .service+ .delete_label(&receipt, params.label_id)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}++/// Move a channel into a label of the caller's authorized scope, or out of any label.+#[utoipa::path(+ put,+ tag = "channel_labels",+ operation_id = "set_channel_label",+ path = "/channel-labels/channels/{channel_id}",+ params(ChannelLabelChannelPathParams),+ request_body = SetChannelLabelRequest,+ responses(+ (status = 204),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn set_channel_label_handler<S, Eas, Auth>(+ State(state): State<ChannelLabelsRouterState<S, Eas, Auth>>,+ access: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+ user: MacroAuthorizationExtractor<Auth, UserOnly>,+ Path(params): Path<ChannelLabelChannelPathParams>,+ Json(req): Json<SetChannelLabelRequest>,+) -> Result<StatusCode, ChannelLabelsError>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let receipt = ChannelLabelsReceipt::from_access(+ user.authorization.macro_user_id,+ access.entity_access_receipt,+ )?;+ state+ .service+ .set_channel_label(&receipt, params.channel_id, req.label_id)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}++/// Preview visible channels matched by a smart tag, without creating it.+#[utoipa::path(+ post,+ tag = "channel_labels",+ operation_id = "preview_smart_tag",+ path = "/channel-labels/preview",+ request_body = ChannelLabelRule,+ responses(+ (status = 200, body = SmartTagPreview),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn preview_smart_tag_handler<S, Eas, Auth>(+ State(state): State<ChannelLabelsRouterState<S, Eas, Auth>>,+ access: OptionalMacroUserTeamExtractorV2<MemberTeamRole, Eas, Auth>,+ user: MacroAuthorizationExtractor<Auth, UserOnly>,+ Json(rule): Json<ChannelLabelRule>,+) -> Result<Json<SmartTagPreview>, ChannelLabelsError>+where+ S: ChannelLabelsService,+ Eas: EntityAccessService,+ Auth: MacroAuthorizationService,+{+ let receipt = ChannelLabelsReceipt::from_access(+ user.authorization.macro_user_id,+ access.entity_access_receipt,+ )?;+ Ok(Json(state.service.preview_smart_tag(&receipt, rule).await?))+}++impl IntoResponse for ChannelLabelsError {+ fn into_response(self) -> axum::response::Response {+ let status_code = match &self {+ ChannelLabelsError::NotFound(_) => StatusCode::NOT_FOUND,+ ChannelLabelsError::NameTaken(_) => StatusCode::CONFLICT,+ ChannelLabelsError::BadRequest(_) => StatusCode::BAD_REQUEST,+ ChannelLabelsError::Unauthorized => StatusCode::FORBIDDEN,+ ChannelLabelsError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ let message = match &self {+ ChannelLabelsError::Internal(_) => {+ tracing::error!(error=?self, "channel labels internal server error");+ "internal server error".to_string()+ }+ error => error.to_string(),+ };++ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}diff --git a/crates/channel_labels/src/lib.rs b/crates/channel_labels/src/lib.rsnew file mode 100644index 0000000000..1d38fe9244--- /dev/null+++ b/crates/channel_labels/src/lib.rs@@ -0,0 +1,24 @@+#![deny(missing_docs)]+//! Channel labels: shared or private named groups of chat channels shown in the+//! Chat sidebar, following the hexagonal architecture pattern.+//!+//! Every member of a team sees the same labels in the same order and may+//! create, rename, delete, or move channels between them. A member only sees+//! the channels inside a label that they participate in. Empty labels stay+//! visible. Users without a team have labels private to their account.+//! Smart tags match current channel attributes automatically. Their memberships+//! may overlap other tags and manual labels, and only include visible channels.+//!+//! # Architecture+//!+//! - **domain**: models, ports, and the service implementation.+//! - **inbound**: driving adapters (Axum HTTP router).+//! - **outbound**: driven adapters (Postgres repository).++pub mod domain;++#[cfg(feature = "inbound")]+pub mod inbound;++#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/crates/channel_labels/src/outbound.rs b/crates/channel_labels/src/outbound.rsnew file mode 100644index 0000000000..c5ed8371c5--- /dev/null+++ b/crates/channel_labels/src/outbound.rs@@ -0,0 +1,3 @@+//! Driven adapters for channel labels.++pub mod pg_channel_labels_repo;diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rsnew file mode 100644index 0000000000..3ea7be6ee5--- /dev/null+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs@@ -0,0 +1,387 @@+//! PostgreSQL implementation of the [`ChannelLabelsRepo`] port.++#[cfg(test)]+mod test;++use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::{PgPool, Postgres, Transaction};+use uuid::Uuid;++use crate::domain::models::{+ ChannelLabel, ChannelLabelRule, ChannelLabelsScope, LabelWriteOutcome, SetChannelLabelOutcome,+ SmartTagChannelMatch, SmartTagPreview,+};+use crate::domain::ports::ChannelLabelsRepo;++/// Postgres-backed channel labels repository.+#[derive(Debug, Clone)]+pub struct PgChannelLabelsRepo {+ pool: PgPool,+}++impl PgChannelLabelsRepo {+ /// Create a repository backed by the provided pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++/// Errors produced by the Postgres channel labels repository.+#[derive(Debug, thiserror::Error)]+pub enum ChannelLabelsRepoErr {+ /// Underlying database error.+ #[error(transparent)]+ Db(#[from] sqlx::Error),+}++/// Postgres unique-violation SQLSTATE.+const UNIQUE_VIOLATION: &str = "23505";++fn is_unique_violation(error: &sqlx::Error) -> bool {+ error+ .as_database_error()+ .and_then(|db| db.code())+ .is_some_and(|code| code == UNIQUE_VIOLATION)+}++struct LabelRow {+ id: Uuid,+ team_id: Option<Uuid>,+ name: String,+ name_contains: Option<String>,+ sort_order: f64,+ channel_ids: Vec<Uuid>,+ channel_count: i64,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+}++impl From<LabelRow> for ChannelLabel {+ fn from(row: LabelRow) -> Self {+ ChannelLabel {+ id: row.id,+ team_id: row.team_id,+ name: row.name,+ rule: row+ .name_contains+ .map(|contains| ChannelLabelRule::Name { contains }),+ sort_order: row.sort_order,+ channel_ids: row.channel_ids,+ channel_count: row.channel_count,+ created_at: row.created_at,+ updated_at: row.updated_at,+ }+ }+}++impl PgChannelLabelsRepo {+ /// Labels of `scope` (optionally just `label_id`) with the channels+ /// `viewer` participates in, in manual order.+ async fn load_labels(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Option<Uuid>,+ viewer: &MacroUserIdStr<'_>,+ ) -> Result<Vec<ChannelLabel>, ChannelLabelsRepoErr> {+ let scope_key = scope.key();+ // Visible channels are those the viewer currently participates in;+ // channel names of anything else never leave the database. Channels+ // come back A→Z so every member sees the same order inside a label.+ let rows = sqlx::query_as!(+ LabelRow,+ r#"+ WITH labels AS (+ SELECT l.*, ARRAY(+ SELECT c.id+ FROM comms_channels c+ JOIN comms_channel_participants p+ ON p.channel_id = c.id AND p.user_id = $3 AND p.left_at IS NULL+ WHERE (+ l.name_contains IS NULL AND EXISTS (+ SELECT 1 FROM channel_label_channel lc+ WHERE lc.label_id = l.id AND lc.channel_id = c.id+ )+ ) OR (+ l.name_contains IS NOT NULL AND c.channel_type != 'direct_message'+ AND strpos(lower(c.name), lower(l.name_contains)) > 0+ )+ ORDER BY lower(c.name), c.id+ ) AS visible_ids+ FROM channel_label l+ WHERE l.scope_key = $1 AND ($2::uuid IS NULL OR l.id = $2)+ )+ SELECT+ l.id as "id!",+ l.team_id as "team_id?",+ l.name as "name!",+ l.name_contains as "name_contains?",+ l.sort_order as "sort_order!",+ l.created_at as "created_at!",+ l.updated_at as "updated_at!",+ l.visible_ids as "channel_ids!: Vec<Uuid>",+ CASE WHEN l.name_contains IS NULL THEN+ (SELECT COUNT(*) FROM channel_label_channel lc WHERE lc.label_id = l.id)+ ELSE cardinality(l.visible_ids)::bigint END as "channel_count!"+ FROM labels l+ ORDER BY l.sort_order, l.created_at, l.id+ "#,+ scope_key,+ label_id,+ viewer.as_ref(),+ )+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(ChannelLabel::from).collect())+ }+}++impl ChannelLabelsRepo for PgChannelLabelsRepo {+ type Err = ChannelLabelsRepoErr;++ #[tracing::instrument(err, skip(self))]+ async fn list_labels(+ &self,+ scope: &ChannelLabelsScope,+ viewer: &MacroUserIdStr<'_>,+ ) -> Result<Vec<ChannelLabel>, Self::Err> {+ self.load_labels(scope, None, viewer).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ viewer: &MacroUserIdStr<'_>,+ ) -> Result<Option<ChannelLabel>, Self::Err> {+ Ok(self.load_labels(scope, Some(label_id), viewer).await?.pop())+ }++ #[tracing::instrument(err, skip(self))]+ async fn create_label(+ &self,+ scope: &ChannelLabelsScope,+ name: &str,+ channel_ids: &[Uuid],+ viewer: &MacroUserIdStr<'_>,+ rule: Option<&ChannelLabelRule>,+ ) -> Result<LabelWriteOutcome, Self::Err> {+ let scope_key = scope.key();+ let team_id = scope.team_id();+ let user_id = scope.owner_id();+ let name_contains = rule.map(ChannelLabelRule::name_contains);+ let mut tx = self.pool.begin().await?;+ let validity = validate_channels(&mut tx, channel_ids, viewer).await?;+ if validity != SetChannelLabelOutcome::Updated {+ return Ok(LabelWriteOutcome::InvalidChannel(validity));+ }+ let new_id = Uuid::now_v7();+ let id = sqlx::query_scalar!(+ r#"+ INSERT INTO channel_label (id, team_id, user_id, name, name_contains, sort_order)+ VALUES ($1, $2, $3, $4, $6,+ COALESCE((SELECT MAX(sort_order) + 1 FROM channel_label WHERE scope_key = $5), 0))+ ON CONFLICT DO NOTHING+ RETURNING id+ "#,+ new_id,+ team_id,+ user_id,+ name,+ scope_key,+ name_contains,+ )+ .fetch_optional(&mut *tx)+ .await?;+ let Some(id) = id else {+ return Ok(LabelWriteOutcome::NameTaken);+ };+ sqlx::query!(+ r#"INSERT INTO channel_label_channel (scope_key, channel_id, label_id)+ SELECT $1, channel_id, $2 FROM unnest($3::uuid[]) AS channel_id+ ON CONFLICT (scope_key, channel_id) DO UPDATE SET label_id = EXCLUDED.label_id"#,+ scope_key,+ id,+ channel_ids,+ )+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ match self.get_label(scope, id, viewer).await? {+ Some(label) => Ok(LabelWriteOutcome::Written(label)),+ None => Ok(LabelWriteOutcome::NotFound),+ }+ }++ #[tracing::instrument(err, skip(self))]+ async fn rename_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ name: &str,+ viewer: &MacroUserIdStr<'_>,+ rule: Option<&ChannelLabelRule>,+ ) -> Result<LabelWriteOutcome, Self::Err> {+ let scope_key = scope.key();+ let name_contains = rule.map(ChannelLabelRule::name_contains);+ let result = sqlx::query!(+ r#"+ UPDATE channel_label+ SET name = $3, name_contains = COALESCE($4, name_contains), updated_at = now()+ WHERE id = $2 AND scope_key = $1+ "#,+ scope_key,+ label_id,+ name,+ name_contains,+ )+ .execute(&self.pool)+ .await;+ match result {+ Ok(done) if done.rows_affected() == 0 => return Ok(LabelWriteOutcome::NotFound),+ Ok(_) => {}+ Err(error) if is_unique_violation(&error) => {+ return Ok(LabelWriteOutcome::NameTaken);+ }+ Err(error) => return Err(error.into()),+ }+ match self.get_label(scope, label_id, viewer).await? {+ Some(label) => Ok(LabelWriteOutcome::Written(label)),+ None => Ok(LabelWriteOutcome::NotFound),+ }+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete_label(+ &self,+ scope: &ChannelLabelsScope,+ label_id: Uuid,+ ) -> Result<bool, Self::Err> {+ let scope_key = scope.key();+ // Assignments cascade; channels and other scopes are unaffected.+ let done = sqlx::query!(+ r#"DELETE FROM channel_label WHERE id = $2 AND scope_key = $1"#,+ scope_key,+ label_id,+ )+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() > 0)+ }++ #[tracing::instrument(err, skip(self))]+ async fn set_channel_label(+ &self,+ scope: &ChannelLabelsScope,+ channel_id: Uuid,+ label_id: Option<Uuid>,+ actor: &MacroUserIdStr<'_>,+ ) -> Result<SetChannelLabelOutcome, Self::Err> {+ let scope_key = scope.key();+ let mut tx = self.pool.begin().await?;+ if let Some(label_id) = label_id {+ let label = sqlx::query!(+ "SELECT id, name_contains FROM channel_label WHERE id = $2 AND scope_key = $1 FOR KEY SHARE",+ scope_key,+ label_id,+ )+ .fetch_optional(&mut *tx)+ .await?;+ let Some(label) = label else {+ return Ok(SetChannelLabelOutcome::LabelNotFound);+ };+ if label.name_contains.is_some() {+ return Ok(SetChannelLabelOutcome::SmartTagReadOnly);+ }+ }+ let validity = validate_channels(&mut tx, &[channel_id], actor).await?;+ if validity != SetChannelLabelOutcome::Updated {+ return Ok(validity);+ }+ if let Some(label_id) = label_id {+ sqlx::query!(+ r#"INSERT INTO channel_label_channel (scope_key, channel_id, label_id)+ VALUES ($1, $2, $3)+ ON CONFLICT (scope_key, channel_id) DO UPDATE SET label_id = EXCLUDED.label_id"#,+ scope_key,+ channel_id,+ label_id,+ )+ .execute(&mut *tx)+ .await?;+ } else {+ sqlx::query!(+ "DELETE FROM channel_label_channel WHERE scope_key = $1 AND channel_id = $2",+ scope_key,+ channel_id,+ )+ .execute(&mut *tx)+ .await?;+ }+ tx.commit().await?;+ Ok(SetChannelLabelOutcome::Updated)+ }++ #[tracing::instrument(err, skip(self))]+ async fn preview_smart_tag(+ &self,+ viewer: &MacroUserIdStr<'_>,+ rule: &ChannelLabelRule,+ limit: u16,+ ) -> Result<SmartTagPreview, Self::Err> {+ let name_contains = rule.name_contains();+ let rows = sqlx::query!(+ r#"SELECT c.id, c.name as "name!", COUNT(*) OVER () as "total_count!"+ FROM comms_channels c+ JOIN comms_channel_participants p ON p.channel_id = c.id+ WHERE p.user_id = $1 AND p.left_at IS NULL+ AND c.channel_type != 'direct_message'+ AND strpos(lower(c.name), lower($2)) > 0+ ORDER BY lower(c.name), c.id+ LIMIT $3"#,+ viewer.as_ref(),+ name_contains,+ i64::from(limit),+ )+ .fetch_all(&self.pool)+ .await?;+ Ok(SmartTagPreview {+ total_count: rows.first().map_or(0, |row| row.total_count),+ channels: rows+ .into_iter()+ .map(|row| SmartTagChannelMatch {+ id: row.id,+ name: row.name,+ })+ .collect(),+ })+ }+}++/// The port permits grouping only active participants' non-DM channels.+/// Lock the selected channels and memberships until all assignments commit.+async fn validate_channels(+ tx: &mut Transaction<'_, Postgres>,+ channel_ids: &[Uuid],+ actor: &MacroUserIdStr<'_>,+) -> Result<SetChannelLabelOutcome, ChannelLabelsRepoErr> {+ let channels = sqlx::query!(+ r#"SELECT c.id, c.channel_type::text as "channel_type!"+ FROM comms_channels c+ JOIN comms_channel_participants p ON p.channel_id = c.id+ WHERE c.id = ANY($1) AND p.user_id = $2 AND p.left_at IS NULL+ ORDER BY c.id FOR SHARE OF c, p"#,+ channel_ids,+ actor.as_ref(),+ )+ .fetch_all(&mut **tx)+ .await?;+ if channels.len() != channel_ids.len() {+ return Ok(SetChannelLabelOutcome::ChannelNotFound);+ }+ if channels.iter().any(|c| c.channel_type == "direct_message") {+ return Ok(SetChannelLabelOutcome::ChannelNotLabelable);+ }+ Ok(SetChannelLabelOutcome::Updated)+}diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rsnew file mode 100644index 0000000000..b7a5e9e34b--- /dev/null+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test.rs@@ -0,0 +1,705 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::PgPool;+use uuid::Uuid;++use super::PgChannelLabelsRepo;+use crate::domain::models::{ChannelLabelsScope, LabelWriteOutcome, SetChannelLabelOutcome};+use crate::domain::ports::ChannelLabelsRepo;++const USER_A: &str = "macro|[email protected]";+const USER_B: &str = "macro|[email protected]";++fn user(id: &str) -> MacroUserIdStr<'_> {+ MacroUserIdStr::parse_from_str(id).expect("valid user id")+}++async fn insert_user(pool: &PgPool, id: &str) {+ let macro_user_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)"#,+ )+ .bind(macro_user_id)+ .bind(id)+ .execute(pool)+ .await+ .expect("macro_user should insert");+ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#)+ .bind(id)+ .bind(macro_user_id)+ .execute(pool)+ .await+ .expect("user should insert");+}++async fn insert_team(pool: &PgPool, owner: &str) -> Uuid {+ let team_id = Uuid::now_v7();+ sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, 'GTM', $2)"#)+ .bind(team_id)+ .bind(owner)+ .execute(pool)+ .await+ .expect("team should insert");+ sqlx::query(r#"INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'owner')"#)+ .bind(owner)+ .bind(team_id)+ .execute(pool)+ .await+ .expect("team_user should insert");+ team_id+}++async fn insert_channel(+ pool: &PgPool,+ name: Option<&str>,+ channel_type: &str,+ owner: &str,+ participants: &[&str],+) -> Uuid {+ let channel_id = Uuid::now_v7();+ sqlx::query(+ r#"INSERT INTO comms_channels (id, name, channel_type, owner_id)+ VALUES ($1, $2, $3::comms_channel_type, $4)"#,+ )+ .bind(channel_id)+ .bind(name)+ .bind(channel_type)+ .bind(owner)+ .execute(pool)+ .await+ .expect("channel should insert");+ for participant in participants {+ sqlx::query(+ r#"INSERT INTO comms_channel_participants (channel_id, role, user_id)+ VALUES ($1, 'member', $2)"#,+ )+ .bind(channel_id)+ .bind(participant)+ .execute(pool)+ .await+ .expect("participant should insert");+ }+ channel_id+}++fn written(outcome: LabelWriteOutcome) -> crate::domain::models::ChannelLabel {+ match outcome {+ LabelWriteOutcome::Written(label) => label,+ other => panic!("expected a written label, got {other:?}"),+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_appends_in_order_and_rejects_duplicate_names(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let team_id = insert_team(&pool, USER_A).await;+ let repo = PgChannelLabelsRepo::new(pool);++ let first = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_id),+ "Enterprise",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("first label should insert"),+ );+ let second = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_id),+ "SMB",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("second label should insert"),+ );+ assert!(first.sort_order < second.sort_order);+ assert_eq!(first.channel_ids, Vec::<Uuid>::new());+ assert_eq!(first.channel_count, 0);++ let duplicate = repo+ .create_label(+ &ChannelLabelsScope::Team(team_id),+ "enterprise",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("duplicate should not error");+ assert_eq!(duplicate, LabelWriteOutcome::NameTaken);++ let listed = repo+ .list_labels(&ChannelLabelsScope::Team(team_id), &user(USER_A))+ .await+ .expect("labels should list");+ assert_eq!(+ listed.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(),+ ["Enterprise", "SMB"]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn labels_are_team_scoped(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_a = insert_team(&pool, USER_A).await;+ let team_b = insert_team(&pool, USER_B).await;+ let repo = PgChannelLabelsRepo::new(pool);++ let label = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_a),+ "Enterprise",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("label should insert"),+ );++ assert!(+ repo.list_labels(&ChannelLabelsScope::Team(team_b), &user(USER_B))+ .await+ .expect("labels should list")+ .is_empty()+ );+ assert_eq!(+ repo.rename_label(+ &ChannelLabelsScope::Team(team_b),+ label.id,+ "Stolen",+ &user(USER_B),+ None+ )+ .await+ .expect("rename should not error"),+ LabelWriteOutcome::NotFound+ );+ assert!(+ !repo+ .delete_label(&ChannelLabelsScope::Team(team_b), label.id)+ .await+ .expect("delete should not error")+ );+ assert!(+ repo.delete_label(&ChannelLabelsScope::Team(team_a), label.id)+ .await+ .expect("delete should not error")+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn rename_reports_conflicts_and_missing_labels(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let team_id = insert_team(&pool, USER_A).await;+ let repo = PgChannelLabelsRepo::new(pool);++ let enterprise = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_id),+ "Enterprise",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("label should insert"),+ );+ written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_id),+ "SMB",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("label should insert"),+ );++ let renamed = written(+ repo.rename_label(+ &ChannelLabelsScope::Team(team_id),+ enterprise.id,+ "Enterprise support",+ &user(USER_A),+ None,+ )+ .await+ .expect("rename should succeed"),+ );+ assert_eq!(renamed.name, "Enterprise support");+ assert!(renamed.updated_at >= enterprise.updated_at);++ assert_eq!(+ repo.rename_label(+ &ChannelLabelsScope::Team(team_id),+ enterprise.id,+ "smb",+ &user(USER_A),+ None+ )+ .await+ .expect("rename should not error"),+ LabelWriteOutcome::NameTaken+ );+ assert_eq!(+ repo.rename_label(+ &ChannelLabelsScope::Team(team_id),+ Uuid::now_v7(),+ "Anything",+ &user(USER_A),+ None+ )+ .await+ .expect("rename should not error"),+ LabelWriteOutcome::NotFound+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn channels_in_a_label_are_viewer_relative_and_sorted_by_name(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_id = insert_team(&pool, USER_A).await;+ let shared = insert_channel(+ &pool,+ Some("zeta-support"),+ "public",+ USER_A,+ &[USER_A, USER_B],+ )+ .await;+ let only_a = insert_channel(&pool, Some("acme-support"), "public", USER_A, &[USER_A]).await;+ let only_b = insert_channel(&pool, Some("beta-support"), "public", USER_B, &[USER_B]).await;+ let repo = PgChannelLabelsRepo::new(pool);++ let label = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_id),+ "Enterprise",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("label should insert"),+ );+ for channel in [shared, only_a] {+ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_id),+ channel,+ Some(label.id),+ &user(USER_A)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::Updated+ );+ }+ // B labels a channel A cannot see.+ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_id),+ only_b,+ Some(label.id),+ &user(USER_B)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::Updated+ );++ let for_a = repo+ .get_label(&ChannelLabelsScope::Team(team_id), label.id, &user(USER_A))+ .await+ .expect("label should load")+ .expect("label should exist");+ assert_eq!(for_a.channel_ids, vec![only_a, shared], "A→Z by name");+ assert_eq!(+ for_a.channel_count, 3,+ "count includes channels A cannot see"+ );++ let for_b = repo+ .get_label(&ChannelLabelsScope::Team(team_id), label.id, &user(USER_B))+ .await+ .expect("label should load")+ .expect("label should exist");+ assert_eq!(for_b.channel_ids, vec![only_b, shared]);++ // Removing from the label and deleting the label both unlabel channels.+ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_id),+ shared,+ None,+ &user(USER_A)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::Updated+ );+ assert!(+ repo.delete_label(&ChannelLabelsScope::Team(team_id), label.id)+ .await+ .expect("delete should not error")+ );+ let labelled: i64 = sqlx::query_scalar(r#"SELECT COUNT(*) FROM channel_label_channel"#)+ .fetch_one(&repo.pool)+ .await+ .expect("count should load");+ assert_eq!(labelled, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn set_channel_label_rejects_invisible_channels_dms_and_foreign_labels(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_a = insert_team(&pool, USER_A).await;+ let team_b = insert_team(&pool, USER_B).await;+ let only_b = insert_channel(&pool, Some("beta-support"), "public", USER_B, &[USER_B]).await;+ let dm = insert_channel(&pool, None, "direct_message", USER_A, &[USER_A, USER_B]).await;+ let mine = insert_channel(&pool, Some("acme-support"), "public", USER_A, &[USER_A]).await;+ let repo = PgChannelLabelsRepo::new(pool);++ let label_a = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_a),+ "Enterprise",+ &[],+ &user(USER_A),+ None,+ )+ .await+ .expect("label should insert"),+ );+ let label_b = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_b),+ "Theirs",+ &[],+ &user(USER_B),+ None,+ )+ .await+ .expect("label should insert"),+ );++ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_a),+ only_b,+ Some(label_a.id),+ &user(USER_A)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::ChannelNotFound+ );+ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_a),+ dm,+ Some(label_a.id),+ &user(USER_A)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::ChannelNotLabelable+ );+ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_a),+ mine,+ Some(label_b.id),+ &user(USER_A)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::LabelNotFound+ );+ assert_eq!(+ repo.set_channel_label(+ &ChannelLabelsScope::Team(team_a),+ Uuid::now_v7(),+ None,+ &user(USER_A)+ )+ .await+ .expect("set should not error"),+ SetChannelLabelOutcome::ChannelNotFound+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn private_and_team_assignments_do_not_overwrite_each_other(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team = ChannelLabelsScope::Team(insert_team(&pool, USER_A).await);+ let a = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());+ let b = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_B.to_owned()).unwrap());+ let channel = insert_channel(&pool, Some("Shared"), "public", USER_A, &[USER_A, USER_B]).await;+ let repo = PgChannelLabelsRepo::new(pool);+ let team_label = written(+ repo.create_label(&team, "Group", &[channel], &user(USER_A), None)+ .await+ .unwrap(),+ );+ let private_a = written(+ repo.create_label(&a, "Group", &[channel], &user(USER_A), None)+ .await+ .unwrap(),+ );+ let private_b = written(+ repo.create_label(&b, "Group", &[channel], &user(USER_B), None)+ .await+ .unwrap(),+ );+ assert_eq!(private_a.team_id, None);+ assert_eq!(private_b.team_id, None);+ assert_eq!(+ repo.list_labels(&a, &user(USER_A)).await.unwrap(),+ vec![private_a.clone()]+ );+ assert_eq!(+ repo.set_channel_label(&b, channel, Some(private_a.id), &user(USER_B))+ .await+ .unwrap(),+ SetChannelLabelOutcome::LabelNotFound+ );+ assert!(!repo.delete_label(&b, private_a.id).await.unwrap());+ repo.set_channel_label(&a, channel, None, &user(USER_A))+ .await+ .unwrap();+ assert_eq!(+ repo.get_label(&team, team_label.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap()+ .channel_ids,+ vec![channel]+ );+ assert_eq!(+ repo.get_label(&b, private_b.id, &user(USER_B))+ .await+ .unwrap()+ .unwrap()+ .channel_ids,+ vec![channel]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_with_invalid_channel_leaves_no_partial_label_or_moves(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let scope = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());+ let channel = insert_channel(&pool, Some("Mine"), "public", USER_A, &[USER_A]).await;+ let dm = insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;+ let repo = PgChannelLabelsRepo::new(pool);+ let original = written(+ repo.create_label(&scope, "Original", &[channel], &user(USER_A), None)+ .await+ .unwrap(),+ );+ for invalid in [dm, Uuid::now_v7()] {+ let outcome = repo+ .create_label(+ &scope,+ "New group",+ &[channel, invalid],+ &user(USER_A),+ None,+ )+ .await+ .unwrap();+ assert!(matches!(outcome, LabelWriteOutcome::InvalidChannel(_)));+ assert_eq!(+ repo.list_labels(&scope, &user(USER_A)).await.unwrap(),+ vec![original.clone()]+ );+ }+ let created = written(+ repo.create_label(&scope, "New group", &[channel], &user(USER_A), None)+ .await+ .unwrap(),+ );+ assert_eq!(created.channel_ids, vec![channel]);+ assert_eq!(+ repo.get_label(&scope, original.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap()+ .channel_count,+ 0+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn smart_tags_overlap_manual_groups_and_follow_channel_changes(pool: PgPool) {+ use crate::domain::models::ChannelLabelRule;+ insert_user(&pool, USER_A).await;+ let scope = ChannelLabelsScope::User(MacroUserIdStr::try_from(USER_A.to_owned()).unwrap());+ let repo = PgChannelLabelsRepo::new(pool.clone());+ let channel = insert_channel(&pool, Some("Acme SUPPORT"), "public", USER_A, &[USER_A]).await;+ let manual = written(+ repo.create_label(&scope, "Manual", &[channel], &user(USER_A), None)+ .await+ .unwrap(),+ );+ let support_rule = ChannelLabelRule::Name {+ contains: "support".into(),+ };+ let acme_rule = ChannelLabelRule::Name {+ contains: "acme".into(),+ };+ let support = written(+ repo.create_label(&scope, "Support", &[], &user(USER_A), Some(&support_rule))+ .await+ .unwrap(),+ );+ let acme = written(+ repo.create_label(&scope, "Acme", &[], &user(USER_A), Some(&acme_rule))+ .await+ .unwrap(),+ );+ for label in [&manual, &support, &acme] {+ assert_eq!(label.channel_ids, vec![channel]);+ }+ assert_eq!(+ repo.set_channel_label(&scope, channel, Some(support.id), &user(USER_A))+ .await+ .unwrap(),+ SetChannelLabelOutcome::SmartTagReadOnly+ );+ let renamed = written(+ repo.rename_label(+ &scope,+ acme.id,+ "Sales",+ &user(USER_A),+ Some(&ChannelLabelRule::Name {+ contains: "sales".into(),+ }),+ )+ .await+ .unwrap(),+ );+ assert!(renamed.channel_ids.is_empty());+ sqlx::query!(+ "UPDATE comms_channels SET name = 'Acme sales' WHERE id = $1",+ channel+ )+ .execute(&pool)+ .await+ .unwrap();+ assert!(+ repo.get_label(&scope, support.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap()+ .channel_ids+ .is_empty()+ );+ assert_eq!(+ repo.get_label(&scope, acme.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap()+ .channel_ids,+ vec![channel]+ );+ let added = insert_channel(&pool, Some("New support"), "public", USER_A, &[USER_A]).await;+ assert_eq!(+ repo.get_label(&scope, support.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap()+ .channel_ids,+ vec![added]+ );+ repo.delete_label(&scope, support.id).await.unwrap();+ assert_eq!(+ repo.get_label(&scope, manual.id, &user(USER_A))+ .await+ .unwrap()+ .unwrap()+ .channel_ids,+ vec![channel]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn smart_preview_is_bounded_literal_and_respects_membership(pool: PgPool) {+ use crate::domain::models::ChannelLabelRule;+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let team_id = insert_team(&pool, USER_A).await;+ let repo = PgChannelLabelsRepo::new(pool.clone());+ let rule = ChannelLabelRule::Name {+ contains: "support".into(),+ };+ for n in 0..8 {+ insert_channel(+ &pool,+ Some(&format!("SUPPORT {n}")),+ "public",+ USER_A,+ &[USER_A],+ )+ .await;+ }+ insert_channel(&pool, Some("support hidden"), "private", USER_B, &[USER_B]).await;+ insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;+ let left = insert_channel(&pool, Some("support left"), "public", USER_A, &[USER_A]).await;+ sqlx::query!(+ "UPDATE comms_channel_participants SET left_at = now() WHERE channel_id = $1",+ left+ )+ .execute(&pool)+ .await+ .unwrap();+ let preview = repo+ .preview_smart_tag(&user(USER_A), &rule, 5)+ .await+ .unwrap();+ assert_eq!(preview.total_count, 8);+ assert_eq!(preview.channels.len(), 5);+ assert_eq!(preview.channels[0].name, "SUPPORT 0");+ let saved = written(+ repo.create_label(+ &ChannelLabelsScope::Team(team_id),+ "Support",+ &[],+ &user(USER_A),+ Some(&rule),+ )+ .await+ .unwrap(),+ );+ assert_eq!(saved.channel_ids.len(), 8);+ assert_eq!(saved.channel_count, 8);+ let literal = insert_channel(&pool, Some("100%_support"), "public", USER_A, &[USER_A]).await;+ let literal_rule = ChannelLabelRule::Name {+ contains: "%_".into(),+ };+ let literal_preview = repo+ .preview_smart_tag(&user(USER_A), &literal_rule, 5)+ .await+ .unwrap();+ assert_eq!(literal_preview.total_count, 1);+ assert_eq!(literal_preview.channels[0].id, literal);+ let empty = repo+ .preview_smart_tag(&user(USER_B), &literal_rule, 5)+ .await+ .unwrap();+ assert_eq!(empty.total_count, 0);+ assert!(empty.channels.is_empty());+}diff --git a/crates/macro_db_client/migrations/20260918212552_create_channel_labels.sql b/crates/macro_db_client/migrations/20260918212552_create_channel_labels.sqlnew file mode 100644index 0000000000..cc1556a5e3--- /dev/null+++ b/crates/macro_db_client/migrations/20260918212552_create_channel_labels.sql@@ -0,0 +1,23 @@+-- Team-shared channel labels: named groups of chat channels that every member+-- of the team sees and can manage. A channel belongs to at most one label.++CREATE TABLE channel_label+(+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ team_id uuid NOT NULL REFERENCES team (id) ON DELETE CASCADE,+ name text NOT NULL,+ sort_order double precision NOT NULL,+ created_at timestamp with time zone NOT NULL DEFAULT now(),+ updated_at timestamp with time zone NOT NULL DEFAULT now(),+ CONSTRAINT channel_label_name_not_blank CHECK (length(btrim(name)) > 0)+);++-- One label per name within a team, case-insensitively.+CREATE UNIQUE INDEX channel_label_team_name_key ON channel_label (team_id, lower(name));+CREATE INDEX channel_label_team_id_sort_idx ON channel_label (team_id, sort_order);++ALTER TABLE comms_channels+ ADD COLUMN label_id uuid REFERENCES channel_label (id) ON DELETE SET NULL;++CREATE INDEX idx_comms_channels_label_id ON comms_channels (label_id)+ WHERE label_id IS NOT NULL;diff --git a/crates/macro_db_client/migrations/20260921130641_scoped_channel_labels.sql b/crates/macro_db_client/migrations/20260921130641_scoped_channel_labels.sqlnew file mode 100644index 0000000000..93a75e1f1f--- /dev/null+++ b/crates/macro_db_client/migrations/20260921130641_scoped_channel_labels.sql@@ -0,0 +1,27 @@+-- Labels are either team-shared or account-private. Keep the legacy channel+-- column while replacing its global assignment with one assignment per scope.+ALTER TABLE channel_label+ ALTER COLUMN team_id DROP NOT NULL,+ ADD COLUMN user_id text REFERENCES "User" (id) ON DELETE CASCADE,+ ADD CONSTRAINT channel_label_scope_check CHECK ((team_id IS NULL) <> (user_id IS NULL)),+ ADD COLUMN scope_key text GENERATED ALWAYS AS (+ CASE WHEN team_id IS NOT NULL THEN 'team:' || team_id::text ELSE 'user:' || user_id END+ ) STORED,+ ADD CONSTRAINT channel_label_scope_id_key UNIQUE (scope_key, id);++CREATE UNIQUE INDEX channel_label_user_name_key ON channel_label (user_id, lower(name));+CREATE INDEX channel_label_scope_sort_idx ON channel_label (scope_key, sort_order);++CREATE TABLE channel_label_channel (+ scope_key text NOT NULL,+ channel_id uuid NOT NULL REFERENCES comms_channels (id) ON DELETE CASCADE,+ label_id uuid NOT NULL,+ PRIMARY KEY (scope_key, channel_id),+ FOREIGN KEY (scope_key, label_id) REFERENCES channel_label (scope_key, id) ON DELETE CASCADE+);+CREATE INDEX channel_label_channel_label_idx ON channel_label_channel (label_id);++INSERT INTO channel_label_channel (scope_key, channel_id, label_id)+SELECT l.scope_key, c.id, l.id+FROM comms_channels c JOIN channel_label l ON l.id = c.label_id+ON CONFLICT DO NOTHING;diff --git a/crates/macro_db_client/migrations/20260921141239_smart_channel_tags.sql b/crates/macro_db_client/migrations/20260921141239_smart_channel_tags.sqlnew file mode 100644index 0000000000..98bfd1c14a--- /dev/null+++ b/crates/macro_db_client/migrations/20260921141239_smart_channel_tags.sql@@ -0,0 +1,8 @@+-- NULL preserves existing, manually managed labels. Smart memberships are+-- evaluated from current channel attributes; they are never assignment rows.+ALTER TABLE channel_label+ ADD COLUMN name_contains text,+ ADD CONSTRAINT channel_label_name_contains_check CHECK (+ name_contains IS NULL OR+ (char_length(name_contains) BETWEEN 1 AND 200 AND name_contains = btrim(name_contains))+ );diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 89095e3fdd..a5d5dac20b 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -313,10 +313,103 @@ the shared 256px default sidebar width and resize limits. In splits narrower thawith the same full sidebar contents. There is no separate skinny sidebar mode.On desktop, the Chat rail has `All` and `Recent` tabs. All contains an-optional `Favorites` section above the independently paginated `Channels` and-`DMs` sections. It appears when the user has channel favorites and only lists-channels. Channel favorites open in the channel preview. Shift-clicking a-favorite, channel, or DM opens that conversation in a new split instead.+optional `Favorites` section, an optional `Unread` section, and the+independently paginated `Channels` and `DMs` sections. Favorites appears when+the user has channel favorites and only lists channels. Channel favorites open+in the channel preview. Shift-clicking a favorite, channel, or DM opens that+conversation in a new split instead.++`Unread` appears only while at least one channel (not DM) has unread activity.+It is a flat list, newest unread notification first, with each row's timestamp+always visible, and a count pill on its heading. Marking a channel read drops+it from the list. It is capped at a third of the column and scrolls inside.++### Channel labels++Channel labels require the `enable-channel-tags` feature flag. The flag is off+until explicitly enabled, including in development. For a local frontend,+`VITE_ENABLE_CHANNEL_TAGS=true` enables it and `VITE_ENABLE_CHANNEL_TAGS=false`+forces it off; restart the frontend after changing the environment override.++With the flag off, Channels remains a flat list in its selected sort order.+The heading's `+` creates a channel directly. Label headings, creation dialogs,+channel-menu label actions, and label drag targets are absent, and the app makes+no channel-label list or smart-label preview requests. Existing saved labels+remain unchanged and reappear when the flag is enabled.++Verify both states after reloading Chat: with the flag off, inspect the heading+action and a channel's context menu, drag between channel rows, and confirm+there are no `/channel-labels` requests. With the flag enabled, verify the `+`+menu offers `New channel`, `New label`, and `New smart label`; open each label+dialog and cancel to check the controls without changing shared data. The+creation, assignment, and persistence checks below require the label backend+and an account where those changes are safe.++Labels group channels inside the `Channels` section. Team members share the+same labels and can create, rename, delete, or move their channels between them.+Users without a team have labels private to their account. The naming and delete+dialogs explain which scope applies. Collapse/expand state is per user.+Every label remains visible, including empty labels; only channels the viewer+actively participates in are shown inside it. Direct messages cannot be labelled.+Names are unique within the team or account, case-insensitively.++Layout: labels come first in creation order, each showing its visible channels+A→Z, followed by ungrouped channels in the section's selected sort order. The+`Unread` section remains ordered by activity. A label row has an unread count,+a `···` menu (`Rename`, `Mark all as read`, `Delete label`), and a disclosure caret.+Clicking the row or pressing Enter toggles it; `h` / `l` on a label or one of its+channels collapses or expands that label. `[` / `]` jump between section headings.++Creating: use the `Channels` heading's `+` → `New label`, including when the+account has no team. The name field receives focus on opening and reopening.+Enter or `Create label` saves; Escape or Cancel dismisses without saving.+The dialog stays open while saving and shows a failure inline, preserving the+name for a retry. A successful empty label appears immediately and survives+reload. Rename uses the same dialog prefilled. Delete asks for confirmation;+its button says `Delete for everyone` for shared labels and `Delete label` for+private ones. Channels remain accessible after deleting their label.++Moving: right-click a channel for `Add to label` / `Move to label`, including a+`New label…` option, or use `Ungroup from “<label>”`. Drag a channel onto a label+heading or one of its channels to move in. Drag a grouped channel onto a plain+channel, the Channels heading, or empty space below the list to ungroup it.+Dragging one ungrouped channel onto another opens a name dialog; saving creates+the label with both channels atomically. A failed save changes neither channel.+Dropping on the source channel or its current label does nothing; Escape from+the naming dialog leaves both channels unchanged.++For drag verification, start from the channel name and from different horizontal+positions in a row, then move across row boundaries and scroll the list. The+highlight follows the visible target under the pointer, with a whole group+highlighted when moving into it. A drag must not open a preview or reorder the+source. Check moves into collapsed and empty labels, ungrouping, cancellation,+and persistence after reload. Grouping in one Chat rail must not trigger a+second dialog in another rail. If the label service cannot be reached, the+UI reports the failure instead of claiming the group was saved.++Smart labels: use `Channels` → `+` → `New smart label`. Enter a label name and a+`Name contains` pattern. Matching ignores capitalization and treats punctuation+literally; it does not use wildcards or regular expressions. The creation dialog+shows up to five matching channels as you type, followed by `+N more channels+matched` for overflow. Empty patterns cannot be saved; a valid pattern with no+current matches can be saved for future channels. Only channels you participate+in are matched, and direct messages are excluded.++Group headings have no icon in the sidebar; smart label creation uses a filter+icon. Channels appear in every matching smart label and keep any manual label+assignment. A channel in any smart label is excluded+from the ungrouped list, even when its matching labels are collapsed. Membership+follows channel names automatically. Loaded channels update with live name+changes; other matches refresh periodically. Use the heading's `···` →+`Edit smart label` to change the name or pattern and preview the new matches.+Smart labels cannot be drag targets or manually assigned through `Move to label`.+Deleting a smart label preserves channels, other labels, and manual assignments.++Verify overlapping rules, collapsed labels, no matches, overflow, and quickly+changing patterns (an older response must not replace the latest preview).+Open the same matched channel from two labels and verify keyboard focus remains+on the chosen row. Check rule edits and persistence after reload.+If a restored Chat selection is already open in another view, its preview staysclosed but the saved selection is retained. Close the other view, then selectthe conversation again or reopen Chat to restore its preview. Verify that an@@ -350,8 +443,8 @@ keyboard activation still toggles the highlighted section.Arrow Down / `j` at the last loaded conversation holds focus while thatsection loads its next page. Once loading finishes, the next press advancesinto the appended rows. If the section has no next page, navigation proceeds-to the next section. `[` and `]` jump between the visible Favorites, Channels,-and DMs section headers.+to the next section. `[` and `]` jump between the visible Favorites, Unread,+Channels, and DMs section headers.On touch layouts, the `Recent`, `Channels`, and `DMs` pill tabs each retaintheir own loaded pages and load more as their active list approaches the end.diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 237305184d..9a46f324ca 100644--- a/packages/sdk/generated/storage/index.ts+++ b/packages/sdk/generated/storage/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/sdk.gen.ts b/packages/sdk/generated/storage/sdk.gen.tsindex 83e1132229..24f84e21d0 100644--- a/packages/sdk/generated/storage/sdk.gen.ts+++ b/packages/sdk/generated/storage/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, ServerSentEventsResult, TDataShape } from './client';import { client } from './client.gen';-import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, AssignInitiativeTasksData, AssignInitiativeTasksErrors, AssignInitiativeTasksResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UnassignInitiativeTaskData, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';+import type { AddFavoriteData, AddFavoriteErrors, AddFavoriteResponses, AddParticipantsData, AddParticipantsErrors, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerErrors, AddPinHandlerResponses, ApproveHarnessPairingData, ApproveHarnessPairingErrors, ApproveHarnessPairingResponses, AssignInitiativeTasksData, AssignInitiativeTasksErrors, AssignInitiativeTasksResponses, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponses, CallWebhookData, CallWebhookErrors, CallWebhookResponses, CheckActiveCallData, CheckActiveCallErrors, CheckActiveCallResponses, ClaimHarnessPairingData, ClaimHarnessPairingErrors, ClaimHarnessPairingResponses, CopyDocumentData, CopyDocumentErrors, CopyDocumentResponses, CreateAgentData, CreateAgentErrors, CreateAgentResponses, CreateAnchorData, CreateAnchorErrors, CreateAnchorResponses, CreateChannelData, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelErrors, CreateChannelLabelResponses, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotErrors, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentErrors, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentErrors, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyErrors, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactErrors, CreateCrmContactResponses, CreateDocumentData, CreateDocumentErrors, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionErrors, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingErrors, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeErrors, CreateInitiativeResponses, CreateInstructionsHandlerData, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponses, CreateMarkdownHandlerData, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerErrors, CreateProjectHandlerResponses, CreateReminderData, CreateReminderErrors, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerErrors, CreateSkillHandlerResponses, CreateSnippetHandlerData, CreateSnippetHandlerErrors, CreateSnippetHandlerResponses, CreateTaskHandlerData, CreateTaskHandlerErrors, CreateTaskHandlerResponses, CreateUserApiKeyData, CreateUserApiKeyErrors, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerErrors, CreateViewHandlerResponses, CreateWebhookData, CreateWebhookErrors, CreateWebhookResponses, DeleteAnchorData, DeleteAnchorErrors, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordErrors, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelErrors, DeleteChannelLabelResponses, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentErrors, DeleteCrmCommentResponses, DeleteDocumentData, DeleteDocumentErrors, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionErrors, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessErrors, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeErrors, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageErrors, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerErrors, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderErrors, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessErrors, DeleteSelfHarnessResponses, DeleteUserApiKeyData, DeleteUserApiKeyErrors, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookErrors, DeleteWebhookResponses, EditAnchorData, EditAnchorErrors, EditAnchorResponses, EditCallRecordData, EditCallRecordErrors, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptErrors, EditCallTranscriptResponses, EditCommentData, EditCommentErrors, EditCommentResponses, EditCrmCommentData, EditCrmCommentErrors, EditCrmCommentResponses, EditDocumentData, EditDocumentErrors, EditDocumentResponses, EditProjectV2Data, EditProjectV2Errors, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Errors, EditThreadV2Responses, EnsureCollabSurfaceData, EnsureCollabSurfaceErrors, EnsureCollabSurfaceResponses, EntityMessageCreateData, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponses, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExportDocumentData, ExportDocumentErrors, ExportDocumentResponses, GetActiveCallsData, GetActiveCallsErrors, GetActiveCallsResponses, GetActivityData, GetActivityErrors, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesErrors, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewErrors, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponses, GetBatchProjectPreviewData, GetBatchProjectPreviewErrors, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordErrors, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsErrors, GetChannelAttachmentsResponses, GetChannelData, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkErrors, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesErrors, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsErrors, GetChannelParticipantsResponses, GetChannelResponses, GetChannelsData, GetChannelsErrors, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceErrors, GetCollabSurfaceResponses, GetCompanyData, GetCompanyErrors, GetCompanyResponses, GetContactByEmailData, GetContactByEmailErrors, GetContactByEmailResponses, GetContactData, GetContactErrors, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsErrors, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameErrors, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsErrors, GetDocumentCommentsResponses, GetDocumentData, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponses, GetDocumentListHandlerData, GetDocumentListHandlerErrors, GetDocumentListHandlerResponses, GetDocumentLocationV3Data, GetDocumentLocationV3Errors, GetDocumentLocationV3Responses, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Responses, GetDocumentProcessingResultData, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponses, GetDocumentResponses, GetDocumentShortIdData, GetDocumentShortIdErrors, GetDocumentShortIdResponses, GetDocumentTeamShareData, GetDocumentTeamShareErrors, GetDocumentTeamShareResponses, GetDocumentVersionData, GetDocumentVersionErrors, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityErrors, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingErrors, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerErrors, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeErrors, GetInitiativeResponses, GetInstructionsHandlerData, GetInstructionsHandlerErrors, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupErrors, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerErrors, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextErrors, GetMessageWithContextResponses, GetOrCreateCallData, GetOrCreateCallErrors, GetOrCreateCallResponses, GetOrCreateDmData, GetOrCreateDmErrors, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateErrors, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerErrors, GetPinsHandlerResponses, GetProjectContentHandlerData, GetProjectContentHandlerErrors, GetProjectContentHandlerResponses, GetProjectHandlerData, GetProjectHandlerErrors, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Responses, GetProjectsHandlerData, GetProjectsHandlerErrors, GetProjectsHandlerResponses, GetProjectUserAccessLevelData, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderErrors, GetReminderResponses, GetRingStatusData, GetRingStatusErrors, GetRingStatusResponses, GetSelfBotData, GetSelfBotErrors, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessErrors, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesErrors, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponses, GetViewsHandlerData, GetViewsHandlerErrors, GetViewsHandlerResponses, GetWebhookData, GetWebhookErrors, GetWebhookResponses, HandlerData, HandlerErrors, HandlerResponses, HealthHandlerData, HealthHandlerResponses, IngestTranscriptData, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsErrors, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, JobProcessingResultHandlerData, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelErrors, JoinChannelResponses, LeaveChannelData, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallErrors, LeaveOrEndCallResponses, ListAgentsData, ListAgentsErrors, ListAgentsResponses, ListBotChannelsData, ListBotChannelsErrors, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsErrors, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsErrors, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsErrors, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesErrors, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsErrors, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesErrors, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsErrors, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesErrors, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponses, ListRemindersData, ListRemindersErrors, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysErrors, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksErrors, ListWebhooksResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponses, MessageTimelineData, MessageTimelineResponses, PatchChannelData, PatchChannelErrors, PatchChannelResponses, PatchMessageData, PatchMessageErrors, PatchMessageResponses, PatchViewHandlerData, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookErrors, PatchWebhookResponses, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponses, PostActivityData, PostActivityErrors, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookErrors, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesErrors, PostChannelMessagesResponses, PostItemsSoupAstData, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupErrors, PostItemsSoupResponses, PostMessageData, PostMessageErrors, PostMessageResponses, PostReactionData, PostReactionErrors, PostReactionResponses, PostTypingData, PostTypingErrors, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponses, PreviewSmartTagData, PreviewSmartTagErrors, PreviewSmartTagResponses, PutCrmTeamSettingsData, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesErrors, PutCrmTeamStagesResponses, RecentlyDeletedData, RecentlyDeletedErrors, RecentlyDeletedResponses, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsErrors, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerErrors, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelErrors, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesErrors, ReorderFavoritesResponses, ReorderPinsHandlerData, ReorderPinsHandlerErrors, ReorderPinsHandlerResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageErrors, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentErrors, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectErrors, RevertDeleteProjectResponses, SaveDocumentHandlerData, SaveDocumentHandlerErrors, SaveDocumentHandlerResponses, SetChannelLabelData, SetChannelLabelErrors, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureErrors, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenErrors, SetCompanyHiddenResponses, SetContactHiddenData, SetContactHiddenErrors, SetContactHiddenResponses, SetCrmCompanyNameData, SetCrmCompanyNameErrors, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameErrors, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareErrors, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncErrors, SetEmailSyncResponses, SimpleSaveData, SimpleSaveErrors, SimpleSaveResponses, StreamEventsData, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, ToggleShareWithTeamData, ToggleShareWithTeamErrors, ToggleShareWithTeamResponses, UnassignInitiativeTaskData, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponses, UpdateAgentData, UpdateAgentErrors, UpdateAgentResponses, UpdateInitiativeData, UpdateInitiativeErrors, UpdateInitiativeResponses, UpdateReminderData, UpdateReminderErrors, UpdateReminderResponses, UploadExtractFolderHandlerData, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponses, UploadFolderHandlerData, UploadFolderHandlerErrors, UploadFolderHandlerResponses, UpsertHistoryHandlerData, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationResponses, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookErrors, ValidateWebhookResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -413,6 +413,76 @@ export class Sdk extends HeyApiClient {});}+ /**+ * List the caller's shared or private labels.+ */+ public listChannelLabels<ThrowOnError extends boolean = false>(options?: Options<ListChannelLabelsData, ThrowOnError>): RequestResult<ListChannelLabelsResponses, ListChannelLabelsErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<ListChannelLabelsResponses, ListChannelLabelsErrors, ThrowOnError>({ url: '/channel-labels', ...options });+ }++ /**+ * Create a label for the caller's authorized scope.+ */+ public createChannelLabel<ThrowOnError extends boolean = false>(options: Options<CreateChannelLabelData, ThrowOnError>): RequestResult<CreateChannelLabelResponses, CreateChannelLabelErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CreateChannelLabelResponses, CreateChannelLabelErrors, ThrowOnError>({+ url: '/channel-labels',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Move a channel into a label of the caller's authorized scope, or out of any label.+ */+ public setChannelLabel<ThrowOnError extends boolean = false>(options: Options<SetChannelLabelData, ThrowOnError>): RequestResult<SetChannelLabelResponses, SetChannelLabelErrors, ThrowOnError> {+ return (options.client ?? this.client).put<SetChannelLabelResponses, SetChannelLabelErrors, ThrowOnError>({+ url: '/channel-labels/channels/{channel_id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Preview visible channels matched by a smart tag, without creating it.+ */+ public previewSmartTag<ThrowOnError extends boolean = false>(options: Options<PreviewSmartTagData, ThrowOnError>): RequestResult<PreviewSmartTagResponses, PreviewSmartTagErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PreviewSmartTagResponses, PreviewSmartTagErrors, ThrowOnError>({+ url: '/channel-labels/preview',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }++ /**+ * Delete a label of the caller's authorized scope. Its channels return to the plain list.+ */+ public deleteChannelLabel<ThrowOnError extends boolean = false>(options: Options<DeleteChannelLabelData, ThrowOnError>): RequestResult<DeleteChannelLabelResponses, DeleteChannelLabelErrors, ThrowOnError> {+ return (options.client ?? this.client).delete<DeleteChannelLabelResponses, DeleteChannelLabelErrors, ThrowOnError>({ url: '/channel-labels/{label_id}', ...options });+ }++ /**+ * Rename a label of the caller's authorized scope.+ */+ public renameChannelLabel<ThrowOnError extends boolean = false>(options: Options<RenameChannelLabelData, ThrowOnError>): RequestResult<RenameChannelLabelResponses, RenameChannelLabelErrors, ThrowOnError> {+ return (options.client ?? this.client).patch<RenameChannelLabelResponses, RenameChannelLabelErrors, ThrowOnError>({+ url: '/channel-labels/{label_id}',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Handler for `POST /channels`.*/diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex f505943bf3..357f56b27c 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -2324,6 +2324,74 @@ export type ChannelJoinCodeResponse = {join_code: string;};+/**+ * A shared or account-private label grouping chat channels in the sidebar.+ *+ * `channel_ids` is viewer-relative: it lists only the labelled channels the+ * requesting user participates in. `channel_count` counts every channel in+ * the label so clients can warn accurately before a delete.+ */+export type ChannelLabel = {+ /**+ * All assignments for a manual label; visible matches for a smart tag.+ */+ channelCount: number;+ /**+ * Channels in this label that the requesting user participates in.+ */+ channelIds: Array<string>;+ /**+ * When the label was created.+ */+ createdAt: string;+ /**+ * Stable label id.+ */+ id: string;+ /**+ * Display name, unique within the scope (case-insensitive).+ */+ name: string;+ rule?: null | ChannelLabelRule;+ /**+ * Manual ordering value within the scope; lower sorts first.+ */+ sortOrder: number;+ /**+ * Owning team, or `None` for account-private labels.+ */+ teamId?: string | null;+ /**+ * When the label was last renamed or reordered.+ */+ updatedAt: string;+};++/**+ * Case-insensitive, literal substring matching on the channel name.+ */+export type ChannelLabelRule = {+ attribute: 'name';+ /**+ * The substring to find anywhere in the name.+ */+ contains: string;+};++/**+ * The authorized scope's labels in manual order.+ */+export type ChannelLabelsList = {+ /**+ * Every label of the scope, whether or not the caller sees channels in it.+ */+ labels: Array<ChannelLabel>;+ /**+ * Team scope, or `None` for private labels.+ */+ teamId?: string | null;+};+/*** Metadata for [`ChannelTopicEvent::Mentioned`].*/@@ -3196,6 +3264,21 @@ export type CreateBulkDocumentResponseData = {success: boolean;};+/**+ * Request body for creating a label.+ */+export type CreateChannelLabelRequest = {+ /**+ * Channels to move into the new label.+ */+ channelIds?: Array<string>;+ /**+ * Display name; unique within the scope, case-insensitively.+ */+ name: string;+ rule?: null | ChannelLabelRule;+};+/*** Request to create a channel.*/@@ -8031,6 +8114,17 @@ export type RemoveParticipantsRequest = {participants: Array<string>;};+/**+ * Request body for renaming a label.+ */+export type RenameChannelLabelRequest = {+ /**+ * New display name.+ */+ name: string;+ rule?: null | ChannelLabelRule;+};+/*** Request body for reordering favorites.*/@@ -8268,6 +8362,16 @@ export type SessionStoppedMetadata = {turn_in_flight?: null | InFlightTurnSummary;};+/**+ * Request body for moving a channel between labels.+ */+export type SetChannelLabelRequest = {+ /**+ * The label to put the channel in, or `null` to remove it from its label.+ */+ labelId?: string | null;+};+/*** Replace a channel's picture, or remove it by sending a null file id.*/@@ -8439,6 +8543,34 @@ export type SimpleMention = {entity_type: string;};+/**+ * A channel visible to the caller that matches a smart tag rule.+ */+export type SmartTagChannelMatch = {+ /**+ * Channel id.+ */+ id: string;+ /**+ * Channel display name.+ */+ name: string;+};++/**+ * A bounded preview and the total number of visible channels matching a rule.+ */+export type SmartTagPreview = {+ /**+ * First matches, in alphabetical order.+ */+ channels: Array<SmartTagChannelMatch>;+ /**+ * Number of matching channels the caller participates in, including overflow.+ */+ totalCount: number;+};+/*** An agent session as displayed in Soup.*@@ -11467,6 +11599,157 @@ export type IngestTranscriptResponses = {200: unknown;};+export type ListChannelLabelsData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/channel-labels';+};++export type ListChannelLabelsErrors = {+ 401: ErrorResponse;+ 403: ErrorResponse;+ 500: ErrorResponse;+};++export type ListChannelLabelsError = ListChannelLabelsErrors[keyof ListChannelLabelsErrors];++export type ListChannelLabelsResponses = {+ 200: ChannelLabelsList;+};++export type ListChannelLabelsResponse = ListChannelLabelsResponses[keyof ListChannelLabelsResponses];++export type CreateChannelLabelData = {+ body: CreateChannelLabelRequest;+ path?: never;+ query?: never;+ url: '/channel-labels';+};++export type CreateChannelLabelErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 409: ErrorResponse;+ 500: ErrorResponse;+};++export type CreateChannelLabelError = CreateChannelLabelErrors[keyof CreateChannelLabelErrors];++export type CreateChannelLabelResponses = {+ 200: ChannelLabel;+};++export type CreateChannelLabelResponse = CreateChannelLabelResponses[keyof CreateChannelLabelResponses];++export type SetChannelLabelData = {+ body: SetChannelLabelRequest;+ path: {+ /**+ * The channel id.+ */+ channel_id: string;+ };+ query?: never;+ url: '/channel-labels/channels/{channel_id}';+};++export type SetChannelLabelErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type SetChannelLabelError = SetChannelLabelErrors[keyof SetChannelLabelErrors];++export type SetChannelLabelResponses = {+ 204: void;+};++export type SetChannelLabelResponse = SetChannelLabelResponses[keyof SetChannelLabelResponses];++export type PreviewSmartTagData = {+ body: ChannelLabelRule;+ path?: never;+ query?: never;+ url: '/channel-labels/preview';+};++export type PreviewSmartTagErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 403: ErrorResponse;+ 500: ErrorResponse;+};++export type PreviewSmartTagError = PreviewSmartTagErrors[keyof PreviewSmartTagErrors];++export type PreviewSmartTagResponses = {+ 200: SmartTagPreview;+};++export type PreviewSmartTagResponse = PreviewSmartTagResponses[keyof PreviewSmartTagResponses];++export type DeleteChannelLabelData = {+ body?: never;+ path: {+ /**+ * The label id.+ */+ label_id: string;+ };+ query?: never;+ url: '/channel-labels/{label_id}';+};++export type DeleteChannelLabelErrors = {+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 500: ErrorResponse;+};++export type DeleteChannelLabelError = DeleteChannelLabelErrors[keyof DeleteChannelLabelErrors];++export type DeleteChannelLabelResponses = {+ 204: void;+};++export type DeleteChannelLabelResponse = DeleteChannelLabelResponses[keyof DeleteChannelLabelResponses];++export type RenameChannelLabelData = {+ body: RenameChannelLabelRequest;+ path: {+ /**+ * The label id.+ */+ label_id: string;+ };+ query?: never;+ url: '/channel-labels/{label_id}';+};++export type RenameChannelLabelErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 403: ErrorResponse;+ 404: ErrorResponse;+ 409: ErrorResponse;+ 500: ErrorResponse;+};++export type RenameChannelLabelError = RenameChannelLabelErrors[keyof RenameChannelLabelErrors];++export type RenameChannelLabelResponses = {+ 200: ChannelLabel;+};++export type RenameChannelLabelResponse = RenameChannelLabelResponses[keyof RenameChannelLabelResponses];+export type CreateChannelData = {body: CreateChannelRequest;path?: never;diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 6034716949..0f0c4588cf 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -1861,6 +1861,458 @@}}},+ "/channel-labels": {+ "get": {+ "tags": ["channel_labels"],+ "summary": "List the caller's shared or private labels.",+ "operationId": "list_channel_labels",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabelsList"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["channel_labels"],+ "summary": "Create a label for the caller's authorized scope.",+ "operationId": "create_channel_label",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateChannelLabelRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabel"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channel-labels/channels/{channel_id}": {+ "put": {+ "tags": ["channel_labels"],+ "summary": "Move a channel into a label of the caller's authorized scope, or out of any label.",+ "operationId": "set_channel_label",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "The channel id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetChannelLabelRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "204": {+ "description": ""+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channel-labels/preview": {+ "post": {+ "tags": ["channel_labels"],+ "summary": "Preview visible channels matched by a smart tag, without creating it.",+ "operationId": "preview_smart_tag",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabelRule"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SmartTagPreview"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/channel-labels/{label_id}": {+ "delete": {+ "tags": ["channel_labels"],+ "summary": "Delete a label of the caller's authorized scope. Its channels return to the plain list.",+ "operationId": "delete_channel_label",+ "parameters": [+ {+ "name": "label_id",+ "in": "path",+ "description": "The label id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ },+ "patch": {+ "tags": ["channel_labels"],+ "summary": "Rename a label of the caller's authorized scope.",+ "operationId": "rename_channel_label",+ "parameters": [+ {+ "name": "label_id",+ "in": "path",+ "description": "The label id.",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RenameChannelLabelRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelLabel"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "409": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/channels": {"post": {"tags": ["channels"],@@ -17432,6 +17884,113 @@}}},+ "ChannelLabel": {+ "type": "object",+ "description": "A shared or account-private label grouping chat channels in the sidebar.\n\n`channel_ids` is viewer-relative: it lists only the labelled channels the\nrequesting user participates in. `channel_count` counts every channel in\nthe label so clients can warn accurately before a delete.",+ "required": [+ "id",+ "name",+ "sortOrder",+ "channelIds",+ "channelCount",+ "createdAt",+ "updatedAt"+ ],+ "properties": {+ "channelCount": {+ "type": "integer",+ "format": "int64",+ "description": "All assignments for a manual label; visible matches for a smart tag."+ },+ "channelIds": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Channels in this label that the requesting user participates in."+ },+ "createdAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the label was created."+ },+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Stable label id."+ },+ "name": {+ "type": "string",+ "description": "Display name, unique within the scope (case-insensitive)."+ },+ "rule": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelLabelRule",+ "description": "Automatic membership rule, or `None` for a manually managed label."+ }+ ]+ },+ "sortOrder": {+ "type": "number",+ "format": "double",+ "description": "Manual ordering value within the scope; lower sorts first."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Owning team, or `None` for account-private labels."+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the label was last renamed or reordered."+ }+ }+ },+ "ChannelLabelRule": {+ "oneOf": [+ {+ "type": "object",+ "description": "Case-insensitive, literal substring matching on the channel name.",+ "required": ["contains", "attribute"],+ "properties": {+ "attribute": {+ "type": "string",+ "enum": ["name"]+ },+ "contains": {+ "type": "string",+ "description": "The substring to find anywhere in the name."+ }+ }+ }+ ],+ "description": "An attribute rule that automatically groups matching channels."+ },+ "ChannelLabelsList": {+ "type": "object",+ "description": "The authorized scope's labels in manual order.",+ "required": ["labels"],+ "properties": {+ "labels": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ChannelLabel"+ },+ "description": "Every label of the scope, whether or not the caller sees channels in it."+ },+ "teamId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Team scope, or `None` for private labels."+ }+ }+ },"ChannelMentionedMetadata": {"type": "object","description": "Metadata for [`ChannelTopicEvent::Mentioned`].",@@ -18720,6 +19279,36 @@}}},+ "CreateChannelLabelRequest": {+ "type": "object",+ "description": "Request body for creating a label.",+ "required": ["name"],+ "properties": {+ "channelIds": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "Channels to move into the new label."+ },+ "name": {+ "type": "string",+ "description": "Display name; unique within the scope, case-insensitively."+ },+ "rule": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelLabelRule",+ "description": "Automatic name-matching rule; omitted for manual labels or a name-only rename."+ }+ ]+ }+ }+ },"CreateChannelRequest": {"type": "object","description": "Request to create a channel.",@@ -26862,6 +27451,28 @@}}},+ "RenameChannelLabelRequest": {+ "type": "object",+ "description": "Request body for renaming a label.",+ "required": ["name"],+ "properties": {+ "name": {+ "type": "string",+ "description": "New display name."+ },+ "rule": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChannelLabelRule",+ "description": "Automatic name-matching rule; omitted for manual labels or a name-only rename."+ }+ ]+ }+ }+ },"ReorderFavoritesRequest": {"type": "object","description": "Request body for reordering favorites.",@@ -27177,6 +27788,17 @@}}},+ "SetChannelLabelRequest": {+ "type": "object",+ "description": "Request body for moving a channel between labels.",+ "properties": {+ "labelId": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "The label to put the channel in, or `null` to remove it from its label."+ }+ }+ },"SetChannelPictureRequest": {"type": "object","description": "Replace a channel's picture, or remove it by sending a null file id.",@@ -27497,6 +28119,41 @@}}},+ "SmartTagChannelMatch": {+ "type": "object",+ "description": "A channel visible to the caller that matches a smart tag rule.",+ "required": ["id", "name"],+ "properties": {+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel id."+ },+ "name": {+ "type": "string",+ "description": "Channel display name."+ }+ }+ },+ "SmartTagPreview": {+ "type": "object",+ "description": "A bounded preview and the total number of visible channels matching a rule.",+ "required": ["channels", "totalCount"],+ "properties": {+ "channels": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/SmartTagChannelMatch"+ },+ "description": "First matches, in alphabetical order."+ },+ "totalCount": {+ "type": "integer",+ "format": "int64",+ "description": "Number of matching channels the caller participates in, including overflow."+ }+ }+ },"SoupAgentSession_SoupPropertiesField": {"allOf": [{diff --git a/packages/sdk/src/entities/channels/labels.ts b/packages/sdk/src/entities/channels/labels.tsnew file mode 100644index 0000000000..5827ea8eb1--- /dev/null+++ b/packages/sdk/src/entities/channels/labels.ts@@ -0,0 +1,105 @@+import type {+ ChannelLabel,+ ChannelLabelRule,+ SmartTagPreview,+} from '../../../generated/storage/types.gen';+import { unwrap } from '../../utils';+import type { MacroClient } from '../../utils/client';+import type { Channel } from './channel';++export type { ChannelLabel, ChannelLabelRule, SmartTagPreview };++/**+ * Shared or private channel labels: named groups of channels shown in the Chat+ * sidebar. Every member of the team sees the same labels in the same order,+ * and any member may create, rename, delete, or move channels between them;+ * each change applies to the whole team. Users without a team have private+ * labels belonging to their account.+ *+ * A label's `channelIds` lists only the channels the authenticated user is a+ * member of. Manual labels count all assignments; smart tags count visible+ * matches. A channel can be in one manual label and any number of matching+ * smart tags per team or account. Direct messages cannot be grouped.+ */+export class ChannelLabelsNamespace {+ constructor(private readonly client: MacroClient) {}++ /** Every label in the authenticated user's shared or private scope. */+ async list(): Promise<ChannelLabel[]> {+ const { labels } = unwrap(await this.client.storage.listChannelLabels());+ return labels;+ }++ /**+ * Create a label and atomically move `channels` into it. Names are unique+ * within the team or account, case-insensitively.+ */+ async create(name: string, channels: Channel[] = []): Promise<ChannelLabel> {+ return unwrap(+ await this.client.storage.createChannelLabel({+ body: { name, channelIds: channels.map((channel) => channel.id) },+ })+ );+ }++ /** Create a smart tag whose membership follows an attribute rule automatically. */+ async createSmartTag(+ name: string,+ rule: ChannelLabelRule+ ): Promise<ChannelLabel> {+ return unwrap(+ await this.client.storage.createChannelLabel({ body: { name, rule } })+ );+ }++ /** Preview the first matches and total visible count without creating a tag. */+ async previewSmartTag(rule: ChannelLabelRule): Promise<SmartTagPreview> {+ return unwrap(await this.client.storage.previewSmartTag({ body: rule }));+ }++ /** Update the name and matching rule of an existing smart tag. */+ async updateSmartTag(+ label: ChannelLabel,+ name: string,+ rule: ChannelLabelRule+ ): Promise<ChannelLabel> {+ return unwrap(+ await this.client.storage.renameChannelLabel({+ path: { label_id: label.id },+ body: { name, rule },+ })+ );+ }++ /** Rename a label for the whole team. */+ async rename(label: ChannelLabel, name: string): Promise<ChannelLabel> {+ return unwrap(+ await this.client.storage.renameChannelLabel({+ path: { label_id: label.id },+ body: { name },+ })+ );+ }++ /** Delete a label for the whole team; its channels return to the plain list. */+ async delete(label: ChannelLabel): Promise<void> {+ unwrap(+ await this.client.storage.deleteChannelLabel({+ path: { label_id: label.id },+ })+ );+ }++ /** Move a channel into `label`, or out of any label when `label` is `undefined`. */+ async setLabel(+ channel: Channel,+ label: ChannelLabel | undefined+ ): Promise<void> {+ unwrap(+ await this.client.storage.setChannelLabel({+ path: { channel_id: channel.id },+ body: { labelId: label?.id ?? null },+ })+ );+ }+}diff --git a/packages/sdk/src/entities/channels/namespace.ts b/packages/sdk/src/entities/channels/namespace.tsindex ec743fe4e4..3db8e36d40 100644--- a/packages/sdk/src/entities/channels/namespace.ts+++ b/packages/sdk/src/entities/channels/namespace.ts@@ -5,9 +5,15 @@ import type { SearchOpts } from '../search';import type { Team } from '../teams/team';import type { User } from '../users/user';import { Channel } from './channel';+import { ChannelLabelsNamespace } from './labels';export class ChannelNamespace {- constructor(private readonly client: MacroClient) {}+ /** Team-shared labels that group channels in the Chat sidebar. */+ readonly labels: ChannelLabelsNamespace;++ constructor(private readonly client: MacroClient) {+ this.labels = new ChannelLabelsNamespace(client);+ }byId(id: string): Channel {return Channel.byId(this.client, id);diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.tomlindex 2f8c9dfd82..4b73ed9708 100644--- a/services/document_storage_service/Cargo.toml+++ b/services/document_storage_service/Cargo.toml@@ -85,6 +85,10 @@ connection = { path = "../../crates/connection", default-features = false, featuconnection_gateway_client = { path = "../../crates/connection_gateway_client" }contacts = { path = "../../crates/contacts" }cowlike = { path = "../../crates/cowlike" }+channel_labels = { path = "../../crates/channel_labels", features = [+ "inbound",+ "postgres",+] }crm = { path = "../../crates/crm" }document_sub_type = { path = "../../crates/document_sub_type" }documents_hex = { path = "../../crates/documents", package = "documents" }diff --git a/services/document_storage_service/src/api.rs b/services/document_storage_service/src/api.rsindex c1cc5b10cf..33cb3f480d 100644--- a/services/document_storage_service/src/api.rs+++ b/services/document_storage_service/src/api.rs@@ -232,6 +232,12 @@ fn api_router(state: ApiContext) -> Router {"/favorites",favorites::inbound::axum_router::favorites_router(state.favorites_state.clone()),)+ .nest(+ "/channel-labels",+ channel_labels::inbound::axum_router::channel_labels_router(+ state.channel_labels_state.clone(),+ ),+ ).nest("/user-api-keys",user_api_key::inbound::axum_router::user_api_key_router(diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex c32d518c1b..466b27eee6 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -21,6 +21,10 @@ use call::{inbound::axum_router::{CallRouterState, InternalCallRouterState, WebhookRouterState},outbound::{livekit_rtc_client::LivekitRtcClient, pg_call_repo::PgCallRepo},};+use channel_labels::{+ domain::service::ChannelLabelsServiceImpl, inbound::axum_router::ChannelLabelsRouterState,+ outbound::pg_channel_labels_repo::PgChannelLabelsRepo,+};use channels::{domain::{list_service::ChannelListServiceImpl,@@ -468,6 +472,13 @@ pub(crate) type FavoritesServiceType = FavoritesServiceImpl<PgFavoritesRepo>;pub(crate) type FavoritesMutationServiceType =FavoritesMutationServiceImpl<FavoritesServiceType, EntityAccessService>;+/// Type alias for the channel labels service.+pub(crate) type ChannelLabelsServiceType = ChannelLabelsServiceImpl<PgChannelLabelsRepo>;++/// Type alias for the channel labels router state.+pub(crate) type DssChannelLabelsState =+ ChannelLabelsRouterState<ChannelLabelsServiceType, EntityAccessService, AuthorizationService>;+/// Type alias for the favorites router state.pub(crate) type DssFavoritesState =FavoritesRouterState<FavoritesServiceType, EntityAccessService, AuthorizationService>;@@ -571,6 +582,7 @@ pub(crate) struct ApiContext {pub favorites_state: DssFavoritesState,pub favorites_service: Arc<FavoritesServiceType>,pub favorites_mutation_service: Arc<FavoritesMutationServiceType>,+ pub channel_labels_state: DssChannelLabelsState,pub user_api_key_state: DssUserApiKeyState,pub reminders_state: DssRemindersState,pub initiative_state: DssInitiativeState,diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rsindex 644ca17bef..1246fb79b9 100644--- a/services/document_storage_service/src/api/swagger.rs+++ b/services/document_storage_service/src/api/swagger.rs@@ -57,6 +57,12 @@ use crate::{},},};+use channel_labels::domain::models::{+ ChannelLabel, ChannelLabelRule, ChannelLabelsList, SmartTagChannelMatch, SmartTagPreview,+};+use channel_labels::inbound::axum_router::{+ CreateChannelLabelRequest, RenameChannelLabelRequest, SetChannelLabelRequest,+};use channels::inbound::axum_router::{ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference,ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage,@@ -348,6 +354,13 @@ use utoipa::OpenApi;favorites::inbound::axum_router::add_favorite_handler,favorites::inbound::axum_router::remove_favorite_by_entity_handler,favorites::inbound::axum_router::reorder_favorites_handler,+ // channel labels+ channel_labels::inbound::axum_router::list_channel_labels_handler,+ channel_labels::inbound::axum_router::preview_smart_tag_handler,+ channel_labels::inbound::axum_router::create_channel_label_handler,+ channel_labels::inbound::axum_router::rename_channel_label_handler,+ channel_labels::inbound::axum_router::delete_channel_label_handler,+ channel_labels::inbound::axum_router::set_channel_label_handler,// user api keysuser_api_key::inbound::axum_router::create_user_api_key_handler,@@ -520,6 +533,14 @@ use utoipa::OpenApi;AddFavoriteRequest,FavoriteEntityRef,ReorderFavoritesRequest,+ ChannelLabel,+ ChannelLabelsList,+ ChannelLabelRule,+ SmartTagChannelMatch,+ SmartTagPreview,+ CreateChannelLabelRequest,+ RenameChannelLabelRequest,+ SetChannelLabelRequest,Reminder,RemindersList,ReminderSchedule,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex c4fa292a9d..bdf45e044f 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -36,6 +36,10 @@ use call::{s3_recording_storage::{RecordingCloudFrontConfig, S3RecordingStorage},},};+use channel_labels::{+ domain::service::ChannelLabelsServiceImpl, inbound::axum_router::ChannelLabelsRouterState,+ outbound::pg_channel_labels_repo::PgChannelLabelsRepo,+};use channels::{domain::{list_service::ChannelListServiceImpl,@@ -1495,6 +1499,13 @@ async fn run() -> anyhow::Result<()> {),favorites_service,favorites_mutation_service,+ channel_labels_state: ChannelLabelsRouterState::new(+ Arc::new(ChannelLabelsServiceImpl::new(PgChannelLabelsRepo::new(+ db.clone(),+ ))),+ entity_access_service.clone(),+ authorization_state.clone(),+ ),user_api_key_state: UserApiKeyRouterState::new(user_api_key_service,authorization_state.clone(),