Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(channels): add customizable sidebar sections (#9274)

dev-rbcb26666a2503
diff --git a/.sqlx/query-766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b.json b/.sqlx/query-1afcc912c33b24f25d2f5da5b5ea3d8645f530094ceaa7ae8a35c8361c9e564d.json
similarity index 67%
rename from .sqlx/query-766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b.json
rename to .sqlx/query-1afcc912c33b24f25d2f5da5b5ea3d8645f530094ceaa7ae8a35c8361c9e564d.json
index a469d14ab5..f839e5a6d9 100644
--- a/.sqlx/query-766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b.json
+++ b/.sqlx/query-1afcc912c33b24f25d2f5da5b5ea3d8645f530094ceaa7ae8a35c8361c9e564d.json
@@ -1,6 +1,6 @@
{
"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 = 'team'\n AND ($4::uuid IS NULL OR c.team_id = $4)\n AND strpos(lower(c.name), lower($2)) > 0\n ORDER BY lower(c.name), c.id\n LIMIT $3",
+ "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 (($4::uuid IS NULL AND c.channel_type IN ('team', 'public', 'private'))\n OR (c.channel_type = 'team' AND c.team_id = $4))\n AND strpos(lower(c.name), lower($2)) > 0\n ORDER BY lower(c.name), c.id\n LIMIT $3",
"describe": {
"columns": [
{
@@ -33,5 +33,5 @@
null
]
},
- "hash": "766c7c48742a815496b6d3faa7ed41cfcb8fe63995e99108f08584f60774961b"
+ "hash": "1afcc912c33b24f25d2f5da5b5ea3d8645f530094ceaa7ae8a35c8361c9e564d"
}
diff --git a/.sqlx/query-21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0.json b/.sqlx/query-21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0.json
deleted file mode 100644
index 48c8023eab..0000000000
--- a/.sqlx/query-21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0.json
+++ /dev/null
@@ -1,72 +0,0 @@
-{
- "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 c.channel_type = 'team'\n AND (l.team_id IS NULL OR c.team_id = l.team_id)\n AND ((\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\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\n JOIN comms_channels c ON c.id = lc.channel_id\n WHERE lc.label_id = l.id AND c.channel_type = 'team'\n AND (l.team_id IS NULL OR c.team_id = l.team_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": "21a5251aafa52d9ef1be79a2d66f4cabbc5609b7e5d136489c1a8df3252277b0"
-}
diff --git a/.sqlx/query-240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad.json b/.sqlx/query-240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad.json
deleted file mode 100644
index c5fcc1e2c6..0000000000
--- a/.sqlx/query-240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "SELECT c.id, c.team_id\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": "team_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "UuidArray",
- "Text"
- ]
- },
- "nullable": [
- false,
- true
- ]
- },
- "hash": "240725f9f867a15d13b90008e42f8e41f01504c8bbeee1bd1c1b527d2457f8ad"
-}
diff --git a/.sqlx/query-792c93e5824cd148379afa932e0df053b1c3bd5c1611c097b4cb6ab441b3455b.json b/.sqlx/query-792c93e5824cd148379afa932e0df053b1c3bd5c1611c097b4cb6ab441b3455b.json
new file mode 100644
index 0000000000..01b318c26b
--- /dev/null
+++ b/.sqlx/query-792c93e5824cd148379afa932e0df053b1c3bd5c1611c097b4cb6ab441b3455b.json
@@ -0,0 +1,35 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT c.id, c.team_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": "team_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "channel_type!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ null
+ ]
+ },
+ "hash": "792c93e5824cd148379afa932e0df053b1c3bd5c1611c097b4cb6ab441b3455b"
+}
diff --git a/.sqlx/query-abcb8e7c4e49ec5486a640e3bceae44e4efe0e1368b909af09f5ac7713aa660c.json b/.sqlx/query-abcb8e7c4e49ec5486a640e3bceae44e4efe0e1368b909af09f5ac7713aa660c.json
new file mode 100644
index 0000000000..60de94e6a4
--- /dev/null
+++ b/.sqlx/query-abcb8e7c4e49ec5486a640e3bceae44e4efe0e1368b909af09f5ac7713aa660c.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 ((l.team_id IS NULL AND c.channel_type IN ('team', 'public', 'private'))\n OR (l.team_id IS NOT NULL AND c.channel_type = 'team' AND c.team_id = l.team_id))\n AND ((\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\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\n JOIN comms_channels c ON c.id = lc.channel_id\n WHERE lc.label_id = l.id AND ((l.team_id IS NULL AND c.channel_type IN ('team', 'public', 'private'))\n OR (l.team_id IS NOT NULL AND c.channel_type = 'team' AND c.team_id = l.team_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": "abcb8e7c4e49ec5486a640e3bceae44e4efe0e1368b909af09f5ac7713aa660c"
+}
diff --git a/CODING.md b/CODING.md
index ccf9059448..c05c86db41 100644
--- a/CODING.md
+++ b/CODING.md
@@ -25,7 +25,9 @@ files; the [style guide](docs/development/style-guide.md) indexes them.
- Use native APIs and existing libraries. No polyfills, no homemade crypto.
- Keep types and traits small.
- Name things for what they are or do; avoid jargon, slang, and vague labels such as `candidates`.
-- Use explicit branches instead of deeply nested ternaries.
+- Use ternaries sparingly for short, simple expressions; use explicit branches for complex or nested decisions.
+- Break up long statements and compound conditions instead of compressing them onto one line.
+- Separate functions, variable groups, conditionals, and distinct logic blocks with blank lines.
- Keep compatibility only at deployed boundaries; reject obsolete unreleased formats instead of adding upgrade paths.
## Correctness
diff --git a/Cargo.lock b/Cargo.lock
index e63ba6427a..490b329df9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4637,7 +4637,7 @@ dependencies = [
"webhook",
"windows-sys 0.61.2",
"workspace-hack",
- "zip 9.0.5",
+ "zip",
]
[[package]]
@@ -5194,7 +5194,7 @@ dependencies = [
"utoipa",
"utoipa-swagger-ui",
"workspace-hack",
- "zip 9.0.5",
+ "zip",
]
[[package]]
@@ -6680,7 +6680,7 @@ dependencies = [
"wiremock",
"work_feed",
"workspace-hack",
- "zip 9.0.5",
+ "zip",
]
[[package]]
@@ -6932,7 +6932,7 @@ dependencies = [
"tracing",
"urlencoding",
"workspace-hack",
- "zip 9.0.5",
+ "zip",
]
[[package]]
@@ -13598,7 +13598,7 @@ dependencies = [
"tracing-subscriber",
"url",
"workspace-hack",
- "zip 9.0.5",
+ "zip",
]
[[package]]
@@ -21193,7 +21193,7 @@ dependencies = [
"tracing",
"walkdir",
"workspace-hack",
- "zip 9.0.5",
+ "zip",
]
[[package]]
@@ -21407,7 +21407,7 @@ dependencies = [
"url",
"utoipa",
"utoipa-swagger-ui-vendored",
- "zip 3.0.0",
+ "zip",
]
[[package]]
@@ -23041,6 +23041,7 @@ dependencies = [
"xxhash-rust",
"zerocopy",
"zeroize",
+ "zip",
]
[[package]]
@@ -23397,20 +23398,6 @@ dependencies = [
"syn 2.0.117",
]
-[[package]]
-name = "zip"
-version = "3.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12598812502ed0105f607f941c386f43d441e00148fce9dec3ca5ffb0bde9308"
-dependencies = [
- "arbitrary",
- "crc32fast",
- "flate2",
- "indexmap 2.14.0",
- "memchr",
- "zopfli",
-]
-
[[package]]
name = "zip"
version = "9.0.5"
diff --git a/apps/marketing/README.md b/apps/marketing/README.md
index 0c6a33c16d..e22405f2da 100644
--- a/apps/marketing/README.md
+++ b/apps/marketing/README.md
@@ -996,13 +996,15 @@ and closing sources at desktop and phone widths, without remounting the original
conversation or document. Display names use first names. All product pages use
`HomepageClosing` for the bottom Open app CTA and the shared feature heading styles.
-Chat sidebar parity: `workspace/ChatSidebar.tsx` adapts the app's
-`channels-view/components/rail/ExpandedChannelsRail.tsx` with local fixtures.
-It uses the shared Tabs and ViewSidebar controls, 32px section headers and a 4px
-header-to-list gap. Channels and DMs scroll independently. Verify search,
-section collapse, Threads navigation, and opening a mentioned source after
-switching channels. Message text uses the app's 15px/24px reading size; dark
-surface and edge tokens are frozen from `apps/web/src/index.css`.
+Chat sidebar demo: `workspace/ChatSidebar.tsx` retains the earlier
+All/Recent/Threads layout with local fixtures, shared Tabs and ViewSidebar
+controls, 32px section headers, and a 4px header-to-list gap. It is not the current
+app's sidebar parity target: `channels-view/components/rail/ExpandedChannelsRail.tsx`
+uses Favorites, Team channels, and custom sections in one scrolling list, with a
+sticky collapsible DM panel and no view tabs. Verify the demo's search, section
+collapse, thread navigation, and opening a mentioned source after switching
+channels. Message text uses the app's 15px/24px reading size; dark surface and edge
+tokens are frozen from `apps/web/src/index.css`.
Keep Merge/Merged and Open session actions in the shared agent chip at the same
24px height and pill radius, with touch resizing disabled for both.
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 27ab25db14..5941d0cc2a 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -528,11 +528,31 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
[dragging rows into a folder](../../docs/agent-guide/navigation.md#dragging-rows-into-a-folder).
- Keep channel rail and title menus on `CHANNEL_ACTION_VIEW_CONTEXT`, including
the shared desktop `Open in new split` action and its mobile/capacity guards.
+- Gate the Chat redesign with `enable-chat-sidebar-sections`; wait for its result, restore the tabbed rail when off, and keep mobile unchanged.
+ Keep the original rail renderer and label dialogs in `components/rail/`; build the redesigned rail and section dialogs in `components/rail/next/`, with shared controller, context, and row primitives outside `next/`.
+ With the flag on, keep desktop Chat sections in a scrolling stack with Favorites first and DMs directly below; personal and team-shared section assignments remain independent, including when dragging a row out of its originating section.
+ Keep resize grips keyboard-accessible, preserve per-section heights in personal preferences, and route list navigation through the sectioned renderer's scroll handle rather than global virtualizer indexes.
+ Cap section heights at measured list content and available pane space; hide resize grips for two or fewer items, default Favorites and DMs to four rows, and default other sections to their maximum height.
+ Mobile retains the recent feed. Keep New channel and New direct message on their separate existing creation flows, independent of the sidebar flag.
+ Use `--sidebar-gutter` for the outer section, DM, and search containers; shared headings and rows provide their own item padding.
+ Indent all section content by 8px, including Favorites, custom sections, DMs, and empty states; keep unsectioned search results unindented.
+ Reuse shared collapsible section headers and their hidden-caret behavior without leading icons; keep a neutral Shared badge next to the name before the caret, apply focus backgrounds across the full header row, and omit trailing header padding.
+ Space sections with the stack's flex gap, not header padding; wrap each custom section's header and content in one drop target and highlight.
+ Name the team-channel section after the current team, falling back to Team channels while its name is unavailable.
+ Keep available channel rows visible during section hydration and refetches; pass server-returned member IDs to `queries/channel/by-ids`, whose single Soup owner selects cached rows and fetches missing records. Keep entity-ID hydration generic in Soup, with channel identities, batching, and unread refreshes in the channel query layer; append per-section skeletons only while unresolved members load.
+ Show lock icons for private conversations and visible per-section options; keep empty sections usable as drop targets without an all-sections management menu.
+ Create all section types through New → New section in a wider dialog with Smart in the body and Shared in the footer; keep collapse on the header and style deletion as destructive.
+ Keep per-section sorting and unread filters personal, and filter after membership assignment so hidden rows never leak into another section.
+ Default Favorites to Custom order and persist drag reordering through the shared favorites mutation; preserve hidden and non-channel favorite positions, disable dragging under automatic sorts, show an insertion line at the actual destination edge, and keep the original rail unchanged.
+ Share the sliders-icon section menu's Sort, Filter, and actions with a header context menu; use trailing `SingleSelectCheck` marks for sorting, keep the Unread only label left and its switch right, and keep the filter submenu open when toggled.
+ Compose the section click and right-click menus with `ContextMenuContent`, `MenuItem`, `MenuGroup`, and `MenuSeparator`; do not nest padded `Dropdown.Group` elements inside a context-menu surface.
+ Keep all section mute, unmute, and snooze actions personal to the viewer; use the complete current membership, not filtered or hydrated rows, and never apply the change to later additions. Resolve built-in membership through the complete channel list, preserving sidebar assignment exclusions and participant checks; Favorites targets channel favorites only. Reuse notification mutations and the shared snooze picker, preserving successful writes on partial failure.
+ Use checkbox items in Add to section to toggle membership within each scope without changing the other scope.
- Route supported move, trash, restore, permanent-delete, duplicate, and share-policy
writes through `queries/storage/entity-mutations` when GraphQL Soup is enabled;
never retry failed GraphQL writes through REST. Preserve non-owner history removal
and version-specific markdown forks on their existing paths. Confirmed restores
- clear earlier deletion markers without clearing a newer delete's intent.
+ clear earlier deletion markers without clearing a newer delete's intent; key markers and restore confirmations by normalized entity type plus ID, never by bare ID.
- Preserve loaded block content on initial access confirmation when its loader
supplies no permissions; reload only on a later confirmed permission change.
Apply shared access in place only after a successful permissionless load.
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.md
index 159df9aa00..33861e084a 100644
--- a/apps/web/docs/graphql-normalized-cache-plan.md
+++ b/apps/web/docs/graphql-normalized-cache-plan.md
@@ -881,6 +881,25 @@ use `createSoupLiveQuery`: it adds Soup's local membership, ordering, pagination
and Mail policy through its predicate adapter. That policy remains outside
generic cache-core.
+Supported Soup predicates can read indexed matches before a server response,
+using an empty baseline. `useSoupAstItemsQuery.cacheStatus` reports local
+predicate readiness separately from network loading; `ready` does not prove
+complete server membership. `fetchError` retains background failures even when
+the display-oriented `error` keeps cached results quiet. Explicit entity lookups
+pass typed identities through `graphqlCacheFirstEntities`. The single Soup owner
+keeps the full-identity cache predicate separate from a stable missing-entity
+network request, including pagination and retries. Identity includes entity type,
+so equal IDs in different entity types remain independent. Channel lookups use
+`queries/channel/by-ids` for channel identities, batching, and bounded unread
+refreshes. Soup exposes generic revalidation descriptors rather than registering
+channel notification readers. Consumers receive rows and unresolved IDs without
+coordinating query lifetimes.
+Deletion markers use the same `typename:id` identity through pending mutations,
+retention, display filtering, and restore confirmation. Deleting or restoring a
+document must not hide or restore an unrelated channel with the same ID. The
+GraphQL-enabled deletion flow also scopes REST Soup and search side-cache
+removals to the entity type, including grouped caches and partial-failure rollback.
+
Mail list pages carry same-query server membership in the existing `baseline`
field. The Mail adapter reconciles only baseline rows outside the indexed window,
retaining unknown rows and rejecting confirmed nonmembers. Known read, archive,
diff --git a/apps/web/src/components/ui/components/ImperativeDialog.test.tsx b/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
index 3c48651ec5..86b722b31a 100644
--- a/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
+++ b/apps/web/src/components/ui/components/ImperativeDialog.test.tsx
@@ -1,5 +1,5 @@
import { cleanup, render, screen } from '@solidjs/testing-library';
-import { createRoot, getOwner } from 'solid-js';
+import { createMemo, createRoot, createSignal, getOwner } from 'solid-js';
import { afterEach, describe, expect, it } from 'vitest';
import { ImperativeDialogHost, openDialog } from './ImperativeDialog';
@@ -42,4 +42,40 @@ describe('keyed imperative dialogs', () => {
});
expect(screen.queryByRole('dialog')).toBeNull();
});
+
+ it('closes dialogs when a memo owner reruns without changing identity', async () => {
+ render(() => <ImperativeDialogHost />);
+ const Dialog = () => <div role="dialog">Section</div>;
+ const { owner, setSections, dispose } = createRoot((dispose) => {
+ const [sections, setSections] = createSignal(true);
+ const owner = createMemo(() => {
+ sections();
+ return getOwner();
+ });
+ return { owner, setSections, dispose };
+ });
+ try {
+ const initialOwner = owner();
+ const first = openDialog(Dialog, {}, { owner: initialOwner });
+ setSections(false);
+ expect(first.isOpen()).toBe(false);
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(owner()).toBe(initialOwner);
+ expect(await first.closed).toEqual({
+ id: first.id,
+ reason: 'owner-disposed',
+ });
+
+ const second = openDialog(Dialog, {}, { owner: owner() });
+ setSections(true);
+ expect(second.isOpen()).toBe(false);
+ expect(await second.closed).toEqual({
+ id: second.id,
+ reason: 'owner-disposed',
+ });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ } finally {
+ dispose();
+ }
+ });
});
diff --git a/apps/web/src/features/channels-view/channels-view-context.tsx b/apps/web/src/features/channels-view/channels-view-context.tsx
index f18cbf4d18..f70e18a8e2 100644
--- a/apps/web/src/features/channels-view/channels-view-context.tsx
+++ b/apps/web/src/features/channels-view/channels-view-context.tsx
@@ -13,7 +13,10 @@ import {
import { channelDetailRoute, channelsSplitRoute } from '@app/routes/routes';
import { createPreviewSelectionGuard } from '@components/app/createPreviewSelectionGuard';
import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
-import { enableChannelThreadsPreview } from '@core/constant/featureFlags';
+import {
+ enableChannelThreadsPreview,
+ enableChatSidebarSections,
+} from '@core/constant/featureFlags';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -30,13 +33,14 @@ import {
import { createChannelsViewPersistence } from './persistence';
import type {
ChannelListSort,
+ ChannelSectionKey,
+ ChannelSectionPreferences,
ChannelsRailSection,
ChannelsSortGroup,
ChannelsTab,
ChannelsViewState,
ChannelsViewStateOptions,
} from './types';
-import { activeChannelsTab } from './utils';
type ChannelsViewProviderProps = ContextProviderProps & {
initialState?: ChannelsViewStateOptions;
@@ -46,6 +50,9 @@ export type ChannelsViewContext = {
state: Store<ChannelsViewState>;
/** The mobile list opens channels in the split; only desktop renders detail. */
mobileLayout: () => boolean;
+ /** Whether the redesigned desktop sections are enabled. */
+ sectionsEnabled: Accessor<boolean>;
+ sectionsLoading: Accessor<boolean>;
selectedChannel: Accessor<ChannelPreviewSelection | undefined>;
/** Whether the Threads tab is available to this user. */
threadsEnabled: Accessor<boolean>;
@@ -64,6 +71,10 @@ export type ChannelsViewContext = {
/** Per-user collapse state of a team channel label. */
setLabelOpen: (labelId: string, open: boolean) => void;
setSortBy: (group: ChannelsSortGroup, sort: ChannelListSort) => void;
+ setSectionPreferences: (
+ section: ChannelSectionKey,
+ preferences: ChannelSectionPreferences
+ ) => void;
setAsideWidth: (width: number) => void;
};
@@ -89,6 +100,7 @@ function createInitialState(
CHANNELS_DEFAULT_SORT_BY.direct_messages,
threads: initial.sortBy?.threads ?? CHANNELS_DEFAULT_SORT_BY.threads,
},
+ sectionPreferences: { ...initial.sectionPreferences },
asideWidth: clampChannelsRailWidth(
initial.asideWidth ?? CHANNELS_DEFAULT_RAIL_WIDTH
),
@@ -108,6 +120,8 @@ export const [ChannelsViewProvider, useChannelsView] =
const navigate = useNavigate();
const params = useRouteParams(channelDetailRoute);
const [search, setSearch] = createSearchParams(channelsSearch);
+ const sectionsFlag = useFeatureFlag(enableChatSidebarSections);
+ const sectionsEnabled = () => sectionsFlag().enabled;
const threadsFlag = useFeatureFlag(enableChannelThreadsPreview);
const threadsEnabled = () => threadsFlag().enabled;
const selectPreview = createPreviewSelectionGuard();
@@ -218,8 +232,15 @@ export const [ChannelsViewProvider, useChannelsView] =
state,
mobileLayout,
selectedChannel,
+ sectionsEnabled,
+ sectionsLoading: () => sectionsFlag().loading,
threadsEnabled,
- tab: () => activeChannelsTab(state.tab, threadsEnabled()),
+ tab: () => {
+ if (sectionsEnabled()) return 'browse';
+ return state.tab === 'threads' && !threadsEnabled()
+ ? 'browse'
+ : state.tab;
+ },
threadsChannelId: () => state.threadsChannelId,
setThreadsChannelId: (channelId) => {
if (state.threadsChannelId === channelId) return;
@@ -241,6 +262,11 @@ export const [ChannelsViewProvider, useChannelsView] =
: [...collapsed, labelId]
),
setSortBy: (group, sort) => setState('sortBy', group, sort),
+ setSectionPreferences: (section, preferences) =>
+ setState('sectionPreferences', (current) => ({
+ ...current,
+ [section]: { ...current[section], ...preferences },
+ })),
setAsideWidth: (width) =>
setState('asideWidth', clampChannelsRailWidth(width)),
};
diff --git a/apps/web/src/features/channels-view/channels-view.test.tsx b/apps/web/src/features/channels-view/channels-view.test.tsx
index 58e3524df8..39657a212e 100644
--- a/apps/web/src/features/channels-view/channels-view.test.tsx
+++ b/apps/web/src/features/channels-view/channels-view.test.tsx
@@ -21,6 +21,7 @@ import { createStore } from 'solid-js/store';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChannelsDataSource } from './queries';
+import type { ChannelsTab } from './types';
type FullChannel = ChannelEntity & { notifications: Notification[] };
const mocks = vi.hoisted(() => ({
@@ -28,6 +29,9 @@ const mocks = vi.hoisted(() => ({
selectedId: (): string | undefined => undefined,
rows: (): ChannelEntity[] => [],
mobileLayout: (): boolean => false,
+ sectionsEnabled: (): boolean => true,
+ sectionsLoading: (): boolean => false,
+ tab: (): ChannelsTab => 'browse',
active: (): boolean => true,
searchOpen: (): boolean => false,
searchText: (): string => '',
@@ -181,7 +185,12 @@ vi.mock('./channels-view-context', () => ({
tab: 'browse',
sortBy: { channels: 'updated_at', direct_messages: 'updated_at' },
},
- tab: () => 'browse',
+ tab: () => (mocks.sectionsEnabled() ? 'browse' : mocks.tab()),
+ sectionsEnabled: () => mocks.sectionsEnabled(),
+ sectionsLoading: () => mocks.sectionsLoading(),
+ threadsChannelId: () => undefined,
+ setTab: vi.fn(),
+ setSelectedChannel: vi.fn(),
mobileLayout: () => mocks.mobileLayout(),
selectedChannel: () =>
mocks.selectedId()
@@ -215,6 +224,7 @@ vi.mock('./queries', () => ({
direct_messages: { items: () => mocks.rows() },
recents: { items: () => mocks.rows() },
search: { items: () => [] },
+ threads: { items: () => mocks.rows() },
};
},
}));
@@ -264,6 +274,9 @@ let setRows: ReturnType<typeof createSignal<ChannelEntity[]>>[1];
beforeEach(() => {
vi.clearAllMocks();
mocks.mobileLayout = () => false;
+ mocks.sectionsEnabled = () => true;
+ mocks.sectionsLoading = () => false;
+ mocks.tab = () => 'browse';
mocks.favoriteIds = () => [];
mocks.active = () => true;
mocks.searchOpen = () => false;
@@ -303,6 +316,63 @@ beforeEach(() => {
});
afterEach(cleanup);
+describe('Chat rollout source activation', () => {
+ it('waits for the desktop flag before loading sources or mounting either experience', () => {
+ const [loading, setLoading] = createSignal(true);
+ mocks.sectionsLoading = loading;
+ mocks.sectionsEnabled = () => false;
+ mocks.tab = () => 'recents';
+ render(() => <ChannelsView />);
+ for (const scope of [
+ 'team_channels',
+ 'channels',
+ 'direct_messages',
+ 'recents',
+ 'threads',
+ 'search',
+ ]) {
+ expect(mocks.sourceEnabled(scope)).toBe(false);
+ }
+ expect(screen.queryByTestId('channel-detail')).toBeNull();
+ setLoading(false);
+ expect(mocks.sourceEnabled('recents')).toBe(true);
+ expect(mocks.sourceEnabled('channels')).toBe(false);
+ });
+
+ it('restores a saved legacy tab without activating it while sections are enabled', () => {
+ const [enabled, setEnabled] = createSignal(true);
+ mocks.sectionsEnabled = enabled;
+ mocks.tab = () => 'recents';
+ render(() => <ChannelsView />);
+ expect(mocks.sourceEnabled('channels')).toBe(true);
+ expect(mocks.sourceEnabled('recents')).toBe(false);
+ setEnabled(false);
+ expect(mocks.sourceEnabled('channels')).toBe(false);
+ expect(mocks.sourceEnabled('recents')).toBe(true);
+ });
+
+ it('restores the Threads surface only in the legacy layout', () => {
+ const [enabled, setEnabled] = createSignal(false);
+ mocks.sectionsEnabled = enabled;
+ mocks.tab = () => 'threads';
+ render(() => <ChannelsView />);
+ expect(screen.getByTestId('channel-threads')).toBeTruthy();
+ expect(mocks.sourceEnabled('threads')).toBe(true);
+ setEnabled(true);
+ expect(screen.queryByTestId('channel-threads')).toBeNull();
+ expect(mocks.sourceEnabled('threads')).toBe(false);
+ expect(mocks.sourceEnabled('channels')).toBe(true);
+ });
+
+ it('keeps the mobile recent feed active while the desktop rollout is unresolved', () => {
+ mocks.mobileLayout = () => true;
+ mocks.sectionsLoading = () => true;
+ render(() => <ChannelsView />);
+ expect(screen.getByTestId('mobile-channels')).toBeTruthy();
+ expect(mocks.sourceEnabled('recents')).toBe(true);
+ expect(mocks.sourceEnabled('channels')).toBe(false);
+ });
+});
describe('mobile dock search wiring', () => {
it('shows only recent conversations independently of the dock search session', () => {
mocks.mobileLayout = () => true;
diff --git a/apps/web/src/features/channels-view/channels-view.tsx b/apps/web/src/features/channels-view/channels-view.tsx
index aa8dd2e41f..8b1e5426b3 100644
--- a/apps/web/src/features/channels-view/channels-view.tsx
+++ b/apps/web/src/features/channels-view/channels-view.tsx
@@ -141,17 +141,23 @@ function DesktopChannelThreads(props: { sources: ChannelsSources }) {
/>
);
}
-
function ChannelsViewRoot() {
const panel = useSplitPanelOrThrow();
- const { state, tab, mobileLayout, selectedChannel, setAsideWidth } =
- useChannelsView();
+ const {
+ state,
+ tab,
+ mobileLayout,
+ sectionsLoading,
+ selectedChannel,
+ setAsideWidth,
+ } = useChannelsView();
const threadsTab = () => !mobileLayout() && tab() === 'threads';
const [railSearchOpen, setRailSearchOpen] = createSignal(false);
const sources = useChannelsSources(
(scope) => {
if (mobileLayout()) return scope === 'recents';
+ if (sectionsLoading()) return false;
if (railSearchOpen()) return scope === 'search';
if (scope === 'search') return false;
if (scope === 'recents') return tab() === 'recents';
@@ -165,106 +171,117 @@ function ChannelsViewRoot() {
return (
<ListEntityMetadataQueryProvider>
<StaticMarkdownContext>
- <SplitPanel.Root>
- <SplitPanel.Body>
- <Show
- when={mobileLayout()}
- fallback={
- <div class="size-full min-h-0 bg-panel">
- <ViewShell.Root
- asidePreferenceKey="channels"
- // The empty state only points at the rail, so keep it open.
- asideRequired={selectedChannel() === undefined}
- // Keep the tab out of asideRequired: every change to it
- // resets a narrow overlay, so switching tabs inside the
- // overlay would close it.
- asidePinned={threadsTab()}
- aside={{
- width: state.asideWidth,
- preserveDuringResize: false,
- }}
- main={{ preferredWidth: 640 }}
- resizable
- >
- <ViewShell.Aside onWidthChangeEnd={setAsideWidth}>
- <DebugSuspense
- name="ChannelsView.rail"
- fallback={
- <SpinnerIcon
- aria-hidden={false}
- aria-label="Loading channels"
- class="size-5 animate-spin"
+ <Show
+ when={mobileLayout() || !sectionsLoading()}
+ fallback={
+ <div class="grid size-full place-items-center">
+ <SpinnerIcon
+ aria-hidden={false}
+ aria-label="Loading channels"
+ class="size-5 animate-spin"
+ />
+ </div>
+ }
+ >
+ <SplitPanel.Root>
+ <SplitPanel.Body>
+ <Show
+ when={mobileLayout()}
+ fallback={
+ <div class="size-full min-h-0 bg-panel">
+ <ViewShell.Root
+ asidePreferenceKey="channels"
+ // The empty state only points at the rail, so keep it open.
+ asideRequired={selectedChannel() === undefined}
+ // Keep tab changes from resetting a narrow navigation overlay.
+ asidePinned={threadsTab()}
+ aside={{
+ width: state.asideWidth,
+ preserveDuringResize: false,
+ }}
+ main={{ preferredWidth: 640 }}
+ resizable
+ >
+ <ViewShell.Aside onWidthChangeEnd={setAsideWidth}>
+ <DebugSuspense
+ name="ChannelsView.rail"
+ fallback={
+ <SpinnerIcon
+ aria-hidden={false}
+ aria-label="Loading channels"
+ class="size-5 animate-spin"
+ />
+ }
+ >
+ <DesktopChannelsRail
+ sources={sources}
+ searchOpen={railSearchOpen()}
+ onSearchOpenChange={setRailSearchOpen}
/>
- }
- >
- <DesktopChannelsRail
- sources={sources}
- searchOpen={railSearchOpen()}
- onSearchOpenChange={setRailSearchOpen}
- />
- </DebugSuspense>
- </ViewShell.Aside>
- <ViewShell.Main class="overflow-hidden">
- <ViewTour tour={channelsTour} />
- <Show
- when={!threadsTab()}
- fallback={
- <DebugSuspense name="ChannelsView.threads">
- <DesktopChannelThreads sources={sources} />
- </DebugSuspense>
- }
- >
- <ChannelSourcesContext.Provider value={sources}>
- <DebugSuspense name="ChannelsView.outlet">
- <SplitRouter.Outlet
- fallback={() => (
- <>
- <ViewShell.TopBar>
- <ViewSidebar.Title caret={false}>
- Chat
- </ViewSidebar.Title>
- </ViewShell.TopBar>
- <div class="flex min-h-0 flex-1 items-center justify-center px-6 text-center">
- <div class="flex max-w-sm flex-col gap-2">
- <h2 class="text-base font-semibold text-ink">
- Select a conversation
- </h2>
- <p class="text-sm leading-5 text-ink-muted">
- Choose a channel or person from the
- sidebar to open the conversation here.
- </p>
+ </DebugSuspense>
+ </ViewShell.Aside>
+ <ViewShell.Main class="overflow-hidden">
+ <ViewTour tour={channelsTour} />
+ <Show
+ when={!threadsTab()}
+ fallback={
+ <DebugSuspense name="ChannelsView.threads">
+ <DesktopChannelThreads sources={sources} />
+ </DebugSuspense>
+ }
+ >
+ <ChannelSourcesContext.Provider value={sources}>
+ <DebugSuspense name="ChannelsView.outlet">
+ <SplitRouter.Outlet
+ fallback={() => (
+ <>
+ <ViewShell.TopBar>
+ <ViewSidebar.Title caret={false}>
+ Chat
+ </ViewSidebar.Title>
+ </ViewShell.TopBar>
+ <div class="flex min-h-0 flex-1 items-center justify-center px-6 text-center">
+ <div class="flex max-w-sm flex-col gap-2">
+ <h2 class="text-base font-semibold text-ink">
+ Select a conversation
+ </h2>
+ <p class="text-sm leading-5 text-ink-muted">
+ Choose a channel or person from the
+ sidebar to open the conversation here.
+ </p>
+ </div>
</div>
- </div>
- </>
- )}
- />
- </DebugSuspense>
- </ChannelSourcesContext.Provider>
- </Show>
- </ViewShell.Main>
- </ViewShell.Root>
- </div>
- }
- >
- <MaybeSoupEntityActionDrawerManager>
- <DebugSuspense
- name="ChannelsView.mobile"
- fallback={
- <div class="grid size-full place-items-center text-ink-muted">
- <SpinnerIcon
- aria-hidden={false}
- aria-label="Loading channels"
- class="size-5 animate-spin"
- />
- </div>
- }
- >
- <MobileChannelsList sources={sources} />
- </DebugSuspense>
- </MaybeSoupEntityActionDrawerManager>
- </Show>
- </SplitPanel.Body>
- </SplitPanel.Root>
+ </>
+ )}
+ />
+ </DebugSuspense>
+ </ChannelSourcesContext.Provider>
+ </Show>
+ </ViewShell.Main>
+ </ViewShell.Root>
+ </div>
+ }
+ >
+ <MaybeSoupEntityActionDrawerManager>
+ <DebugSuspense
+ name="ChannelsView.mobile"
+ fallback={
+ <div class="grid size-full place-items-center text-ink-muted">
+ <SpinnerIcon
+ aria-hidden={false}
+ aria-label="Loading channels"
+ class="size-5 animate-spin"
+ />
+ </div>
+ }
+ >
+ <MobileChannelsList sources={sources} />
+ </DebugSuspense>
+ </MaybeSoupEntityActionDrawerManager>
+ </Show>
+ </SplitPanel.Body>
+ </SplitPanel.Root>
+ </Show>
</StaticMarkdownContext>
</ListEntityMetadataQueryProvider>
);
diff --git a/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx b/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx
index e6b1feed3b..6e6995a4b4 100644
--- a/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx
+++ b/apps/web/src/features/channels-view/components/ConversationsCreateMenu.tsx
@@ -1,17 +1,27 @@
import { ViewSidebar } from '@app/components/view-shell';
import { ViewCreateButton } from '@app/components/view-shell/ViewCreateButton';
import { runCreateAction } from '@app/features/command/Launcher';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { t } from '@app/lib/i18n';
import { openNewChannelModal } from '@channel/CreateChannelModal';
-import ChatCircleIcon from '@icon/system/regular/chat-circle.svg';
+import { enableChatSidebarSections } from '@core/constant/featureFlags';
+import ChatIcon from '@icon/system/regular/chat-circle.svg';
import HashIcon from '@icon/system/regular/hash.svg';
import PlusIcon from '@icon/system/regular/plus.svg';
import { Dropdown } from '@ui';
+import { tourTarget } from '@ui/components/Tour';
import { Show } from 'solid-js';
+import { CHANNELS_TOUR } from '../tour';
-/** Channel and direct-message creation in the Chat navigation. */
+/** Channel, direct-message, and section creation in the Chat navigation. */
export function ConversationsCreateMenu(props: {
presentation?: 'sidebar' | 'toolbar';
+ onCreateSection?: () => void;
+ sectionDisabledReason?: string;
}) {
+ const sections = useFeatureFlag(enableChatSidebarSections);
+ const label = () => t('channelSections.createChannelOrDirectMessage');
+
return (
<Dropdown
placement={
@@ -22,11 +32,9 @@ export function ConversationsCreateMenu(props: {
when={props.presentation}
fallback={
<Dropdown.Trigger
- aria-label="Create channel or direct message"
- tooltip="Create channel or direct message"
as={ViewSidebar.Control}
- variant="ghost"
- size="icon-sm"
+ aria-label={label()}
+ tooltip={label()}
>
<PlusIcon class="size-3.5" />
</Dropdown.Trigger>
@@ -34,22 +42,40 @@ export function ConversationsCreateMenu(props: {
>
<Dropdown.Trigger
as={ViewCreateButton}
+ ref={tourTarget(CHANNELS_TOUR.create)}
presentation={props.presentation}
menu
- aria-label="Create channel or direct message"
+ aria-label={label()}
/>
</Show>
- <Dropdown.Content class="min-w-44">
+ <Dropdown.Content
+ class="min-w-48"
+ onCloseAutoFocus={(event) => {
+ if (document.querySelector('[role="dialog"]')) {
+ event.preventDefault();
+ }
+ }}
+ >
<Dropdown.Group>
<Dropdown.Item onSelect={openNewChannelModal}>
<HashIcon class="size-3.5 shrink-0 text-ink-muted" />
- <span>New channel</span>
+ {t('channelSections.newChannel')}
</Dropdown.Item>
<Dropdown.Item onSelect={() => runCreateAction('channel')}>
- <ChatCircleIcon class="size-3.5 shrink-0 text-ink-muted" />
- <span>New direct message</span>
+ <ChatIcon class="size-3.5 shrink-0 text-ink-muted" />
+ {t('channelSections.newDirectMessage')}
</Dropdown.Item>
</Dropdown.Group>
+ <Show when={sections().enabled && props.onCreateSection}>
+ <Dropdown.Group>
+ <Dropdown.Item
+ disabledReason={props.sectionDisabledReason}
+ onSelect={() => props.onCreateSection?.()}
+ >
+ {t('channelSections.newSection')}
+ </Dropdown.Item>
+ </Dropdown.Group>
+ </Show>
</Dropdown.Content>
</Dropdown>
);
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx
index 7bc66a5bc3..18ee8de751 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.test.tsx
@@ -1,6 +1,14 @@
import type { ChannelEntity } from '@entity';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
import type { Favorite } from '@service-storage/generated/schemas/favorite';
-import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ renderHook,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
import {
type ComponentProps,
createSignal,
@@ -11,12 +19,89 @@ import {
} from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ChannelFavoriteRow } from './ChannelFavoriteRows';
+import { ChannelOption } from './ChannelOption';
+import { ChannelFavoriteRow as DraggableFavoriteRow } from './next/ChannelFavoriteRow';
+import { ResizableRailSection } from './next/ResizableRailSection';
+import {
+ reorderVisibleFavorites,
+ useFavoriteReorder,
+} from './next/useFavoriteReorder';
+const measurements = vi.hoisted(() => ({ contentHeight: (): number => 400 }));
const rail = vi.hoisted(() => ({
channelById: (_channelId: string): ChannelEntity | undefined => undefined,
activateRow: vi.fn(),
prefetchRow: vi.fn(),
list: { focus: { set: vi.fn() } },
+ railId: 'rail',
+ sectionPreferences: () => ({ sort: 'manual' }),
+ setSectionPreferences: vi.fn(),
+ labels: (): ChannelLabel[] => [],
+ labelsAvailable: () => true,
+ sectionsEnabled: () => true,
+ activeDropTarget: () => undefined,
+}));
+
+const drag = vi.hoisted(() => ({
+ starts: [] as Array<
+ (event: { draggable: { data: Record<string, unknown> } }) => void
+ >,
+ ends: [] as Array<
+ (event: {
+ draggable: { data: Record<string, unknown> };
+ droppable: { data: Record<string, unknown> };
+ }) => void
+ >,
+ favorites: [] as Favorite[],
+ draggables: new Map<string, Record<string, unknown>>(),
+ reorder: vi.fn(
+ async (_args: {
+ favorites: { entityId: string; entityType: string }[];
+ }) => ({ kind: 'committed' })
+ ),
+}));
+vi.mock('@queries/favorites/favorites', () => ({
+ useFavoritesData: () => () => ({ favorites: drag.favorites }),
+ useReorderFavoritesMutation: () => ({ mutateAsync: drag.reorder }),
+}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: {
+ span: async (
+ _name: string,
+ run: (span: { setAttr: () => void }) => Promise<void>
+ ) => await run({ setAttr() {} }),
+ },
+}));
+vi.mock('@solid-primitives/resize-observer', () => ({
+ createElementSize: (element: () => HTMLElement | undefined) => ({
+ width: 200,
+ get height() {
+ return element()?.hasAttribute('data-section-content')
+ ? measurements.contentHeight()
+ : 100;
+ },
+ }),
+}));
+vi.mock('@thisbeyond/solid-dnd', () => ({
+ createDraggable: (id: string, data: Record<string, unknown>) => {
+ drag.draggables.set(id, data);
+ return {
+ ref() {},
+ dragActivators: {},
+ isActiveDraggable: false,
+ };
+ },
+ createDroppable: () => ({ ref() {}, isActiveDroppable: false }),
+ useDragDropContext: () => [
+ { active: {} },
+ {
+ onDragStart: (callback: (typeof drag.starts)[number]) =>
+ drag.starts.push(callback),
+ onDragEnd: (callback: (typeof drag.ends)[number]) =>
+ drag.ends.push(callback),
+ },
+ ],
}));
vi.mock('./ChannelsRailContext', async (importOriginal) => ({
@@ -25,6 +110,12 @@ vi.mock('./ChannelsRailContext', async (importOriginal) => ({
}));
vi.mock('./ChannelsRailSection', () => ({}));
vi.mock('./hooks/useChannelRailState', () => ({
+ useChannelRailItemState: () => () => ({
+ domId: 'rail-channel-row',
+ selected: false,
+ focused: false,
+ muted: false,
+ }),
useChannelRailFavoriteItemState: () => () => ({
domId: 'rail-favorite-row',
selected: false,
@@ -40,6 +131,9 @@ vi.mock('./hooks/useChannelRailState', () => ({
}),
}));
vi.mock('./ChannelRailItems', () => ({
+ ChannelAvatar: () => <span />,
+ ChannelCallIndicator: () => null,
+ IncomingCallActions: () => null,
isPrimaryMouseDown: (event: MouseEvent) => event.button === 0,
ChannelRailItemContextMenu: (
props: ParentProps<{
@@ -58,7 +152,7 @@ vi.mock('./ChannelRailItems', () => ({
</div>
),
}));
-vi.mock('./ChannelLabelRows', () => ({
+vi.mock('./next/ChannelLabelRows', () => ({
ChannelLabelMenuItems: (props: { channel: ChannelEntity }) => (
<span data-testid="label-actions" data-channel={props.channel.id} />
),
@@ -117,13 +211,75 @@ const channel = {
let setChannel: Setter<ChannelEntity | undefined>;
beforeEach(() => {
vi.clearAllMocks();
+ drag.starts.length = 0;
+ drag.ends.length = 0;
+ drag.draggables.clear();
+ rail.labels = () => [];
+ drag.favorites = [];
const [loaded, update] = createSignal<ChannelEntity | undefined>(undefined);
+ [measurements.contentHeight] = createSignal(400);
setChannel = update;
rail.channelById = (channelId) =>
loaded()?.id === channelId ? loaded() : undefined;
});
afterEach(cleanup);
+describe('channel section drag sources', () => {
+ it('keeps each rendered section as the drag source when a channel belongs to both scopes', () => {
+ rail.labels = () => [
+ {
+ id: 'shared',
+ name: 'Shared',
+ teamId: 'team',
+ channelIds: ['design'],
+ channelCount: 1,
+ sortOrder: 0,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ },
+ {
+ id: 'personal',
+ name: 'Personal',
+ channelIds: ['design'],
+ channelCount: 1,
+ sortOrder: 0,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ },
+ ];
+ render(() => (
+ <>
+ <ChannelOption
+ channel={channel}
+ rowId="channel:design:label:shared"
+ labelId="shared"
+ draggable
+ />
+ <ChannelOption
+ channel={channel}
+ rowId="channel:design:label:personal"
+ labelId="personal"
+ draggable
+ />
+ <ChannelOption channel={channel} draggable />
+ </>
+ ));
+
+ expect(
+ drag.draggables.get('rail:channel-label:drag:channel:design:label:shared')
+ ?.labelId
+ ).toBe('shared');
+ expect(
+ drag.draggables.get(
+ 'rail:channel-label:drag:channel:design:label:personal'
+ )?.labelId
+ ).toBe('personal');
+ expect(
+ drag.draggables.get('rail:channel-label:drag:channel:design')?.labelId
+ ).toBe('shared');
+ });
+});
+
describe('favorite rows in the chat rail', () => {
it('gives a favorited channel its channel actions, aimed at the favorite row', () => {
setChannel(channel);
@@ -171,3 +327,283 @@ describe('favorite rows in the chat rail', () => {
);
});
});
+
+describe('favorite reordering', () => {
+ const first: Favorite = { ...favorite, entityId: 'first' };
+ const last: Favorite = { ...favorite, entityId: 'last' };
+ const hidden: Favorite = { ...favorite, entityId: 'hidden' };
+ const document: Favorite = {
+ ...favorite,
+ entityType: 'document',
+ entityId: 'first',
+ };
+ const original = [first, document, hidden, last];
+
+ it('moves visible favorites without moving hidden or other-type slots', () => {
+ expect(
+ reorderVisibleFavorites(
+ original,
+ [first, last],
+ 'favorite:channel:last',
+ 'favorite:channel:first'
+ )
+ ).toEqual([last, document, hidden, first]);
+ expect(original).toEqual([first, document, hidden, last]);
+ });
+
+ it('ignores self drops, missing targets, and incomplete favorite snapshots', () => {
+ expect(
+ reorderVisibleFavorites(
+ original,
+ [first, last],
+ 'favorite:channel:first',
+ 'favorite:channel:first'
+ )
+ ).toBeUndefined();
+ expect(
+ reorderVisibleFavorites(
+ original,
+ [first, last],
+ 'favorite:channel:first',
+ 'favorite:channel:missing'
+ )
+ ).toBeUndefined();
+ expect(
+ reorderVisibleFavorites(
+ [first],
+ [first, last],
+ 'favorite:channel:first',
+ 'favorite:channel:last'
+ )
+ ).toBeUndefined();
+ });
+
+ it('sends the complete reordered list through the shared mutation', async () => {
+ drag.favorites = original;
+ renderHook(() => useFavoriteReorder(() => [first, last]));
+ const source = {
+ data: {
+ dndScope: 'rail:favorites',
+ favoriteKey: 'favorite:channel:last',
+ },
+ };
+ const target = {
+ data: {
+ dndScope: 'rail:favorites',
+ favoriteKey: 'favorite:channel:first',
+ },
+ };
+ drag.starts.forEach((start) => start({ draggable: source }));
+ drag.ends.forEach((end) => end({ draggable: source, droppable: target }));
+ await waitFor(() =>
+ expect(drag.reorder).toHaveBeenCalledExactlyOnceWith({
+ favorites: [last, document, hidden, first].map(
+ ({ entityId, entityType }) => ({ entityId, entityType })
+ ),
+ })
+ );
+ });
+
+ it('suppresses drag clicks without blocking keyboard or later pointer activation', () => {
+ render(() => (
+ <DraggableFavoriteRow
+ favorite={favorite}
+ reorder={{
+ scope: 'rail:favorites',
+ enabled: () => true,
+ dropEdge: () => undefined,
+ }}
+ />
+ ));
+ drag.starts.forEach((start) =>
+ start({
+ draggable: {
+ data: {
+ dndScope: 'rail:favorites',
+ favoriteKey: 'favorite:channel:design',
+ },
+ },
+ })
+ );
+ fireEvent.click(screen.getByRole('treeitem'), { detail: 1 });
+ expect(rail.activateRow).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('treeitem'), { detail: 0 });
+ expect(rail.activateRow).toHaveBeenCalledOnce();
+ fireEvent.pointerDown(screen.getByRole('treeitem'));
+ fireEvent.click(screen.getByRole('treeitem'), { detail: 1 });
+ expect(rail.activateRow).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('resizable chat sections', () => {
+ it('saves the final zoom-adjusted size and can resize again after collapse cancels a drag', () => {
+ const [open, setOpen] = createSignal(true);
+ render(() => (
+ <ResizableRailSection
+ section="favorites"
+ label="Favorites"
+ open={open()}
+ maxHeight={400}
+ itemCount={12}
+ header={<span>Section</span>}
+ rootRef={() => {}}
+ scrollRef={(element) => {
+ Object.defineProperty(element, 'offsetHeight', { value: 100 });
+ vi.spyOn(element, 'getBoundingClientRect').mockReturnValue(
+ new DOMRect(0, 0, 200, 200)
+ );
+ }}
+ >
+ Conversations
+ </ResizableRailSection>
+ ));
+ let handle = screen.getByRole('separator');
+ Object.defineProperty(handle, 'setPointerCapture', { value: vi.fn() });
+ for (const [type, y] of [
+ ['pointerdown', 100],
+ ['pointermove', 140],
+ ['pointerup', 180],
+ ] as const) {
+ const event = new MouseEvent(type, {
+ bubbles: true,
+ button: 0,
+ clientY: y,
+ });
+ Object.defineProperty(event, 'pointerId', { value: 1 });
+ handle.dispatchEvent(event);
+ }
+ expect(rail.setSectionPreferences).toHaveBeenCalledExactlyOnceWith(
+ 'favorites',
+ { height: 140 }
+ );
+ const start = new MouseEvent('pointerdown', {
+ bubbles: true,
+ button: 0,
+ clientY: 100,
+ });
+ Object.defineProperty(start, 'pointerId', { value: 1 });
+ handle.dispatchEvent(start);
+ setOpen(false);
+ expect(rail.setSectionPreferences).toHaveBeenCalledTimes(1);
+ setOpen(true);
+ handle = screen.getByRole('separator');
+ Object.defineProperty(handle, 'setPointerCapture', { value: vi.fn() });
+ for (const [type, y] of [
+ ['pointerdown', 100],
+ ['pointerup', 160],
+ ] as const) {
+ const event = new MouseEvent(type, {
+ bubbles: true,
+ button: 0,
+ clientY: y,
+ });
+ Object.defineProperty(event, 'pointerId', { value: 1 });
+ handle.dispatchEvent(event);
+ }
+ expect(rail.setSectionPreferences).toHaveBeenLastCalledWith('favorites', {
+ height: 130,
+ });
+ });
+
+ it('clamps keyboard resizing and resets only the section height', () => {
+ render(() => (
+ <ResizableRailSection
+ section="favorites"
+ label="Favorites"
+ open
+ maxHeight={120}
+ itemCount={4}
+ header={<span>Section</span>}
+ rootRef={() => {}}
+ scrollRef={() => {}}
+ >
+ Conversations
+ </ResizableRailSection>
+ ));
+ const handle = screen.getByRole('separator');
+ fireEvent.keyDown(handle, { key: 'ArrowUp', shiftKey: true });
+ expect(rail.setSectionPreferences).toHaveBeenLastCalledWith('favorites', {
+ height: 68,
+ });
+ fireEvent.keyDown(handle, { key: 'ArrowDown', shiftKey: true });
+ expect(rail.setSectionPreferences).toHaveBeenLastCalledWith('favorites', {
+ height: 120,
+ });
+ fireEvent.dblClick(handle);
+ expect(rail.setSectionPreferences).toHaveBeenLastCalledWith('favorites', {
+ height: undefined,
+ });
+ });
+
+ it('caps resizing at the content height and drops the handle when filtering leaves two items', () => {
+ const [count, setCount] = createSignal(3);
+ const [contentHeight, setContentHeight] = createSignal(102);
+ measurements.contentHeight = contentHeight;
+ let scrollElement: HTMLDivElement | undefined;
+ render(() => (
+ <ResizableRailSection
+ section="team_channels"
+ label="Team channels"
+ open
+ maxHeight={400}
+ itemCount={count()}
+ header={<span>Section</span>}
+ rootRef={() => {}}
+ scrollRef={(element) => {
+ scrollElement = element;
+ }}
+ >
+ Conversations
+ </ResizableRailSection>
+ ));
+ const handle = screen.getByRole('separator');
+ expect(handle.getAttribute('aria-valuemax')).toBe('102');
+ expect(handle.getAttribute('aria-valuenow')).toBe('102');
+ expect(scrollElement?.style.height).toBe('102px');
+ fireEvent.keyDown(handle, { key: 'ArrowDown', shiftKey: true });
+ expect(rail.setSectionPreferences).toHaveBeenLastCalledWith(
+ 'team_channels',
+ { height: 102 }
+ );
+
+ Object.defineProperty(handle, 'setPointerCapture', { value: vi.fn() });
+ const start = new MouseEvent('pointerdown', {
+ bubbles: true,
+ button: 0,
+ clientY: 100,
+ });
+ Object.defineProperty(start, 'pointerId', { value: 1 });
+ handle.dispatchEvent(start);
+ setCount(2);
+ setContentHeight(68);
+ expect(screen.queryByRole('separator')).toBeNull();
+ expect(scrollElement?.style.height).toBe('68px');
+ const finish = new MouseEvent('pointerup', { bubbles: true, clientY: 300 });
+ Object.defineProperty(finish, 'pointerId', { value: 1 });
+ handle.dispatchEvent(finish);
+ expect(rail.setSectionPreferences).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['favorites', 'direct_messages', 'team_channels'] as const)(
+ 'uses the default height for %s within the content and viewport limits',
+ (section) => {
+ render(() => (
+ <ResizableRailSection
+ section={section}
+ label={section}
+ open
+ maxHeight={300}
+ itemCount={12}
+ header={<span>Section</span>}
+ rootRef={() => {}}
+ scrollRef={() => {}}
+ >
+ Conversations
+ </ResizableRailSection>
+ ));
+ expect(screen.getByRole('separator').getAttribute('aria-valuenow')).toBe(
+ section === 'team_channels' ? '300' : '136'
+ );
+ }
+ );
+});
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx
index bd3bc8a175..414539064a 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelFavoriteRows.tsx
@@ -8,8 +8,8 @@ import CaretDownIcon from '@icon/system/regular/caret-down.svg';
import type { Favorite } from '@service-storage/generated/schemas/favorite';
import { cn } from '@ui';
import { For, Show } from 'solid-js';
-import { ChannelLabelMenuItems } from './ChannelLabelRows';
import {
+ ChannelAvatar,
ChannelRailItemContextMenu,
isPrimaryMouseDown,
} from './ChannelRailItems';
@@ -19,6 +19,7 @@ import {
useChannelRailFavoriteItemState,
useChannelRailFavoritesState,
} from './hooks/useChannelRailState';
+import { ChannelLabelMenuItems } from './next/ChannelLabelRows';
/**
* A favorite row in the Chat sidebar. The rail only favorites channels, so the
@@ -65,7 +66,12 @@ export function ChannelFavoriteRow(props: { favorite: Favorite }) {
}}
>
<ViewSidebar.Icon>
- <FavoriteIcon favorite={props.favorite} class="size-4" />
+ <Show
+ when={channel()?.channelType === 'private' ? channel() : undefined}
+ fallback={<FavoriteIcon favorite={props.favorite} class="size-4" />}
+ >
+ {(channel) => <ChannelAvatar channel={channel()} />}
+ </Show>
</ViewSidebar.Icon>
<span class="min-w-0 flex-1 truncate">{displayName()}</span>
<ChannelMutedIndicator muted={item().muted} />
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx
index c6ecbc05c6..f99d5329e6 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelLabelRows.tsx
@@ -25,7 +25,7 @@ import type { ChannelLabel } from '@service-storage/generated/schemas/channelLab
import { createDroppable } from '@thisbeyond/solid-dnd';
import { cn, Dropdown } from '@ui';
import { type Component, For, type JSX, Show } from 'solid-js';
-import { canLabelChannel } from '../../core/channel-label-eligibility';
+import { canLabelChannel as canLabelConversation } from '../../core/channel-label-eligibility';
import { isPrimaryMouseDown } from './ChannelRailItems';
import {
type ChannelLabelDropData,
@@ -36,6 +36,9 @@ import { useChannelRailLabelState } from './hooks/useChannelRailState';
type MenuIcon = Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
+const canLabelChannel = (channel: ChannelEntity) =>
+ channel.channelType === 'team' && canLabelConversation(channel);
+
/** A dropdown row in the house style: muted icon, muted label. */
function MenuRow(props: {
icon: MenuIcon;
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelListViews.tsx b/apps/web/src/features/channels-view/components/rail/ChannelListViews.tsx
new file mode 100644
index 0000000000..133ce22162
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/ChannelListViews.tsx
@@ -0,0 +1,239 @@
+import { ViewSidebar } from '@app/components/view-shell';
+import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
+import { useUserId } from '@core/context/user';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { createScrollTopFade } from '@core/util/createScrollTopFade';
+import type { ChannelEntity } from '@entity';
+import ChatsCircleIcon from '@icon/system/regular/chats-circle.svg';
+import { cn } from '@ui';
+import { createSignal, Match, Show, Switch } from 'solid-js';
+import { Virtualizer } from 'virtua/solid';
+import { channelMentionsUser } from '../../utils';
+import { ChannelsEmptyState } from '../ChannelsEmptyState';
+import { ConversationsCreateMenu } from '../ConversationsCreateMenu';
+import { ChannelLabelMenuItems } from './ChannelLabelRows';
+import { ChannelOption } from './ChannelOption';
+import {
+ ChannelRailItemContextMenu,
+ CONVERSATION_CARD_HEIGHT,
+ ConversationCard,
+ isPrimaryMouseDown,
+} from './ChannelRailItems';
+import { ChannelSortDropdown } from './ChannelSortDropdown';
+import {
+ ALL_THREADS_ROW_ID,
+ domIdForRow,
+ rowKeyForChannel,
+ useChannelsRail,
+} from './ChannelsRailContext';
+import {
+ CollapsibleSection,
+ RailListError,
+ RailListLoading,
+ RailListLoadingMore,
+} from './ChannelsRailSection';
+import {
+ useChannelRailItemState,
+ useChannelRailScopeState,
+ useChannelRailVirtualizer,
+} from './hooks/useChannelRailState';
+
+export function RecentConversationCard(props: { channel: ChannelEntity }) {
+ const rail = useChannelsRail();
+ const currentUserId = useUserId();
+ const item = useChannelRailItemState(() => props.channel.id);
+
+ return (
+ <ChannelRailItemContextMenu
+ channel={props.channel}
+ class="block w-full"
+ extraItems={<ChannelLabelMenuItems channel={props.channel} />}
+ >
+ <ConversationCard
+ id={item().domId}
+ class="border-b border-edge-muted"
+ channel={props.channel}
+ senderId={props.channel.latestRootMessage?.senderId}
+ mentionedCurrentUser={channelMentionsUser(
+ props.channel,
+ currentUserId()
+ )}
+ unread={item().unread}
+ muted={item().muted}
+ callStatus={item().callStatus}
+ incomingCallId={item().incomingCallId}
+ selected={item().selected}
+ focused={item().focused}
+ onActivate={(event) =>
+ rail.activateRow(rowKeyForChannel(props.channel.id), event)
+ }
+ onPress={(event) =>
+ rail.prefetchRow(rowKeyForChannel(props.channel.id), event)
+ }
+ />
+ </ChannelRailItemContextMenu>
+ );
+}
+
+export function ExpandedRecents() {
+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
+ createScrollTopFade(scrollRoot);
+ const scope = useChannelRailScopeState(() => 'recents');
+ const pagination = useChannelRailVirtualizer(() => 'recents');
+ const forceEmptyState = useDebugSetting(
+ DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES
+ );
+
+ return (
+ <Switch>
+ <Match
+ when={
+ !forceEmptyState() &&
+ scope().source.isLoading() &&
+ scope().items.length === 0
+ }
+ >
+ <RailListLoading />
+ </Match>
+ <Match
+ when={
+ !forceEmptyState() &&
+ scope().source.error() &&
+ scope().items.length === 0
+ }
+ >
+ <RailListError retry={scope().source.refresh} />
+ </Match>
+ <Match when={forceEmptyState() || scope().items.length === 0}>
+ <ChannelsEmptyState scope="recents" topAligned />
+ </Match>
+ <Match when={true}>
+ <div
+ ref={setScrollRoot}
+ class="scrollbar-hidden size-full min-h-0 overflow-y-auto"
+ aria-busy={scope().source.isLoadingMore()}
+ >
+ <Virtualizer
+ ref={pagination.registerVirtualizer}
+ data={scope().items}
+ scrollRef={scrollRoot()}
+ itemSize={CONVERSATION_CARD_HEIGHT}
+ bufferSize={360}
+ keepMounted={scope().keepMounted}
+ onScroll={pagination.loadMoreNearEnd}
+ >
+ {(channel) => <RecentConversationCard channel={channel} />}
+ </Virtualizer>
+ <Show when={scope().source.isLoadingMore()}>
+ <RailListLoadingMore variant="recent" />
+ </Show>
+ <Show
+ when={scope().source.error() && !scope().source.isLoadingMore()}
+ >
+ <RailListError retry={scope().source.refresh} compact />
+ </Show>
+ </div>
+ </Match>
+ </Switch>
+ );
+}
+
+export function ExpandedThreads() {
+ const rail = useChannelsRail();
+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
+ const scope = useChannelRailScopeState(() => 'threads');
+ const pagination = useChannelRailVirtualizer(() => 'threads');
+ const allThreadsDomId = () => domIdForRow(rail.railId, ALL_THREADS_ROW_ID);
+ const allThreadsSelected = () => rail.threadsChannelId() === undefined;
+ const allThreadsFocused = () => rail.list.focus.key() === ALL_THREADS_ROW_ID;
+ const registerScrollRef = (element: HTMLDivElement) => {
+ setScrollRoot(element);
+ rail.registerScrollRef('threads', element);
+ };
+
+ return (
+ <ViewSidebar.Content class="h-full overflow-hidden">
+ <ViewSidebar.Nav aria-label="Thread filters" class="shrink-0">
+ <ViewSidebar.Item
+ as="div"
+ id={allThreadsDomId()}
+ role="treeitem"
+ tabIndex={-1}
+ class={cn(
+ !allThreadsSelected() && allThreadsFocused() && 'bg-hover text-ink'
+ )}
+ active={allThreadsSelected()}
+ aria-current={allThreadsSelected() ? 'page' : undefined}
+ onClick={(event) => {
+ if (!isPrimaryMouseDown(event)) return;
+ rail.activateRow(ALL_THREADS_ROW_ID, event);
+ }}
+ >
+ <ViewSidebar.Icon>
+ <ChatsCircleIcon class="size-4" />
+ </ViewSidebar.Icon>
+ <span class="min-w-0 flex-1 truncate">All threads</span>
+ </ViewSidebar.Item>
+ </ViewSidebar.Nav>
+ <CollapsibleSection.Root open sizing="fill">
+ <CollapsibleSection.Header focused={false} focusWithin={false}>
+ <span class="flex h-full min-w-0 flex-1 items-center px-2">
+ <span class="min-w-0 truncate">Conversations</span>
+ </span>
+ <div data-section-action="" class="flex items-center gap-0.5">
+ <ChannelSortDropdown group="threads" label="Conversations" />
+ <Show when={isTouchDevice()}>
+ <ConversationsCreateMenu />
+ </Show>
+ </div>
+ </CollapsibleSection.Header>
+ <CollapsibleSection.Content
+ open
+ contentRef={registerScrollRef}
+ class="flex min-h-0 flex-col gap-0.5"
+ >
+ <Switch>
+ <Match
+ when={scope().source.isLoading() && scope().items.length === 0}
+ >
+ <RailListLoading />
+ </Match>
+ <Match when={scope().source.error() && scope().items.length === 0}>
+ <RailListError retry={scope().source.refresh} />
+ </Match>
+ <Match when={scope().items.length > 0}>
+ <Virtualizer
+ ref={pagination.registerVirtualizer}
+ data={scope().items}
+ scrollRef={scrollRoot()}
+ itemSize={34}
+ bufferSize={240}
+ keepMounted={scope().keepMounted}
+ onScroll={pagination.loadMoreNearEnd}
+ >
+ {(channel) => (
+ <div class="pb-0.5">
+ <ChannelOption channel={channel} />
+ </div>
+ )}
+ </Virtualizer>
+ <Show when={scope().source.isLoadingMore()}>
+ <RailListLoadingMore variant="channel" />
+ </Show>
+ <Show
+ when={scope().source.error() && !scope().source.isLoadingMore()}
+ >
+ <RailListError retry={scope().source.refresh} compact />
+ </Show>
+ </Match>
+ <Match when={true}>
+ <div class="px-2 py-2 text-xs text-ink-extra-muted">
+ No conversations
+ </div>
+ </Match>
+ </Switch>
+ </CollapsibleSection.Content>
+ </CollapsibleSection.Root>
+ </ViewSidebar.Content>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelOption.tsx b/apps/web/src/features/channels-view/components/rail/ChannelOption.tsx
new file mode 100644
index 0000000000..2db397621a
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/ChannelOption.tsx
@@ -0,0 +1,232 @@
+import { ViewSidebar } from '@app/components/view-shell';
+import { ChannelMutedIndicator } from '@channel/components/ChannelMutedIndicator';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { type ChannelEntity, Entity } from '@entity';
+import {
+ createDraggable,
+ createDroppable,
+ useDragDropContext,
+} from '@thisbeyond/solid-dnd';
+import { cn, Tooltip } from '@ui';
+import { tourTarget } from '@ui/components/Tour';
+import { Show } from 'solid-js';
+import { canLabelChannel } from '../../core/channel-label-eligibility';
+import { CHANNELS_TOUR } from '../../tour';
+import { formatDetailedTimestamp } from '../../utils';
+import {
+ ChannelAvatar,
+ ChannelCallIndicator,
+ ChannelRailItemContextMenu,
+ IncomingCallActions,
+ isPrimaryMouseDown,
+} from './ChannelRailItems';
+import {
+ type ChannelLabelDragData,
+ type ChannelLabelDropData,
+ type ChannelRailRow,
+ rowKeyForChannel,
+ useChannelsRail,
+} from './ChannelsRailContext';
+import { useChannelRailItemState } from './hooks/useChannelRailState';
+import { ChannelLabelMenuItems } from './next/ChannelLabelRows';
+
+/**
+ * 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 draggable = createDraggable(
+ `${rail.railId}:channel-label:drag:${props.rowId}`,
+ {
+ dragType: 'channel-label',
+ dndScope: rail.railId,
+ channelId: props.channel.id,
+ get labelId() {
+ const labelId = props.labelId();
+
+ if (labelId !== undefined) {
+ return 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 };
+}
+
+export function ChannelOption(props: {
+ channel: ChannelEntity;
+ /** The list row this option stands for; defaults to the channel's own row. */
+ rowId?: ChannelRailRow['id'];
+ /** Containing section for drag-and-drop targets. */
+ labelId?: string;
+ /** Make a team-channel row draggable between labels (Team 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() || !canLabelChannel(props.channel),
+ })
+ : 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 (
+ <div
+ ref={(element) => {
+ dnd?.draggable.ref(element);
+ dnd?.droppable.ref(element);
+ }}
+ {...(canLabelChannel(props.channel) ? dnd?.draggable.dragActivators : {})}
+ onPointerDown={(event) => {
+ didDrag = false;
+ rail.prefetchRow(rowId(), event);
+ }}
+ class={cn(
+ 'min-w-0',
+ !rail.sectionsEnabled() &&
+ 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',
+ props.draggable && 'pb-0.5',
+ 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.Item
+ as="div"
+ ref={tourTarget(CHANNELS_TOUR.conversation)}
+ 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 when={item().unread}>
+ <span
+ aria-label="Unread"
+ class="size-2 shrink-0 rounded-full bg-accent"
+ />
+ </Show>
+ <Show when={!item().incomingCallId && timestamp()}>
+ {(value) => (
+ <span class="relative hidden shrink-0 group-hover/channel-option:block touch:hidden">
+ <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"
+ >
+ <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>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelSortDropdown.tsx b/apps/web/src/features/channels-view/components/rail/ChannelSortDropdown.tsx
new file mode 100644
index 0000000000..7acd6d4583
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/ChannelSortDropdown.tsx
@@ -0,0 +1,60 @@
+import { ViewSidebar } from '@app/components/view-shell';
+import CheckIcon from '@icon/system/regular/check.svg';
+import SortIcon from '@icon/system/regular/sort-ascending.svg';
+import { Dropdown } from '@ui';
+import { For } from 'solid-js';
+import type { ChannelListSort, ChannelsSortGroup } from '../../types';
+import { useChannelsRail } from './ChannelsRailContext';
+
+const CHANNEL_SORT_OPTIONS: {
+ value: ChannelListSort;
+ label: string;
+}[] = [
+ { value: 'viewed_at', label: 'Last viewed' },
+ { value: 'updated_at', label: 'Last updated' },
+ { value: 'created_at', label: 'Date created' },
+];
+
+export function ChannelSortDropdown(props: {
+ group: ChannelsSortGroup;
+ label: string;
+}) {
+ const rail = useChannelsRail();
+ const setSort = (value: string) => {
+ const option = CHANNEL_SORT_OPTIONS.find((item) => item.value === value);
+ if (option) rail.setSortBy(props.group, option.value);
+ };
+
+ return (
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ aria-label={`Sort ${props.label.toLowerCase()}`}
+ tooltip={`Sort ${props.label.toLowerCase()}`}
+ as={ViewSidebar.Control}
+ variant="ghost"
+ size="icon-sm"
+ >
+ <SortIcon class="size-3.5" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="min-w-40">
+ <Dropdown.Group>
+ <Dropdown.RadioGroup
+ value={rail.sortBy(props.group)}
+ onChange={setSort}
+ >
+ <For each={CHANNEL_SORT_OPTIONS}>
+ {(option) => (
+ <Dropdown.RadioItem closeOnSelect value={option.value}>
+ <span class="flex-1">{option.label}</span>
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ )}
+ </For>
+ </Dropdown.RadioGroup>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx
index 72c1815c72..85e5d9ec3b 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.test.tsx
@@ -1,6 +1,9 @@
+import type { ListScrollHandle } from '@app/components/list';
import type { ChannelPreviewSelection } from '@app/features/next-soup/utils';
import type { ChannelEntity } from '@entity/types/entity';
import type { WithNotification } from '@entity/types/notification';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
import {
cleanup,
fireEvent,
@@ -8,13 +11,19 @@ import {
screen,
waitFor,
} from '@solidjs/testing-library';
+import { getOwner, onCleanup } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ChannelsSources } from '../../queries';
import type { ChannelRailRow } from './ChannelsRailContext';
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => mocks.userId,
+}));
const mocks = vi.hoisted(() => ({
fetchChannel: vi.fn<(id: string) => Promise<ChannelEntity>>(),
favoriteId: undefined as string | undefined,
+ fetchGroupIds:
+ vi.fn<typeof import('../../queries')['fetchChannelGroupIds']>(),
hydrate:
vi.fn<
(
@@ -28,15 +37,30 @@ const mocks = vi.hoisted(() => ({
openSplit: vi.fn(async () => {}),
select: vi.fn((_channel: ChannelPreviewSelection) => true),
selected: undefined as ChannelPreviewSelection | undefined,
- source: {},
+ userId: 'viewer',
+ source: {
+ muteEntity:
+ vi.fn<(entity: { type: string; id: string }) => Promise<void>>(),
+ unmuteEntity:
+ vi.fn<(entity: { type: string; id: string }) => Promise<void>>(),
+ },
+ snooze: vi.fn(),
+ success: vi.fn(),
activate: (_event: MouseEvent) => {},
row: undefined as ChannelEntity | undefined,
failure: vi.fn(),
prefetch: vi.fn(),
tab: 'browse' as 'browse' | 'threads',
+ scrollBrowse: vi.fn(),
+ scroll: (_index: number) => {},
+ focusedRow: undefined as ChannelRailRow | undefined,
+ listRows: undefined as ChannelRailRow[] | undefined,
+ focusSet: vi.fn(),
+ hotkeys: new Map<string, () => unknown>(),
}));
vi.mock('@app/components/list', () => ({
createListController: (options: {
+ items: () => ChannelRailRow[];
onActivate: (event: {
item: ChannelRailRow;
metadata: { event: MouseEvent };
@@ -65,10 +89,24 @@ vi.mock('@app/components/list', () => ({
},
metadata: { event },
});
- return {};
+ const items = () => mocks.listRows ?? options.items();
+
+ return {
+ items: { at: (index: number) => items()[index], all: items },
+ focus: {
+ item: () => mocks.focusedRow,
+ set: (id: string, options: { reason: string }) => {
+ mocks.focusSet(id, options);
+ const index = items().findIndex((row) => row.id === id);
+ return index < 0 ? undefined : { index };
+ },
+ },
+ };
},
listOwnedSlotName: (name: string) => name,
- useListInteractions: vi.fn(),
+ useListInteractions: (options: { scrollHandle: () => ListScrollHandle }) => {
+ mocks.scroll = (index) => options.scrollHandle().scrollToIndex(index);
+ },
}));
vi.mock('@app/components/view-shell', () => ({
useViewControlHotkeys: vi.fn(),
@@ -116,7 +154,7 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({
withSplitPanelOwner: (_name: string, run: () => unknown) => run(),
}));
vi.mock('@core/component/Toast/Toast', () => ({
- toast: { failure: mocks.failure },
+ toast: { failure: mocks.failure, success: mocks.success },
}));
vi.mock('@core/constant/featureFlags', () => ({ enableChannelTags: {} }));
vi.mock('@channel/queries/prefetch-channel-target', () => ({
@@ -124,7 +162,13 @@ vi.mock('@channel/queries/prefetch-channel-target', () => ({
}));
vi.mock('@core/hotkey/hotkeys', () => ({
createHotkeyGroup: () => ({ dispose: vi.fn() }),
- registerHotkey: () => ({ withGroup: vi.fn() }),
+ registerHotkey: (options: {
+ hotkey: string;
+ keyDownHandler: () => unknown;
+ }) => {
+ mocks.hotkeys.set(options.hotkey, options.keyDownHandler);
+ return { withGroup: vi.fn() };
+ },
}));
vi.mock('@entity', () => ({
isChannelEntity: (entity: { type: string }) => entity.type === 'channel',
@@ -136,6 +180,9 @@ vi.mock('@entity/utils/notification', () => ({
vi.mock('@notifications/notification-helpers', () => ({
ensureNotificationSourceLoaded: vi.fn(),
}));
+vi.mock('@notifications/SnoozeNotificationsDialog', () => ({
+ openSnoozeNotifications: mocks.snooze,
+}));
vi.mock('@queries/channel/notification-selection', () => ({
hydrateChannelNotificationSelection: mocks.hydrate,
}));
@@ -165,14 +212,17 @@ vi.mock('../../channels-view-context', () => ({
tab: 'browse',
expandedGroups: { channels: true, direct_messages: true },
collapsedLabels: [],
+ sectionPreferences: {},
},
tab: () => mocks.tab,
+ sectionsEnabled: () => true,
threadsEnabled: () => false,
selectedChannel: () => mocks.selected,
setSelectedChannel: mocks.select,
}),
}));
vi.mock('../../queries', () => ({
+ fetchChannelGroupIds: mocks.fetchGroupIds,
deduplicateChannels: (collections: ChannelEntity[][]) => [
...new Map(
collections.flat().map((channel) => [channel.id, channel])
@@ -182,17 +232,35 @@ vi.mock('../../queries', () => ({
// What the real helper answers for the disabled lookup above.
resolveReferencedChannels: (previous: ChannelEntity[]) => previous,
}));
-vi.mock('./ChannelLabelNameDialog', () => ({ promptLabelName: vi.fn() }));
+vi.mock('@queries/channel/by-ids', () => ({
+ useChannelsByIdsQuery: () => ({ isEnabled: false }),
+ useCachedChannelsByIds: () => ({
+ channels: () => [],
+ pendingIds: () => new Set<string>(),
+ failedIds: () => new Set<string>(),
+ error: () => undefined,
+ isLoading: () => false,
+ retry: async () => {},
+ }),
+}));
+vi.mock('./next/SectionDialog', () => ({ promptSection: vi.fn() }));
+vi.mock('./ChannelLabelNameDialog', () => ({
+ promptLabelName: vi.fn(),
+}));
vi.mock('./SmartTagDialog', () => ({ promptSmartTag: vi.fn() }));
+vi.mock('./ExpandedChannelsRail', () => ({ ExpandedChannelsRail: () => null }));
vi.mock('./hooks/useChannelCalls', () => ({ useChannelCalls: () => ({}) }));
vi.mock('./hooks/useChannelRailActivity', () => ({
- useChannelRailActivity: () => ({}),
+ useChannelRailActivity: () => ({ unreadChannelIds: () => new Set<string>() }),
}));
-vi.mock('./ExpandedChannelsRail', async () => {
+vi.mock('./next/ExpandedChannelsRail', async () => {
const { useChannelsRail } = await import('./ChannelsRailContext');
return {
ExpandedChannelsRail: () => {
const rail = useChannelsRail();
+ onCleanup(
+ rail.registerBrowseScrollHandle({ scrollToIndex: mocks.scrollBrowse })
+ );
return (
<button
onPointerDown={(event) => rail.prefetchRow('channel:one', event)}
@@ -206,6 +274,7 @@ vi.mock('./ExpandedChannelsRail', async () => {
});
import { ChannelsRail } from './ChannelsRail';
+import { useChannelSectionNotifications } from './hooks/useChannelSectionNotifications';
const channel: ChannelEntity = {
id: 'one',
@@ -254,6 +323,14 @@ const mount = () =>
beforeEach(() => {
vi.clearAllMocks();
+ mocks.focusedRow = undefined;
+ mocks.listRows = undefined;
+ mocks.hotkeys.clear();
+ mocks.userId = 'viewer';
+ mocks.source.muteEntity.mockResolvedValue(undefined);
+ mocks.source.unmuteEntity.mockResolvedValue(undefined);
+ mocks.fetchGroupIds.mockReset();
+ mocks.fetchGroupIds.mockResolvedValue(['one', 'unloaded']);
mocks.row = channel;
mocks.favoriteId = undefined;
mocks.tab = 'browse';
@@ -263,6 +340,69 @@ beforeEach(() => {
});
afterEach(cleanup);
+it('delegates keyboard scrolling to the sectioned renderer instead of global indexes', () => {
+ mount();
+ mocks.scroll(0);
+ expect(mocks.scrollBrowse).toHaveBeenCalledExactlyOnceWith(0, undefined);
+});
+
+describe('section heading navigation', () => {
+ it.each([
+ ['label:first', ']', 'label:second'],
+ ['label:second', '[', 'label:first'],
+ ['section:team_channels', ']', 'section:channels'],
+ ['channel:one:label:first', ']', 'label:second'],
+ ])('jumps from %s with %s to %s', (from, hotkey, to) => {
+ const first: ChannelLabel = {
+ id: 'first',
+ name: 'First',
+ channelIds: ['one'],
+ channelCount: 1,
+ sortOrder: 0,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ };
+ mocks.listRows = [
+ { kind: 'section', id: 'section:team_channels', group: 'team_channels' },
+ { kind: 'section', id: 'section:channels', group: 'channels' },
+ {
+ kind: 'label',
+ id: 'label:first',
+ group: 'team_channels',
+ localIndex: 2,
+ label: first,
+ },
+ {
+ kind: 'conversation',
+ id: 'channel:one:label:first',
+ group: 'team_channels',
+ scope: 'team_channels',
+ localIndex: 3,
+ channel,
+ labelId: 'first',
+ },
+ {
+ kind: 'label',
+ id: 'label:second',
+ group: 'team_channels',
+ localIndex: 4,
+ label: { ...first, id: 'second', name: 'Second' },
+ },
+ ];
+ mocks.focusedRow = mocks.listRows.find((row) => row.id === from);
+ mount();
+
+ expect(mocks.hotkeys.get(hotkey)?.()).toBe(true);
+ expect(mocks.focusSet).toHaveBeenCalledExactlyOnceWith(to, {
+ reason: 'keyboard',
+ });
+ expect(mocks.scrollBrowse).toHaveBeenCalledExactlyOnceWith(
+ mocks.listRows.findIndex((row) => row.id === to),
+ undefined
+ );
+ });
+});
+
describe('explicit channel activation read marking', () => {
it('resolves an uncached favorite before opening a split with top-level read marking', async () => {
mocks.favoriteId = 'uncached';
@@ -555,3 +695,264 @@ describe('channel row presses', () => {
expect(mocks.prefetch).not.toHaveBeenCalled();
});
});
+
+describe('section notification actions', () => {
+ const label: ChannelLabel = {
+ id: 'section',
+ name: 'Section',
+ channelIds: ['one', 'unloaded', 'one'],
+ channelCount: 2,
+ sortOrder: 0,
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ };
+
+ const mountActions = (
+ labels: () => ChannelLabel[] = () => [label],
+ enabled: () => boolean = () => true,
+ favorites: () => Favorite[] = () => []
+ ) => {
+ let actions!: ReturnType<typeof useChannelSectionNotifications>;
+
+ render(() => {
+ const owner = getOwner();
+ actions = useChannelSectionNotifications({
+ enabled,
+ labelsAvailable: enabled,
+ labels,
+ favorites,
+ dialogOwner: () => owner,
+ });
+ return null;
+ });
+
+ return actions;
+ };
+
+ it('uses the complete current membership instead of loaded rows or a stale snapshot', async () => {
+ let current = label;
+ const actions = mountActions(() => [current]);
+
+ await actions.muteSection('label:section', true);
+
+ expect(mocks.source.muteEntity.mock.calls).toEqual([
+ [{ type: 'channel', id: 'one' }],
+ [{ type: 'channel', id: 'unloaded' }],
+ ]);
+
+ current = { ...label, channelIds: ['new-member'] };
+ await actions.snoozeSection('label:section');
+
+ expect(mocks.snooze).toHaveBeenCalledWith(
+ [{ item_type: 'channel', item_id: 'new-member' }],
+ { owner: expect.anything() }
+ );
+ });
+
+ it('keeps successful writes when one member fails and blocks duplicate actions until settled', async () => {
+ let finish!: () => void;
+ mocks.source.muteEntity
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ })
+ );
+ const actions = mountActions();
+
+ const pending = actions.muteSection('label:section', true);
+ expect(actions.sectionNotificationsDisabled('label:section')).toBe(true);
+
+ await actions.muteSection('label:section', false);
+ await actions.snoozeSection('label:section');
+
+ expect(mocks.source.muteEntity).toHaveBeenCalledTimes(2);
+ expect(mocks.source.unmuteEntity).not.toHaveBeenCalled();
+ expect(mocks.snooze).not.toHaveBeenCalled();
+
+ finish();
+ await pending;
+
+ expect(actions.sectionNotificationsDisabled('label:section')).toBe(false);
+ expect(mocks.failure).toHaveBeenCalledExactlyOnceWith(
+ 'Muted 1 of 2 items; 1 failed'
+ );
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+
+ it('unmutes all current members without changing section membership', async () => {
+ const actions = mountActions();
+ await actions.muteSection('label:section', false);
+
+ expect(mocks.source.unmuteEntity.mock.calls).toEqual([
+ [{ type: 'channel', id: 'one' }],
+ [{ type: 'channel', id: 'unloaded' }],
+ ]);
+ expect(label.channelIds).toEqual(['one', 'unloaded', 'one']);
+ });
+
+ it('refuses disabled or deleted sections', async () => {
+ let enabled = false;
+ let current = [label];
+ const actions = mountActions(
+ () => current,
+ () => enabled
+ );
+
+ await actions.muteSection('label:section', true);
+ await actions.snoozeSection('label:section');
+
+ enabled = true;
+ current = [];
+
+ await actions.muteSection('label:section', true);
+ await actions.snoozeSection('label:section');
+
+ expect(mocks.source.muteEntity).not.toHaveBeenCalled();
+ expect(mocks.snooze).not.toHaveBeenCalled();
+ });
+
+ it('does not block a new account or clear its pending action when an older batch finishes', async () => {
+ let finishFirst!: () => void;
+ let finishSecond!: () => void;
+ mocks.source.muteEntity
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishFirst = resolve;
+ })
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ finishSecond = resolve;
+ })
+ );
+
+ let current = { ...label, channelIds: ['one'] };
+ const actions = mountActions(() => [current]);
+ const first = actions.muteSection('label:section', true);
+
+ mocks.userId = 'another-viewer';
+ current = { ...label, channelIds: ['two'] };
+
+ expect(actions.sectionNotificationsDisabled('label:section')).toBe(false);
+ const second = actions.muteSection('label:section', true);
+ expect(mocks.source.muteEntity.mock.calls).toEqual([
+ [{ type: 'channel', id: 'one' }],
+ [{ type: 'channel', id: 'two' }],
+ ]);
+
+ finishFirst();
+ await first;
+
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.failure).not.toHaveBeenCalled();
+ expect(actions.sectionNotificationsDisabled('label:section')).toBe(true);
+
+ finishSecond();
+ await second;
+
+ expect(actions.sectionNotificationsDisabled('label:section')).toBe(false);
+ expect(mocks.success).toHaveBeenCalledOnce();
+ });
+
+ it('targets channel favorites without loading rows or touching other favorite types', async () => {
+ const favorites: Favorite[] = [
+ {
+ entityType: 'channel',
+ entityId: 'unloaded',
+ createdAt: '2026-01-01',
+ sortOrder: 0,
+ },
+ {
+ entityType: 'document',
+ entityId: 'document',
+ createdAt: '2026-01-01',
+ sortOrder: 1,
+ },
+ ];
+ const actions = mountActions(
+ () => [],
+ () => true,
+ () => favorites
+ );
+
+ await actions.muteSection('favorites', true);
+ await actions.snoozeSection('favorites');
+
+ expect(mocks.source.muteEntity).toHaveBeenCalledExactlyOnceWith({
+ type: 'channel',
+ id: 'unloaded',
+ });
+ expect(mocks.snooze).toHaveBeenCalledWith(
+ [{ item_type: 'channel', item_id: 'unloaded' }],
+ { owner: expect.anything() }
+ );
+ expect(mocks.fetchGroupIds).not.toHaveBeenCalled();
+ });
+
+ it.each(['channels', 'team_channels', 'direct_messages'] as const)(
+ 'resolves complete %s membership before applying notification updates',
+ async (section) => {
+ const actions = mountActions();
+ await actions.muteSection(section, false);
+
+ expect(mocks.fetchGroupIds).toHaveBeenCalledExactlyOnceWith(
+ section,
+ section === 'direct_messages' ? [] : label.channelIds,
+ expect.any(AbortSignal)
+ );
+ expect(mocks.source.unmuteEntity.mock.calls).toEqual([
+ [{ type: 'channel', id: 'one' }],
+ [{ type: 'channel', id: 'unloaded' }],
+ ]);
+ }
+ );
+
+ it.each(['account', 'unmount'] as const)(
+ 'discards membership resolved after %s changes',
+ async (change) => {
+ let resolve!: (ids: string[]) => void;
+ mocks.fetchGroupIds.mockImplementationOnce(
+ () =>
+ new Promise((done) => {
+ resolve = done;
+ })
+ );
+ const actions = mountActions();
+ const pending = actions.snoozeSection('team_channels');
+ expect(actions.sectionNotificationsDisabled('favorites')).toBe(true);
+
+ if (change === 'account') {
+ mocks.userId = 'another-viewer';
+ } else {
+ cleanup();
+ }
+
+ resolve(['unloaded']);
+ await pending;
+
+ expect(mocks.snooze).not.toHaveBeenCalled();
+ expect(mocks.source.muteEntity).not.toHaveBeenCalled();
+ }
+ );
+
+ it('keeps the section retryable after membership lookup fails without applying partial updates', async () => {
+ const error = new Error('offline');
+ mocks.fetchGroupIds.mockRejectedValueOnce(error);
+ const actions = mountActions();
+
+ await expect(actions.muteSection('team_channels', true)).rejects.toThrow(
+ error
+ );
+
+ expect(actions.sectionNotificationsDisabled('team_channels')).toBe(false);
+ expect(mocks.source.muteEntity).not.toHaveBeenCalled();
+ expect(mocks.failure).toHaveBeenCalledOnce();
+
+ await actions.muteSection('team_channels', true);
+ expect(mocks.source.muteEntity).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
index 6d9ee83d7d..4ca1070505 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRail.tsx
@@ -18,6 +18,7 @@ import {
} from '@app/features/next-soup/utils';
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { t } from '@app/lib/i18n';
import { favoriteSplitContent } from '@app/util/favorites';
import { prefetchLatestChannelMessages } from '@channel/queries/prefetch-channel-target';
import {
@@ -31,25 +32,19 @@ import {
} from '@components/app/split-layout/layoutUtils';
import { toast } from '@core/component/Toast/Toast';
import { enableChannelTags } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
+
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { thrownResultErrorHasCode } from '@core/util/result';
import type { ChannelEntity, WithNotification } from '@entity';
-import { notificationIsRead } from '@entity/utils/notification';
-import { ensureNotificationSourceLoaded } from '@notifications/notification-helpers';
+import { useCachedChannelsByIds } from '@queries/channel/by-ids';
import { hydrateChannelNotificationSelection } from '@queries/channel/notification-selection';
import { fetchChannelSelectionById } from '@queries/channel/selection-by-id';
-import {
- useChannelLabelsQuery,
- useCreateChannelLabelMutation,
- useDeleteChannelLabelMutation,
- useRenameChannelLabelMutation,
- useSetChannelLabelMutation,
-} from '@queries/channel-labels/channel-labels';
+import { useChannelLabelsQuery } from '@queries/channel-labels/channel-labels';
import { useFavoritesData } from '@queries/favorites/favorites';
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,
@@ -57,6 +52,7 @@ import {
createUniqueId,
getOwner,
onCleanup,
+ Show,
startTransition,
} from 'solid-js';
import type { VirtualizerHandle } from 'virtua/solid';
@@ -74,15 +70,16 @@ import {
useChannelsByIdsQuery,
} from '../../queries';
import type {
+ ChannelSectionKey,
+ ChannelSectionPreferences,
ChannelsQueryScope,
ChannelsRailSection,
ChannelsTab,
} from '../../types';
import {
- buildChannelRailRows,
- buildChannelSectionRows,
+ buildChannelRailRows as buildOriginalChannelRailRows,
+ buildChannelSectionRows as buildOriginalChannelSectionRows,
} from './build-channel-rail-rows';
-import { promptLabelName } from './ChannelLabelNameDialog';
import {
type ChannelLabelDragData,
type ChannelLabelDropData,
@@ -98,20 +95,21 @@ import {
rowKeyForSection,
} from './ChannelsRailContext';
import { ExpandedChannelsRail } from './ExpandedChannelsRail';
-import { promptSmartTag } from './SmartTagDialog';
+import {
+ buildChannelRailRows,
+ buildChannelSectionRows,
+ getChannelRailPaginationScope,
+} from './next/build-channel-rail-rows';
+import { ExpandedChannelsRail as NextChannelsRail } from './next/ExpandedChannelsRail';
-export { buildChannelRailRows } from './build-channel-rail-rows';
+export { buildChannelRailRows } from './next/build-channel-rail-rows';
import { fireAndForget } from '@core/util/fireAndForget';
import { useChannelCalls } from './hooks/useChannelCalls';
+import { useChannelLabelActions } from './hooks/useChannelLabelActions';
import { useChannelRailActivity } from './hooks/useChannelRailActivity';
+import { useChannelSectionNotifications } from './hooks/useChannelSectionNotifications';
-const CHANNEL_RAIL_SECTIONS: ChannelsRailSection[] = [
- 'favorites',
- 'team_channels',
- 'channels',
- 'direct_messages',
-];
const LABEL_KEY_PREFIX = 'label:';
const BROWSE_QUERY_SCOPES = [
'team_channels',
@@ -136,24 +134,31 @@ export type ChannelsRailProps = {
export function ChannelsRail(props: ChannelsRailProps) {
const channelTagsFlag = useFeatureFlag(enableChannelTags);
const channelTagsEnabled = createMemo(() => channelTagsFlag().enabled);
- // The dialog manager closes entries when their owner is disposed. Give
- // label dialogs an owner that is cleaned up when the rollout turns off.
- const labelDialogOwner = createMemo(() =>
- channelTagsEnabled() ? getOwner() : undefined
- );
const {
state,
+ sectionsEnabled,
setGroupOpen,
setLabelOpen,
selectedChannel,
setSelectedChannel,
setSortBy,
+ setSectionPreferences,
setTab,
tab,
threadsEnabled,
threadsChannelId,
setThreadsChannelId,
} = useChannelsView();
+ const userId = useUserId();
+
+ // Dispose label dialogs when the account or rollout switches their owning UI.
+ // Memo recomputation runs these cleanups even when the owner identity is unchanged.
+ const labelDialogOwner = createMemo(() => {
+ userId();
+ sectionsEnabled();
+ channelTagsEnabled();
+ return getOwner();
+ });
const panel = useSplitPanelOrThrow();
const layout = useSplitLayout();
@@ -286,6 +291,8 @@ export function ChannelsRail(props: ChannelsRailProps) {
const [virtualizers, setVirtualizers] = createSignal<
Partial<Record<ChannelsSourceScope, VirtualizerHandle>>
>({});
+ const [browseScrollHandle, setBrowseScrollHandle] =
+ createSignal<ListScrollHandle>();
const searchQuery = () => props.searchQuery;
const setSearchQuery = (query: string) => props.onSearchQueryChange(query);
@@ -334,31 +341,55 @@ export function ChannelsRail(props: ChannelsRailProps) {
const searchError = () => props.sources.search.error();
const retrySearch = () => props.sources.search.refresh();
- // Shared or private labels; channel membership is always viewer-relative.
const labelsQuery = useChannelLabelsQuery();
- const labels = createMemo<readonly ChannelLabel[]>(() =>
- resolveChannelLabelMemberships(
- channelTagsEnabled() && labelsQuery.isSuccess
- ? labelsQuery.data.labels
- : [],
- channels()
- )
+ const personalLabelsQuery = useChannelLabelsQuery(
+ 'personal',
+ sectionsEnabled
);
- const labelsAvailable = () => channelTagsEnabled() && labelsQuery.isSuccess;
+ const sharedLabels = () =>
+ !labelsQuery.isPending && Boolean(labelsQuery.data?.teamId);
+ const labels = createMemo<readonly ChannelLabel[]>(() => {
+ if (!channelTagsEnabled()) return [];
+ if (!sectionsEnabled()) {
+ return !labelsQuery.isPending
+ ? resolveChannelLabelMemberships(
+ labelsQuery.data?.labels ?? [],
+ channels()
+ )
+ : [];
+ }
+ const shared =
+ !labelsQuery.isPending && labelsQuery.data?.teamId
+ ? labelsQuery.data.labels
+ : [];
+ const personal = !personalLabelsQuery.isPending
+ ? (personalLabelsQuery.data?.labels ?? [])
+ : [];
+ return resolveChannelLabelMemberships([...shared, ...personal], channels());
+ });
+ const labelsAvailable = () =>
+ channelTagsEnabled() &&
+ !labelsQuery.isPending &&
+ Boolean(labelsQuery.data) &&
+ (!sectionsEnabled() ||
+ (!personalLabelsQuery.isPending && Boolean(personalLabelsQuery.data)));
const labelsUnavailableReason = () => {
- if (labelsQuery.isSuccess) return '';
- if (labelsQuery.isPending) return 'Loading labels…';
- const error = labelsQuery.error;
+ if (labelsAvailable()) return '';
+ if (
+ labelsQuery.isPending ||
+ (sectionsEnabled() && personalLabelsQuery.isPending)
+ )
+ return t('channelSections.loading');
+ const error =
+ labelsQuery.error ??
+ (sectionsEnabled() ? personalLabelsQuery.error : undefined);
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 t('channelSections.noAccess');
}
- return 'Channel labels are unavailable right now.';
+ return t('channelSections.unavailable');
};
const favorites = createMemo(() => favoritesData()?.favorites ?? []);
@@ -368,9 +399,8 @@ export function ChannelsRail(props: ChannelsRailProps) {
.map((favorite) => favorite.entityId)
);
- // A labelled or favorited channel has a row before the paginated Team
- // channels source reaches it, so fetch the ones the sources have not loaded: a label
- // needs them to list its channels, a favorite row to act on its channel.
+ // Sections and favorites can reference channels outside the loaded pages.
+ // Resolve their records independently without exhausting the main lists.
const referencedChannelIds = createMemo(() => [
...new Set([
...labels().flatMap((label) => label.channelIds),
@@ -381,19 +411,21 @@ export function ChannelsRail(props: ChannelsRailProps) {
const loaded = new Set(channels().map((channel) => channel.id));
return referencedChannelIds().filter((id) => !loaded.has(id));
});
- const referencedChannelsQuery = useChannelsByIdsQuery(missingChannelIds);
+ const referencedChannelsQuery = useChannelsByIdsQuery(() =>
+ sectionsEnabled() ? [] : missingChannelIds()
+ );
+ const nextReferencedChannels = useCachedChannelsByIds(
+ referencedChannelIds,
+ sectionsEnabled
+ );
const referencedChannels = createMemo<ChannelEntity[]>(
(previous) =>
- resolveReferencedChannels(previous, {
- isEnabled: referencedChannelsQuery.isEnabled,
- isLoading: referencedChannelsQuery.isLoading,
- error: referencedChannelsQuery.error,
- entities: referencedChannelsQuery.data?.entities,
- }),
+ sectionsEnabled()
+ ? nextReferencedChannels.channels()
+ : resolveReferencedChannels(previous, referencedChannelsQuery),
[]
);
- // Only a label puts a fetched channel in a section. A favorited one stays
- // out of the section lists, and so out of their unread counts.
+ // Only a label puts a fetched channel in the channel-section lists.
const labelledChannels = createMemo<ChannelEntity[]>(() => {
if (!channelTagsEnabled()) return [];
const labelled = new Set(labels().flatMap((label) => label.channelIds));
@@ -410,13 +442,26 @@ export function ChannelsRail(props: ChannelsRailProps) {
channelsById().get(channelId) ??
referencedChannels().find((channel) => channel.id === channelId);
- const channelActivity = useChannelRailActivity(allChannels, channelCalls);
+ const activityChannels = createMemo(() => {
+ if (!sectionsEnabled()) return allChannels();
+ return deduplicateChannels([
+ allChannels(),
+ favoriteChannelIds().flatMap((id) => channelById(id) ?? []),
+ ]);
+ });
+ const channelActivity = useChannelRailActivity(
+ activityChannels,
+ channelCalls
+ );
const isLabelOpen = (labelId: string) =>
!state.collapsedLabels.includes(labelId);
- const channelSectionRows = createMemo(() =>
- buildChannelSectionRows({
+ const channelSectionRows = createMemo(() => {
+ const build = sectionsEnabled()
+ ? buildChannelSectionRows
+ : buildOriginalChannelSectionRows;
+ return build({
labels: labels(),
channels: deduplicateChannels([
props.sources.team_channels.items(),
@@ -424,8 +469,8 @@ export function ChannelsRail(props: ChannelsRailProps) {
]),
channelsById: channelsById(),
isLabelOpen,
- })
- );
+ });
+ });
const labelUnreadCount = (label: ChannelLabel) => {
const unread = channelActivity.unreadChannelIds();
@@ -434,6 +479,28 @@ export function ChannelsRail(props: ChannelsRailProps) {
).length;
};
+ const referenceStatuses = createMemo(() => {
+ const statuses: Partial<Record<ChannelSectionKey, 'loading' | 'error'>> =
+ {};
+ if (!sectionsEnabled()) return statuses;
+ const pending = nextReferencedChannels.pendingIds();
+ const failed = nextReferencedChannels.failedIds();
+ const statusFor = (ids: readonly string[]) => {
+ if (ids.some((id) => failed.has(id) && !channelById(id))) return 'error';
+ if (ids.some((id) => pending.has(id) && !channelById(id)))
+ return 'loading';
+ };
+ if (state.expandedGroups.favorites) {
+ statuses.favorites = statusFor(favoriteChannelIds());
+ }
+ for (const label of labels()) {
+ if (isLabelOpen(label.id)) {
+ statuses[`label:${label.id}`] = statusFor(label.channelIds);
+ }
+ }
+ return statuses;
+ });
+
const visibleRows = createMemo(() => {
if (props.searchOpen) {
return searchResults().map(
@@ -447,18 +514,33 @@ export function ChannelsRail(props: ChannelsRailProps) {
);
}
+ const items = {
+ favorites: favorites(),
+ team_channels: props.sources.team_channels.items(),
+ channels: props.sources.channels.items(),
+ direct_messages: props.sources.direct_messages.items(),
+ recents: props.sources.recents.items(),
+ threads: props.sources.threads.items(),
+ };
+ if (!sectionsEnabled()) {
+ return buildOriginalChannelRailRows(
+ tab(),
+ state.expandedGroups,
+ items,
+ channelSectionRows()
+ );
+ }
return buildChannelRailRows(
tab(),
state.expandedGroups,
+ items,
+ channelSectionRows(),
{
- favorites: favorites(),
- team_channels: props.sources.team_channels.items(),
- channels: props.sources.channels.items(),
- direct_messages: props.sources.direct_messages.items(),
- recents: props.sources.recents.items(),
- threads: props.sources.threads.items(),
- },
- channelSectionRows()
+ preferences: state.sectionPreferences,
+ channelById,
+ unreadChannelIds: channelActivity.unreadChannelIds(),
+ referenceStatuses: referenceStatuses(),
+ }
);
});
@@ -468,6 +550,8 @@ export function ChannelsRail(props: ChannelsRailProps) {
items: visibleRows,
getKey: (row) => row.id,
isSelectable: () => false,
+ isNavigable: (row) =>
+ row.kind !== 'status' && row.kind !== 'reference-status',
initialFocusKey: visibleRows().find(
(row) =>
row.kind === 'conversation' &&
@@ -478,6 +562,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
previewAfterNavigation.clear();
const openInNewSplit =
metadata?.newSplit === true || metadata?.event?.shiftKey === true;
+ if (item.kind === 'status' || item.kind === 'reference-status') return;
if (item.kind === 'all-threads') {
setThreadsChannelId(undefined);
@@ -541,6 +626,10 @@ export function ChannelsRail(props: ChannelsRailProps) {
scrollToIndex: (index, options) => {
const row = list.items.at(index);
if (!row) return;
+ if (sectionsEnabled() && !props.searchOpen) {
+ browseScrollHandle()?.scrollToIndex(index, options);
+ return;
+ }
if (row.kind === 'conversation' || row.kind === 'label') {
const virtualizer =
@@ -552,18 +641,23 @@ export function ChannelsRail(props: ChannelsRailProps) {
}
const element = document.getElementById(domIdForRow(listDomId, row.id));
- const scrollRoot = props.searchOpen
- ? listRoot()
- : row.kind === 'favorite'
- ? sectionScrollRoots().favorites
- : row.kind === 'conversation' && row.group
- ? sectionScrollRoots()[row.group]
- : tab() === 'recents'
- ? listRoot()
- : tab() === 'threads'
- ? sectionScrollRoots().threads
- : undefined;
- if (!element || !scrollRoot) return;
+ let scrollRoot: HTMLDivElement | undefined;
+
+ if (props.searchOpen) {
+ scrollRoot = listRoot();
+ } else if (row.kind === 'favorite') {
+ scrollRoot = sectionScrollRoots().favorites;
+ } else if (row.kind === 'conversation' && row.group) {
+ scrollRoot = sectionScrollRoots()[row.group];
+ } else if (tab() === 'recents') {
+ scrollRoot = listRoot();
+ } else if (tab() === 'threads') {
+ scrollRoot = sectionScrollRoots().threads;
+ }
+
+ if (!element || !scrollRoot) {
+ return;
+ }
const elementBounds = element.getBoundingClientRect();
const scrollBounds = scrollRoot.getBoundingClientRect();
@@ -576,8 +670,6 @@ export function ChannelsRail(props: ChannelsRailProps) {
};
const scrollScopeToSelectedOrStart = (scope: ChannelsQueryScope) => {
- // The Team channels section renders label headings between channels, so
- // its indexes come from the rendered rows rather than the source.
const rendered =
scope === 'team_channels'
? channelSectionRows().map((row) =>
@@ -633,42 +725,43 @@ export function ChannelsRail(props: ChannelsRailProps) {
const scrollFavoritesToSelectedOrStart = () => {
const scrollRoot = sectionScrollRoots().favorites;
if (!scrollRoot?.isConnected) return;
-
scrollRoot.scrollTop = 0;
-
const favorite = favorites().find(
(item) =>
item.entityType === 'channel' && item.entityId === selectedChannel()?.id
);
if (!favorite) return;
-
const element = document.getElementById(
domIdForRow(listDomId, rowKeyForFavorite(favorite))
);
if (!element) return;
-
- const elementBounds = element.getBoundingClientRect();
- const scrollBounds = scrollRoot.getBoundingClientRect();
-
- if (elementBounds.bottom > scrollBounds.bottom) {
- scrollRoot.scrollTop += elementBounds.bottom - scrollBounds.bottom;
- }
+ scrollRoot.scrollTop += Math.max(
+ 0,
+ element.getBoundingClientRect().bottom -
+ scrollRoot.getBoundingClientRect().bottom
+ );
};
-
createEffect(() => {
if (!restoreListScroll()) return;
const searchOpen = props.searchOpen;
- const sourcesReady = searchOpen
- ? !props.sources.search.isLoading()
- : tab() === 'recents'
- ? !props.sources.recents.isLoading()
- : tab() === 'threads'
- ? !props.sources.threads.isLoading()
- : BROWSE_QUERY_SCOPES.every(
- (scope) => !props.sources[scope].isLoading()
- );
- if (!sourcesReady) return;
+ let sourcesReady: boolean;
+
+ if (searchOpen) {
+ sourcesReady = !props.sources.search.isLoading();
+ } else if (tab() === 'recents') {
+ sourcesReady = !props.sources.recents.isLoading();
+ } else if (tab() === 'threads') {
+ sourcesReady = !props.sources.threads.isLoading();
+ } else {
+ sourcesReady = BROWSE_QUERY_SCOPES.every(
+ (scope) => !props.sources[scope].isLoading()
+ );
+ }
+
+ if (!sourcesReady) {
+ return;
+ }
const frame = requestAnimationFrame(() => {
if (props.searchOpen !== searchOpen) return;
@@ -680,9 +773,21 @@ export function ChannelsRail(props: ChannelsRailProps) {
} else if (tab() === 'threads') {
scrollThreadsToSelectedOrStart();
} else {
- scrollFavoritesToSelectedOrStart();
- for (const scope of BROWSE_QUERY_SCOPES) {
- scrollScopeToSelectedOrStart(scope);
+ if (sectionsEnabled()) {
+ const selectedIndex = visibleRows().findIndex(
+ (row) =>
+ (row.kind === 'conversation' &&
+ row.channel.id === selectedChannel()?.id) ||
+ (row.kind === 'favorite' &&
+ row.favorite.entityId === selectedChannel()?.id)
+ );
+ browseScrollHandle()?.scrollToIndex(Math.max(selectedIndex, 0), {
+ align: selectedIndex >= 0 ? 'nearest' : 'start',
+ });
+ } else {
+ scrollFavoritesToSelectedOrStart();
+ for (const scope of BROWSE_QUERY_SCOPES)
+ scrollScopeToSelectedOrStart(scope);
}
}
setRestoreListScroll(false);
@@ -692,13 +797,12 @@ export function ChannelsRail(props: ChannelsRailProps) {
useViewTabHotkeys({
scopeId: panel.splitHotkeyScope,
- enabled: panel.isPanelActive,
+ enabled: () => panel.isPanelActive() && !sectionsEnabled(),
ids: () =>
threadsEnabled() ? CHANNEL_TAB_IDS_WITH_THREADS : CHANNEL_TAB_IDS,
- activeId: () => tab(),
+ activeId: tab,
setActiveId: selectTab,
});
-
useViewControlHotkeys({
scopeId: panel.splitHotkeyScope,
enabled: panel.isPanelActive,
@@ -726,21 +830,42 @@ export function ChannelsRail(props: ChannelsRailProps) {
if (props.searchOpen) return true;
const row = current?.item;
- if (direction !== 1 || row?.kind !== 'conversation') return true;
- const source = props.sources[row.scope];
- const renderedCount =
- row.scope === 'team_channels'
- ? channelSectionRows().length
- : source.items().length;
- if (row.localIndex < renderedCount - 1) return true;
+ if (direction !== 1 || !row) {
+ return true;
+ }
+
+ let scope: ChannelsSourceScope | undefined;
+
+ if (sectionsEnabled()) {
+ scope = getChannelRailPaginationScope(
+ row,
+ visibleRows(),
+ state.expandedGroups
+ );
+ } else if (row.kind === 'conversation') {
+ const sourceLength =
+ row.scope === 'team_channels'
+ ? channelSectionRows().length
+ : props.sources[row.scope].items().length;
+
+ if (row.localIndex >= sourceLength - 1) {
+ scope = row.scope;
+ }
+ }
+
+ if (!scope) {
+ return true;
+ }
+
+ const source = props.sources[scope];
if (!source.isLoadingMore()) {
if (!source.hasMore()) return true;
fireAndForget(source.loadMore(), 'channels-view');
}
- if (row.scope === 'direct_messages') {
+ if (row.kind === 'conversation' && scope === 'direct_messages') {
requestAnimationFrame(() => {
const scrollRoot = sectionScrollRoots().direct_messages;
const element = document.getElementById(
@@ -820,21 +945,26 @@ export function ChannelsRail(props: ChannelsRailProps) {
);
const jumpToSection = (offset: 1 | -1) => {
- const currentGroup = list.focus.item()?.group;
-
- const sections = CHANNEL_RAIL_SECTIONS.filter((section) =>
- section === 'favorites' ? favorites().length > 0 : true
- );
+ const headers = list.items
+ .all()
+ .filter((row) => row.kind === 'section' || row.kind === 'label');
+ const current = list.focus.item();
+ let currentKey = current?.id;
+
+ if (current?.kind === 'label' || current?.kind === 'section') {
+ currentKey = current.id;
+ } else if (current?.kind === 'conversation' && current.labelId) {
+ currentKey = rowKeyForLabel(current.labelId);
+ } else if (current?.group) {
+ currentKey = rowKeyForSection(current.group);
+ }
- const currentIndex = currentGroup ? sections.indexOf(currentGroup) : -1;
+ const currentIndex = headers.findIndex((row) => row.id === currentKey);
const origin = currentIndex === -1 ? (offset === 1 ? -1 : 0) : currentIndex;
- const nextIndex = (origin + offset + sections.length) % sections.length;
- const nextGroup = sections[nextIndex];
- if (!nextGroup) return false;
-
- const result = list.focus.set(rowKeyForSection(nextGroup), {
- reason: 'keyboard',
- });
+ const nextIndex = (origin + offset + headers.length) % headers.length;
+ const next = headers[nextIndex];
+ if (!next) return false;
+ const result = list.focus.set(next.id, { reason: 'keyboard' });
if (!result) return false;
listRoot()?.focus({ preventScroll: true });
@@ -887,230 +1017,37 @@ 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 labelChannelById = (channelId: string) =>
- channelsById().get(channelId) ??
- searchResults().find((channel) => channel.id === channelId);
- const channelName = (channelId: string) => {
- const name = labelChannelById(channelId)?.name;
- return name ? `#${name}` : 'the channel';
- };
- const canLabelChannelId = (channelId: string) =>
- canLabelChannel(labelChannelById(channelId));
-
- 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 (!channelIds.every(canLabelChannelId)) return;
- if (!labelsAvailable()) {
- toast.failure(labelsUnavailableReason());
- return;
- }
- const names = channelIds
- .map((id) => labelChannelById(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.');
- if (!channelIds.every(canLabelChannelId))
- throw new Error('Only team channels can be added to labels.');
- const created = await createLabelMutation.mutateAsync({
- name,
- channelIds,
- });
- setGroupOpen('team_channels', true);
- setLabelOpen(created.id, true);
- },
- },
- { owner: labelDialogOwner() }
- );
- 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('team_channels', true);
- setLabelOpen(created.id, true);
- toast.success(`Created “${name}”`);
- },
- },
- { owner: labelDialogOwner() }
- );
- };
-
- 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: labelDialogOwner() }
- );
- };
-
- 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: labelDialogOwner() }
- );
- 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 Team channels list.'
- : `Its ${label.channelCount} channels go back to the Team 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: labelDialogOwner() }
- );
- 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() || !canLabelChannelId(channelId)) 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 {
+ createLabel,
+ createSmartTag,
+ renameLabel,
+ deleteLabel,
+ setChannelLabel,
+ markLabelRead,
+ canLabelChannelId,
+ labelChannelById,
+ } = useChannelLabelActions({
+ sectionsEnabled,
+ channelTagsEnabled,
+ labelsAvailable,
+ labelsUnavailableReason,
+ sharedLabels,
+ labels,
+ channelsById,
+ searchResults,
+ labelDialogOwner,
+ setGroupOpen,
+ setLabelOpen,
+ });
- const markLabelRead = async (label: ChannelLabel) => {
- if (!channelTagsEnabled()) return;
- const channelIds = new Set(
- filterChannelLabelMembers(label.channelIds, channelsById())
- );
- if (channelIds.size === 0) return;
- try {
- await ensureNotificationSourceLoaded(notificationSource);
- const unread = notificationSource
- .notifications()
- .filter(
- (notification) =>
- notification.entity_type === 'channel' &&
- channelIds.has(notification.entity_id) &&
- !notificationIsRead(notification)
- );
- await notificationSource.bulkMarkAsRead(unread);
- } catch (error) {
- toast.failure(
- errorMessage(error, 'Failed to mark channel label as read')
- );
- }
- };
+ const { muteSection, snoozeSection, sectionNotificationsDisabled } =
+ useChannelSectionNotifications({
+ enabled: sectionsEnabled,
+ labelsAvailable: () => !channelTagsEnabled() || labelsAvailable(),
+ labels,
+ favorites,
+ dialogOwner: labelDialogOwner,
+ });
// Drops are resolved here rather than per row so a channel dragged from
// anywhere in the section lands the same way.
@@ -1120,71 +1057,132 @@ export function ChannelsRail(props: ChannelsRailProps) {
// 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;
+ if (!channelTagsEnabled()) {
+ return undefined;
+ }
+
const drag = dndState?.active.draggable?.data as
| ChannelLabelDragData
| undefined;
- if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId)
+
+ if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId) {
return undefined;
- if (!canLabelChannelId(drag.channelId)) return undefined;
+ }
+
+ if (!canLabelChannelId(drag.channelId)) {
+ 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 === 'smart-tag') {
+ return undefined;
+ }
+
if (
drop.target.kind === 'channel' &&
!canDropOnChannel(drag.channelId, drop.target.channelId)
- )
+ ) {
return undefined;
- if (drop.target.kind === 'label' && drop.target.labelId === drag.labelId)
+ }
+
+ if (drop.target.kind === 'label') {
+ const labelId = drop.target.labelId;
+ const label = labels().find((label) => label.id === labelId);
+
+ if (!label || !canLabelChannel(labelChannelById(drag.channelId), label)) {
+ return undefined;
+ }
+ }
+
+ if (drop.target.kind === 'label' && drop.target.labelId === drag.labelId) {
+ return undefined;
+ }
+
+ if (drop.target.kind === 'unlabelled' && !drag.labelId) {
return undefined;
- if (drop.target.kind === 'unlabelled' && !drag.labelId) return undefined;
+ }
+
return drop.target;
};
+
dndActions?.onDragEnd(({ draggable, droppable }) => {
- if (!channelTagsEnabled()) return;
+ if (!channelTagsEnabled()) {
+ return;
+ }
+
const drag = draggable?.data as ChannelLabelDragData | undefined;
- if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId)
+
+ if (drag?.dragType !== 'channel-label' || drag.dndScope !== listDomId) {
return;
- if (!canLabelChannelId(drag.channelId)) return;
+ }
+
+ if (!canLabelChannelId(drag.channelId)) {
+ 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;
+
+ 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 === '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);
+ if (drag.labelId) {
+ setChannelLabel(drag.channelId, undefined, drag.labelId);
+ }
+
return;
}
- if (!canDropOnChannel(drag.channelId, target.channelId)) return;
+
+ if (!canDropOnChannel(drag.channelId, target.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);
+ setChannelLabel(drag.channelId, undefined, drag.labelId);
return;
}
+
fireAndForget(
createLabel([drag.channelId, target.channelId]),
'channels-view'
@@ -1211,6 +1209,7 @@ export function ChannelsRail(props: ChannelsRailProps) {
const rail: ChannelsRailContext = {
railId: listDomId,
list,
+ sectionsEnabled,
tab,
selectTab,
sources: props.sources,
@@ -1225,20 +1224,62 @@ export function ChannelsRail(props: ChannelsRailProps) {
labels,
labelsAvailable,
labelsUnavailableReason,
+ retryLabels: async () => {
+ await labelsQuery.refetch();
+
+ if (sectionsEnabled()) {
+ await personalLabelsQuery.refetch();
+ }
+ },
+ retryReferencedChannels: nextReferencedChannels.retry,
isLabelOpen,
toggleLabel: (labelId) => setLabelOpen(labelId, !isLabelOpen(labelId)),
channelSectionRows,
labelUnreadCount,
createLabel,
createSmartTag,
- editSmartTag,
+ editSmartTag: renameLabel,
+ canShareSections: () => sharedLabels(),
renameLabel,
deleteLabel,
setChannelLabel,
activeDropTarget,
markLabelRead,
+ muteSection,
+ snoozeSection,
+ sectionNotificationsDisabled,
sortBy: (group) => state.sortBy[group],
setSortBy,
+ sectionPreferences: (section) => {
+ let sort: ChannelSectionPreferences['sort'];
+
+ if (
+ section === 'team_channels' ||
+ section === 'channels' ||
+ section === 'direct_messages'
+ ) {
+ sort = state.sortBy[section];
+ } else if (section === 'favorites') {
+ sort = 'manual';
+ } else {
+ sort = 'name';
+ }
+
+ return { sort, ...state.sectionPreferences[section] };
+ },
+ setSectionPreferences: (section, preferences) => {
+ if (
+ preferences.sort &&
+ preferences.sort !== 'name' &&
+ preferences.sort !== 'manual' &&
+ (section === 'team_channels' ||
+ section === 'channels' ||
+ section === 'direct_messages')
+ ) {
+ setSortBy(section, preferences.sort);
+ }
+ setSectionPreferences(section, preferences);
+ },
registerRootRef: setListRoot,
activateRow,
prefetchRow,
@@ -1248,32 +1289,45 @@ export function ChannelsRail(props: ChannelsRailProps) {
[group]: element,
}));
},
+ registerBrowseScrollHandle: (handle) => {
+ setBrowseScrollHandle(handle);
+ return () => {
+ if (browseScrollHandle() === handle) {
+ setBrowseScrollHandle(undefined);
+ }
+ };
+ },
registerVirtualizer,
channelActivity,
};
+ const search = {
+ isOpen: () => props.searchOpen,
+ query: searchQuery,
+ results: searchResults,
+ isLoading: searchLoading,
+ error: searchError,
+ open: openSearch,
+ close: closeSearch,
+ setQuery: setSearchQuery,
+ registerInput: (element: HTMLInputElement) => {
+ searchInput = element;
+ },
+ retry: retrySearch,
+ };
+
return (
<ChannelsRailProvider value={rail}>
<aside
aria-label="Chat navigation"
class="flex size-full min-h-0 flex-col gap-3 bg-panel"
>
- <ExpandedChannelsRail
- search={{
- isOpen: () => props.searchOpen,
- query: searchQuery,
- results: searchResults,
- isLoading: searchLoading,
- error: searchError,
- open: openSearch,
- close: closeSearch,
- setQuery: setSearchQuery,
- registerInput: (element) => {
- searchInput = element;
- },
- retry: retrySearch,
- }}
- />
+ <Show
+ when={sectionsEnabled()}
+ fallback={<ExpandedChannelsRail search={search} />}
+ >
+ <NextChannelsRail search={search} />
+ </Show>
</aside>
</ChannelsRailProvider>
);
diff --git a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts
index c54ab8bae4..8349fe217f 100644
--- a/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts
+++ b/apps/web/src/features/channels-view/components/rail/ChannelsRailContext.ts
@@ -1,4 +1,4 @@
-import type { ListController } from '@app/components/list';
+import type { ListController, ListScrollHandle } from '@app/components/list';
import type { ChannelPreviewSelection } from '@app/features/next-soup/utils';
import { createAssertedContextProvider } from '@core/context/createContext';
import type { ChannelEntity } from '@entity';
@@ -10,6 +10,8 @@ import type { VirtualizerHandle } from 'virtua/solid';
import type { ChannelsSourceScope, ChannelsSources } from '../../queries';
import type {
ChannelListSort,
+ ChannelSectionKey,
+ ChannelSectionPreferences,
ChannelsGroup,
ChannelsRailSection,
ChannelsSortGroup,
@@ -33,6 +35,18 @@ export type ChannelRailRow =
id: `section:${ChannelsRailSection}`;
group: ChannelsRailSection;
}
+ | {
+ kind: 'status';
+ id: `status:${ChannelsGroup}`;
+ group: ChannelsGroup;
+ }
+ | {
+ /** Loading or retry feedback after an open section's available channels. */
+ kind: 'reference-status';
+ id: `reference-status:${ChannelSectionKey}`;
+ group: 'favorites' | 'team_channels';
+ state: 'loading' | 'error';
+ }
| {
kind: 'favorite';
id: `favorite:${string}`;
@@ -121,14 +135,12 @@ export type ChannelRailActivationMetadata = {
export type ChannelsRailContext = {
railId: string;
list: ListController<ChannelRailRow, ChannelRailActivationMetadata>;
+ sectionsEnabled: Accessor<boolean>;
tab: Accessor<ChannelsTab>;
selectTab: (tab: ChannelsTab) => void;
sources: ChannelsSources;
favorites: Accessor<readonly Favorite[]>;
- /**
- * A channel the rail has loaded, from its sections or fetched by id for a
- * label or favorite row. Undefined until the fetch settles.
- */
+ /** A channel available from loaded pages, normalized cache, or a by-ID lookup. */
channelById: (channelId: string) => ChannelEntity | undefined;
selectedChannel: Accessor<ChannelPreviewSelection | undefined>;
/** Whether the Threads tab is available to this user. */
@@ -145,31 +157,48 @@ export type ChannelsRailContext = {
labelsAvailable: Accessor<boolean>;
/** Why labels are unavailable, for the create menu and refused drops. */
labelsUnavailableReason: Accessor<string>;
+ retryLabels: () => Promise<void>;
+ /** Retry unresolved channels referenced by section membership or favorites. */
+ retryReferencedChannels: () => Promise<void>;
isLabelOpen: (labelId: string) => boolean;
toggleLabel: (labelId: string) => void;
/** The Channels section's rendered rows: label headings and channels. */
channelSectionRows: Accessor<readonly ChannelSectionRow[]>;
/** 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.
- */
+ /** Create a manual or smart section with optional initial channel members. */
+ createLabel: (
+ channelIds: string[],
+ scope?: 'personal' | 'team'
+ ) => Promise<void>;
+ /** Legacy menu actions retained while the section rollout is off. */
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. */
+ canShareSections: Accessor<boolean>;
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;
+ setChannelLabel: (
+ channelId: string,
+ labelId: string | undefined,
+ fromLabelId?: string
+ ) => 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;
+ /** Update the viewer's notifications for the section's current full membership. */
+ muteSection: (section: ChannelSectionKey, muted: boolean) => Promise<void>;
+ snoozeSection: (section: ChannelSectionKey) => Promise<void>;
+ sectionNotificationsDisabled: (section: ChannelSectionKey) => boolean;
sortBy: (group: ChannelsSortGroup) => ChannelListSort;
setSortBy: (group: ChannelsSortGroup, sort: ChannelListSort) => void;
+ sectionPreferences: (section: ChannelSectionKey) => ChannelSectionPreferences;
+ setSectionPreferences: (
+ section: ChannelSectionKey,
+ preferences: ChannelSectionPreferences
+ ) => void;
registerRootRef: (element: HTMLDivElement) => void;
activateRow: (rowId: ChannelRailRow['id'], event?: MouseEvent) => void;
/** Warm a channel row's messages on the press that may open it. */
@@ -178,6 +207,8 @@ export type ChannelsRailContext = {
group: ChannelsRailSection | 'threads',
element: HTMLDivElement
) => void;
+ /** The sectioned renderer owns its nested scroll regions and local indexes. */
+ registerBrowseScrollHandle: (handle: ListScrollHandle) => () => void;
registerVirtualizer: (
scope: ChannelsSourceScope,
handle: VirtualizerHandle
diff --git a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx
index 727a9c56d0..baa5e63b3f 100644
--- a/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx
+++ b/apps/web/src/features/channels-view/components/rail/ExpandedChannelsRail.tsx
@@ -3,32 +3,15 @@ import { runCreateAction } from '@app/features/command/Launcher';
import { SlackImportSidebar } from '@app/features/slack-import/slack-import-sidebar';
import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';
import { openNewChannelModal } from '@channel/CreateChannelModal';
-import { ChannelMutedIndicator } from '@channel/components/ChannelMutedIndicator';
-import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { createScrollTopFade } from '@core/util/createScrollTopFade';
import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';
-import { type ChannelEntity, Entity } from '@entity';
+import type { ChannelEntity } from '@entity';
import CaretDownIcon from '@icon/system/regular/caret-down.svg';
-import ChatsCircleIcon from '@icon/system/regular/chats-circle.svg';
-import CheckIcon from '@icon/system/regular/check.svg';
import MagnifyingGlassIcon from '@icon/system/regular/magnifying-glass.svg';
-import SortIcon from '@icon/system/regular/sort-ascending.svg';
import XIcon from '@icon/system/regular/x.svg';
-import {
- createDraggable,
- createDroppable,
- useDragDropContext,
-} from '@thisbeyond/solid-dnd';
-import {
- cn,
- Dropdown,
- EmptyStatePanel,
- Hotkey,
- type TabOption,
- Tabs,
- Tooltip,
-} from '@ui';
+import { createDroppable } from '@thisbeyond/solid-dnd';
+import { cn, EmptyStatePanel, Hotkey, type TabOption, Tabs } from '@ui';
import { tourTarget } from '@ui/components/Tour';
import {
type Accessor,
@@ -43,35 +26,24 @@ import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
import { canLabelChannel } from '../../core/channel-label-eligibility';
import { ChannelsLiveCallsSidebar } from '../../live-calls-sidebar';
import { CHANNELS_TOUR } from '../../tour';
-import type {
- ChannelListSort,
- ChannelsGroup,
- ChannelsSortGroup,
- ChannelsTab,
-} from '../../types';
-import { channelMentionsUser, formatDetailedTimestamp } from '../../utils';
+import type { ChannelsGroup, ChannelsTab } from '../../types';
import { ChannelsEmptyState } from '../ChannelsEmptyState';
import { ConversationsCreateMenu } from '../ConversationsCreateMenu';
import { ChannelFavoritesSection } from './ChannelFavoriteRows';
+import { ChannelLabelRow, ChannelsCreateMenu } from './ChannelLabelRows';
import {
- ChannelLabelMenuItems,
- ChannelLabelRow,
- ChannelsCreateMenu,
-} from './ChannelLabelRows';
+ ExpandedRecents,
+ ExpandedThreads,
+ RecentConversationCard,
+} from './ChannelListViews';
+import { ChannelOption } from './ChannelOption';
import {
- ChannelAvatar,
- ChannelCallIndicator,
- ChannelRailItemContextMenu,
CONVERSATION_CARD_HEIGHT,
- ConversationCard,
- IncomingCallActions,
isPrimaryMouseDown,
} from './ChannelRailItems';
+import { ChannelSortDropdown } from './ChannelSortDropdown';
import {
- ALL_THREADS_ROW_ID,
- type ChannelLabelDragData,
type ChannelLabelDropData,
- type ChannelRailRow,
type ChannelSectionRow,
domIdForRow,
rowKeyForChannel,
@@ -87,8 +59,6 @@ import {
} from './ChannelsRailSection';
import {
CHANNEL_LIST_GROUPS,
- useChannelRailItemState,
- useChannelRailScopeState,
useChannelRailSectionState,
useChannelRailVirtualizer,
} from './hooks/useChannelRailState';
@@ -147,253 +117,6 @@ const GROUPS: GroupConfig[] = [
},
];
-const CHANNEL_SORT_OPTIONS: {
- value: ChannelListSort;
- label: string;
-}[] = [
- { value: 'viewed_at', label: 'Last viewed' },
- { value: 'updated_at', label: 'Last updated' },
- { value: 'created_at', label: 'Date created' },
-];
-
-function ChannelSortDropdown(props: {
- group: ChannelsSortGroup;
- label: string;
-}) {
- const rail = useChannelsRail();
- const setSort = (value: string) => {
- const option = CHANNEL_SORT_OPTIONS.find((item) => item.value === value);
- if (option) rail.setSortBy(props.group, option.value);
- };
-
- return (
- <Dropdown placement="bottom-end">
- <Dropdown.Trigger
- aria-label={`Sort ${props.label.toLowerCase()}`}
- tooltip={`Sort ${props.label.toLowerCase()}`}
- as={ViewSidebar.Control}
- variant="ghost"
- size="icon-sm"
- >
- <SortIcon class="size-3.5" />
- </Dropdown.Trigger>
- <Dropdown.Content class="min-w-40">
- <Dropdown.Group>
- <Dropdown.RadioGroup
- value={rail.sortBy(props.group)}
- onChange={setSort}
- >
- <For each={CHANNEL_SORT_OPTIONS}>
- {(option) => (
- <Dropdown.RadioItem closeOnSelect value={option.value}>
- <span class="flex-1">{option.label}</span>
- <Dropdown.ItemIndicator>
- <CheckIcon class="size-3.5 text-accent" />
- </Dropdown.ItemIndicator>
- </Dropdown.RadioItem>
- )}
- </For>
- </Dropdown.RadioGroup>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
-
-/**
- * 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 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;
- /** Make a team-channel row draggable between labels (Team 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() || !canLabelChannel(props.channel),
- })
- : 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 (
- <div
- ref={(element) => {
- dnd?.draggable.ref(element);
- dnd?.droppable.ref(element);
- }}
- {...(canLabelChannel(props.channel) ? dnd?.draggable.dragActivators : {})}
- onPointerDown={(event) => {
- didDrag = false;
- rail.prefetchRow(rowId(), event);
- }}
- 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.Item
- as="div"
- ref={tourTarget(CHANNELS_TOUR.conversation)}
- 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 when={item().unread}>
- <span
- aria-label="Unread"
- class="size-2 shrink-0 rounded-full bg-accent"
- />
- </Show>
- <Show when={!item().incomingCallId && timestamp()}>
- {(value) => (
- <span class="relative hidden shrink-0 group-hover/channel-option:block touch:hidden">
- <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"
- >
- <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>
- );
-}
-
function ExpandedHeader(props: { search: ChannelRailSearch }) {
const rail = useChannelsRail();
const selectTab = (value: ChannelsTab) => {
@@ -926,206 +649,6 @@ function ExpandedBrowse() {
);
}
-function RecentConversationCard(props: { channel: ChannelEntity }) {
- const rail = useChannelsRail();
- const currentUserId = useUserId();
- const item = useChannelRailItemState(() => props.channel.id);
-
- return (
- <ChannelRailItemContextMenu
- channel={props.channel}
- class="block w-full"
- extraItems={<ChannelLabelMenuItems channel={props.channel} />}
- >
- <ConversationCard
- id={item().domId}
- class="border-b border-edge-muted"
- channel={props.channel}
- senderId={props.channel.latestRootMessage?.senderId}
- mentionedCurrentUser={channelMentionsUser(
- props.channel,
- currentUserId()
- )}
- unread={item().unread}
- muted={item().muted}
- callStatus={item().callStatus}
- incomingCallId={item().incomingCallId}
- selected={item().selected}
- focused={item().focused}
- onActivate={(event) =>
- rail.activateRow(rowKeyForChannel(props.channel.id), event)
- }
- onPress={(event) =>
- rail.prefetchRow(rowKeyForChannel(props.channel.id), event)
- }
- />
- </ChannelRailItemContextMenu>
- );
-}
-
-function ExpandedRecents() {
- const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
- createScrollTopFade(scrollRoot);
- const scope = useChannelRailScopeState(() => 'recents');
- const pagination = useChannelRailVirtualizer(() => 'recents');
- const forceEmptyState = useDebugSetting(
- DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES
- );
-
- return (
- <Switch>
- <Match
- when={
- !forceEmptyState() &&
- scope().source.isLoading() &&
- scope().items.length === 0
- }
- >
- <RailListLoading />
- </Match>
- <Match
- when={
- !forceEmptyState() &&
- scope().source.error() &&
- scope().items.length === 0
- }
- >
- <RailListError retry={scope().source.refresh} />
- </Match>
- <Match when={forceEmptyState() || scope().items.length === 0}>
- <ChannelsEmptyState scope="recents" topAligned />
- </Match>
- <Match when={true}>
- <div
- ref={setScrollRoot}
- class="scrollbar-hidden size-full min-h-0 overflow-y-auto"
- aria-busy={scope().source.isLoadingMore()}
- >
- <Virtualizer
- ref={pagination.registerVirtualizer}
- data={scope().items}
- scrollRef={scrollRoot()}
- itemSize={CONVERSATION_CARD_HEIGHT}
- bufferSize={360}
- keepMounted={scope().keepMounted}
- onScroll={pagination.loadMoreNearEnd}
- >
- {(channel) => <RecentConversationCard channel={channel} />}
- </Virtualizer>
- <Show when={scope().source.isLoadingMore()}>
- <RailListLoadingMore variant="recent" />
- </Show>
- <Show
- when={scope().source.error() && !scope().source.isLoadingMore()}
- >
- <RailListError retry={scope().source.refresh} compact />
- </Show>
- </div>
- </Match>
- </Switch>
- );
-}
-
-function ExpandedThreads() {
- const rail = useChannelsRail();
- const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
- const scope = useChannelRailScopeState(() => 'threads');
- const pagination = useChannelRailVirtualizer(() => 'threads');
- const allThreadsDomId = () => domIdForRow(rail.railId, ALL_THREADS_ROW_ID);
- const allThreadsSelected = () => rail.threadsChannelId() === undefined;
- const allThreadsFocused = () => rail.list.focus.key() === ALL_THREADS_ROW_ID;
- const registerScrollRef = (element: HTMLDivElement) => {
- setScrollRoot(element);
- rail.registerScrollRef('threads', element);
- };
-
- return (
- <ViewSidebar.Content class="h-full overflow-hidden">
- <ViewSidebar.Nav aria-label="Thread filters" class="shrink-0">
- <ViewSidebar.Item
- as="div"
- id={allThreadsDomId()}
- role="treeitem"
- tabIndex={-1}
- class={cn(
- !allThreadsSelected() && allThreadsFocused() && 'bg-hover text-ink'
- )}
- active={allThreadsSelected()}
- aria-current={allThreadsSelected() ? 'page' : undefined}
- onClick={(event) => {
- if (!isPrimaryMouseDown(event)) return;
- rail.activateRow(ALL_THREADS_ROW_ID, event);
- }}
- >
- <ViewSidebar.Icon>
- <ChatsCircleIcon class="size-4" />
- </ViewSidebar.Icon>
- <span class="min-w-0 flex-1 truncate">All threads</span>
- </ViewSidebar.Item>
- </ViewSidebar.Nav>
- <CollapsibleSection.Root open sizing="fill">
- <CollapsibleSection.Header focused={false} focusWithin={false}>
- <span class="flex h-full min-w-0 flex-1 items-center px-2">
- <span class="min-w-0 truncate">Conversations</span>
- </span>
- <div data-section-action="" class="flex items-center gap-0.5">
- <ChannelSortDropdown group="threads" label="Conversations" />
- <Show when={isTouchDevice()}>
- <ConversationsCreateMenu />
- </Show>
- </div>
- </CollapsibleSection.Header>
- <CollapsibleSection.Content
- open
- contentRef={registerScrollRef}
- class="flex min-h-0 flex-col gap-0.5"
- >
- <Switch>
- <Match
- when={scope().source.isLoading() && scope().items.length === 0}
- >
- <RailListLoading />
- </Match>
- <Match when={scope().source.error() && scope().items.length === 0}>
- <RailListError retry={scope().source.refresh} />
- </Match>
- <Match when={scope().items.length > 0}>
- <Virtualizer
- ref={pagination.registerVirtualizer}
- data={scope().items}
- scrollRef={scrollRoot()}
- itemSize={34}
- bufferSize={240}
- keepMounted={scope().keepMounted}
- onScroll={pagination.loadMoreNearEnd}
- >
- {(channel) => (
- <div class="pb-0.5">
- <ChannelOption channel={channel} />
- </div>
- )}
- </Virtualizer>
- <Show when={scope().source.isLoadingMore()}>
- <RailListLoadingMore variant="channel" />
- </Show>
- <Show
- when={scope().source.error() && !scope().source.isLoadingMore()}
- >
- <RailListError retry={scope().source.refresh} compact />
- </Show>
- </Match>
- <Match when={true}>
- <div class="px-2 py-2 text-xs text-ink-extra-muted">
- No conversations
- </div>
- </Match>
- </Switch>
- </CollapsibleSection.Content>
- </CollapsibleSection.Root>
- </ViewSidebar.Content>
- );
-}
-
export function ExpandedChannelsRail(props: { search: ChannelRailSearch }) {
const listTarget = tourTarget(CHANNELS_TOUR.list);
const rail = useChannelsRail();
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.tsx
index 485cd84b67..f5ecce9dee 100644
--- a/apps/web/src/features/channels-view/components/rail/SmartTagDialog.test.tsx
+++ b/apps/web/src/features/channels-view/components/rail/SmartTagDialog.test.tsx
@@ -14,6 +14,8 @@ import type { ComponentProps, ParentProps } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { promptSmartTag } from './SmartTagDialog';
+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));
+
const fetchPreview = vi.hoisted(() => vi.fn());
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => () => ({ enabled: true }),
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.ts
index e2440dc4a0..04768b4082 100644
--- 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.ts
@@ -5,6 +5,10 @@ import {
buildChannelRailRows,
buildChannelSectionRows,
} from './build-channel-rail-rows';
+import {
+ buildChannelRailRows as buildSectionedRailRows,
+ groupChannelRailSections,
+} from './next/build-channel-rail-rows';
function channel(
id: string,
@@ -123,7 +127,7 @@ describe('buildChannelSectionRows', () => {
});
it.each([true, false])(
- 'keeps non-team channels in the plain list when labels are open=%s, ignoring cached memberships',
+ 'excludes non-team channels from team sections when labels are open=%s',
(isOpen) => {
const publicChannel = channel('public', 'Public', 'public');
const privateChannel = channel('private', 'Private', 'private');
@@ -151,10 +155,7 @@ describe('buildChannelSectionRows', () => {
expect(
rows.filter((row) => row.kind === 'conversation' && !row.labelId)
- ).toEqual([
- { kind: 'conversation', channel: publicChannel },
- { kind: 'conversation', channel: privateChannel },
- ]);
+ ).toEqual([]);
expect(
rows.filter((row) => row.kind === 'conversation' && row.labelId)
).toEqual(
@@ -420,3 +421,98 @@ it('renders a channel in every matching smart tag with unique navigation IDs, ex
{ kind: 'conversation', channel: deals },
]);
});
+
+it('keeps saved favorite order unless an automatic sort is selected', () => {
+ const items: Parameters<typeof buildSectionedRailRows>[2] = {
+ favorites: [zeta, deals].map((item, sortOrder) => ({
+ entityId: item.id,
+ entityType: 'channel',
+ sortOrder,
+ createdAt: '2026-01-01',
+ })),
+ team_channels: [],
+ channels: [],
+ direct_messages: [],
+ recents: [],
+ threads: [],
+ };
+ const expanded = {
+ favorites: true,
+ team_channels: false,
+ channels: false,
+ direct_messages: false,
+ };
+ const rows = (sort?: 'manual' | 'name') =>
+ buildSectionedRailRows('browse', expanded, items, [], {
+ preferences: { favorites: { sort } },
+ channelById: (id) => byId.get(id),
+ unreadChannelIds: new Set(),
+ }).flatMap((row) =>
+ row.kind === 'favorite' ? [row.favorite.entityId] : []
+ );
+ expect(rows()).toEqual(['zeta', 'deals']);
+ expect(rows('manual')).toEqual(['zeta', 'deals']);
+ expect(rows('name')).toEqual(['deals', 'zeta']);
+});
+
+it('keeps overlapping section members and loading rows in their own scroll regions', () => {
+ const labels = [
+ label('first', 'First', ['acme']),
+ label('second', 'Second', ['acme']),
+ ];
+ const sections = buildChannelSectionRows({
+ labels,
+ channels: [acme],
+ channelsById: byId,
+ isLabelOpen: (id) => id === 'first',
+ });
+ const rows = buildSectionedRailRows(
+ 'browse',
+ {
+ favorites: false,
+ team_channels: true,
+ channels: true,
+ direct_messages: true,
+ },
+ {
+ favorites: [],
+ team_channels: [acme],
+ channels: [],
+ direct_messages: [deals],
+ recents: [],
+ threads: [],
+ },
+ sections,
+ {
+ preferences: {},
+ channelById: (id) => byId.get(id),
+ unreadChannelIds: new Set(),
+ referenceStatuses: { 'label:first': 'loading' },
+ }
+ );
+ const grouped = groupChannelRailSections(rows);
+ expect([...grouped.keys()]).toEqual([
+ 'favorites',
+ 'direct_messages',
+ 'team_channels',
+ 'label:first',
+ 'label:second',
+ ]);
+ expect(grouped.get('label:first')?.rows.map((row) => row.id)).toEqual([
+ 'channel:acme:label:first',
+ 'reference-status:label:first',
+ ]);
+ expect(grouped.get('label:second')?.rows).toEqual([]);
+ expect(grouped.get('direct_messages')?.rows.map((row) => row.id)).toEqual([
+ 'channel:deals',
+ 'status:direct_messages',
+ ]);
+ expect(
+ grouped
+ .get('team_channels')
+ ?.rows.every((row) => row.kind !== 'conversation')
+ ).toBe(true);
+ expect(
+ rows.filter((row) => row.kind === 'conversation').map((row) => row.id)
+ ).toEqual(['channel:deals', 'channel:acme:label:first']);
+});
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.ts
index cbc0549570..b224880e90 100644
--- 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.ts
@@ -50,7 +50,9 @@ export function buildChannelSectionRows(options: {
.map((id) => options.channelsById.get(id))
.filter(
(channel): channel is ChannelEntity =>
- channel !== undefined && canLabelChannel(channel)
+ channel !== undefined &&
+ channel.channelType === 'team' &&
+ canLabelChannel(channel, label)
)
.sort(compareChannelName);
@@ -63,7 +65,7 @@ export function buildChannelSectionRows(options: {
}
for (const channel of options.channels) {
- if (labelled.has(channel.id)) continue;
+ if (channel.channelType !== 'team' || labelled.has(channel.id)) continue;
rows.push({ kind: 'conversation', channel });
}
diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts
new file mode 100644
index 0000000000..2715721e9d
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelLabelActions.ts
@@ -0,0 +1,504 @@
+import { t } from '@app/lib/i18n';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import { toast } from '@core/component/Toast/Toast';
+import { useUserId } from '@core/context/user';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { thrownResultErrorHasCode } from '@core/util/result';
+import type { ChannelEntity } from '@entity';
+import { notificationIsRead } from '@entity/utils/notification';
+import { Telemetry } from '@macro-inc/observability';
+import { ensureNotificationSourceLoaded } from '@notifications/notification-helpers';
+import {
+ useCreateChannelLabelMutation,
+ useDeleteChannelLabelMutation,
+ useRenameChannelLabelMutation,
+ useSetChannelLabelMutation,
+} from '@queries/channel-labels/channel-labels';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
+import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';
+import type { ChannelLabelScopeSelection } from '@service-storage/generated/schemas/channelLabelScopeSelection';
+import { confirmDialog } from '@ui';
+import type { Accessor, Owner } from 'solid-js';
+import {
+ canLabelChannel,
+ filterChannelLabelMembers,
+} from '../../../core/channel-label-eligibility';
+import type { ChannelsRailSection } from '../../../types';
+import { promptLabelName } from '../ChannelLabelNameDialog';
+import { promptSection, type SectionDialogValue } from '../next/SectionDialog';
+import { promptSmartTag } from '../SmartTagDialog';
+
+type ChannelLabelActionsOptions = {
+ sectionsEnabled: Accessor<boolean>;
+ channelTagsEnabled: Accessor<boolean>;
+ labelsAvailable: Accessor<boolean>;
+ labelsUnavailableReason: Accessor<string>;
+ sharedLabels: Accessor<boolean>;
+ labels: Accessor<readonly ChannelLabel[]>;
+ channelsById: Accessor<ReadonlyMap<string, ChannelEntity>>;
+ searchResults: Accessor<readonly ChannelEntity[]>;
+ labelDialogOwner: Accessor<Owner | null | undefined>;
+ setGroupOpen: (group: ChannelsRailSection, open: boolean) => void;
+ setLabelOpen: (labelId: string, open: boolean) => void;
+};
+
+export function useChannelLabelActions(options: ChannelLabelActionsOptions) {
+ const userId = useUserId();
+ const notificationSource = useGlobalNotificationSource();
+
+ const {
+ sectionsEnabled,
+ channelTagsEnabled,
+ labelsAvailable,
+ labelsUnavailableReason,
+ sharedLabels,
+ labels,
+ channelsById,
+ searchResults,
+ labelDialogOwner,
+ setGroupOpen,
+ setLabelOpen,
+ } = options;
+
+ // Explain shared versus private scope before creating or changing labels.
+ const mutations = {
+ personal: {
+ create: useCreateChannelLabelMutation('personal'),
+ rename: useRenameChannelLabelMutation('personal'),
+ delete: useDeleteChannelLabelMutation('personal'),
+ assign: useSetChannelLabelMutation('personal'),
+ },
+ team: {
+ create: useCreateChannelLabelMutation(),
+ rename: useRenameChannelLabelMutation(),
+ delete: useDeleteChannelLabelMutation(),
+ assign: useSetChannelLabelMutation(),
+ },
+ };
+
+ const defaultScope = (): ChannelLabelScopeSelection =>
+ sectionsEnabled() || !sharedLabels() ? 'personal' : 'team';
+
+ // Legacy endpoints and their cache keys use the implicit account/team scope.
+ const mutationsForScope = (scope: ChannelLabelScopeSelection) =>
+ sectionsEnabled() ? mutations[scope] : mutations.team;
+
+ const errorMessage = (error: unknown, fallback: string) => {
+ if (
+ thrownResultErrorHasCode(error, 'UNAUTHORIZED') ||
+ thrownResultErrorHasCode(error, 'FORBIDDEN')
+ ) {
+ return t('channelSections.labelsNoAccess');
+ }
+
+ const message = error instanceof Error ? error.message : '';
+ return message || fallback;
+ };
+
+ const labelChannelById = (channelId: string) =>
+ channelsById().get(channelId) ??
+ searchResults().find((channel) => channel.id === channelId);
+ const channelName = (channelId: string) => {
+ const name = labelChannelById(channelId)?.name;
+ return name ? `#${name}` : t('channelSections.unnamedChannel');
+ };
+
+ const canLabelChannelId = (channelId: string) =>
+ canLabelChannel(labelChannelById(channelId)) &&
+ (sectionsEnabled() || labelChannelById(channelId)?.channelType === 'team');
+
+ const scopeForLabel = (label: ChannelLabel): ChannelLabelScopeSelection =>
+ label.teamId ? 'team' : 'personal';
+ const labelScopeDescription = (scope: ChannelLabelScopeSelection) => {
+ if (!sectionsEnabled()) {
+ return t(
+ scope === 'team'
+ ? 'channelLabels.sharedScopeDescription'
+ : 'channelLabels.personalScopeDescription'
+ );
+ }
+
+ return t(
+ scope === 'team'
+ ? 'channelSections.teamDescription'
+ : 'channelSections.personalDescription'
+ );
+ };
+
+ const createLabel = async (
+ channelIds: string[],
+ scope: ChannelLabelScopeSelection = defaultScope(),
+ smart = false
+ ) => {
+ const actorId = userId();
+ const sectionMode = sectionsEnabled();
+
+ if (!channelTagsEnabled() || !channelIds.every(canLabelChannelId)) {
+ return;
+ }
+
+ if (!labelsAvailable()) {
+ toast.failure(labelsUnavailableReason());
+ return;
+ }
+
+ const save = ({ name, scope, rule }: SectionDialogValue) =>
+ Telemetry.span('channels.section.create', async (span) => {
+ span.setAttr('section.scope', scope);
+ span.setAttr('section.smart', Boolean(rule));
+
+ if (
+ actorId !== userId() ||
+ sectionMode !== sectionsEnabled() ||
+ !channelTagsEnabled() ||
+ !labelsAvailable()
+ ) {
+ throw new Error(t('channelSections.unavailable'));
+ }
+
+ if (scope === 'team' && !sharedLabels()) {
+ throw new Error(t('channelSections.noAccess'));
+ }
+
+ const members = rule ? [] : channelIds;
+ if (
+ !members.every(
+ (id) =>
+ canLabelChannelId(id) &&
+ (scope === 'personal' ||
+ labelChannelById(id)?.channelType === 'team')
+ )
+ ) {
+ throw new Error(t('channelSections.ineligibleChannel'));
+ }
+
+ const created = await mutationsForScope(scope).create.mutateAsync({
+ name,
+ rule,
+ channelIds: members,
+ actorId,
+ });
+ span.setAttr('section.id', created.id);
+
+ if (actorId !== userId()) {
+ return;
+ }
+
+ if (!sectionMode) {
+ setGroupOpen('team_channels', true);
+ }
+
+ setLabelOpen(created.id, true);
+ toast.success(t('channelSections.created', { name }));
+ });
+
+ if (sectionMode) {
+ await promptSection(
+ { scope, canShare: sharedLabels(), onConfirm: save },
+ { owner: labelDialogOwner() }
+ );
+ } else if (smart) {
+ await promptSmartTag(
+ {
+ scopeDescription: labelScopeDescription(scope),
+ onConfirm: (name, rule) => save({ name, scope, rule }),
+ },
+ { owner: labelDialogOwner() }
+ );
+ } else {
+ await promptLabelName(
+ {
+ title: t('channelLabels.newLabel'),
+ body: labelScopeDescription(scope),
+ confirmLabel: t('channelLabels.createLabel'),
+ onConfirm: (name) => save({ name, scope }),
+ },
+ { owner: labelDialogOwner() }
+ );
+ }
+ };
+
+ const createSmartTag = () => createLabel([], defaultScope(), true);
+
+ const renameLabel = async (label: ChannelLabel) => {
+ const actorId = userId();
+ const sectionMode = sectionsEnabled();
+
+ if (!channelTagsEnabled()) {
+ return;
+ }
+
+ const scope = scopeForLabel(label);
+ const save = ({ name, rule }: { name: string; rule?: ChannelLabelRule }) =>
+ Telemetry.span('channels.section.update', async (span) => {
+ span.setAttr('section.id', label.id);
+ span.setAttr('section.scope', scope);
+ span.setAttr('section.smart', Boolean(rule));
+
+ if (
+ actorId !== userId() ||
+ sectionMode !== sectionsEnabled() ||
+ !channelTagsEnabled() ||
+ !labelsAvailable()
+ ) {
+ throw new Error(t('channelSections.unavailable'));
+ }
+
+ await mutationsForScope(scope).rename.mutateAsync({
+ labelId: label.id,
+ name,
+ rule,
+ actorId,
+ });
+
+ if (actorId !== userId()) {
+ return;
+ }
+
+ toast.success(t('channelSections.updated', { name }));
+ });
+
+ if (sectionMode) {
+ await promptSection(
+ {
+ scope,
+ canShare: sharedLabels(),
+ initial: { name: label.name, rule: label.rule ?? undefined },
+ onConfirm: save,
+ },
+ { owner: labelDialogOwner() }
+ );
+ } else if (label.rule) {
+ await promptSmartTag(
+ {
+ scopeDescription: labelScopeDescription(scope),
+ initial: { name: label.name, rule: label.rule },
+ onConfirm: (name, rule) => save({ name, rule }),
+ },
+ { owner: labelDialogOwner() }
+ );
+ } else {
+ await promptLabelName(
+ {
+ title: t('channelLabels.renameLabel'),
+ body: labelScopeDescription(scope),
+ confirmLabel: t('channelLabels.rename'),
+ initialValue: label.name,
+ onConfirm: (name) => save({ name }),
+ },
+ { owner: labelDialogOwner() }
+ );
+ }
+ };
+
+ const deleteLabel = async (label: ChannelLabel) => {
+ const actorId = userId();
+
+ if (!channelTagsEnabled()) {
+ return;
+ }
+
+ const sectionMode = sectionsEnabled();
+ let channelsText: string;
+
+ if (label.rule) {
+ channelsText = t('channelSections.deleteSmartChannels');
+ } else if (label.channelCount === 0) {
+ channelsText = t('channelSections.deleteEmptyChannels');
+ } else {
+ channelsText = t('channelSections.conversationsRemain');
+ }
+
+ const confirmed = await confirmDialog(
+ {
+ title: t('channelSections.deleteConfirmTitle', { name: label.name }),
+ body: t('channelSections.deleteConfirmBody', {
+ scopeDescription: labelScopeDescription(scopeForLabel(label)),
+ channelsText,
+ }),
+ confirmLabel: label.teamId
+ ? t('channelSections.deleteForEveryone')
+ : t('channelSections.deleteSection'),
+ cancelLabel: t('channelSections.cancel'),
+ tone: 'danger',
+ },
+ { owner: labelDialogOwner() }
+ );
+
+ if (
+ !confirmed ||
+ !channelTagsEnabled() ||
+ userId() !== actorId ||
+ sectionMode !== sectionsEnabled()
+ ) {
+ return;
+ }
+
+ try {
+ await Telemetry.span('channels.section.delete', async (span) => {
+ span.setAttr('section.id', label.id);
+ span.setAttr('section.scope', scopeForLabel(label));
+ await mutationsForScope(scopeForLabel(label)).delete.mutateAsync({
+ labelId: label.id,
+ actorId,
+ });
+ });
+
+ if (actorId !== userId()) {
+ return;
+ }
+
+ toast.success(t('channelSections.deleted', { name: label.name }));
+ } catch (error) {
+ if (actorId !== userId()) {
+ return;
+ }
+
+ toast.failure(
+ errorMessage(error, t('channelSections.deleteLabelFailed'))
+ );
+ }
+ };
+
+ const setChannelLabel = (
+ channelId: string,
+ labelId: string | undefined,
+ fromLabelId?: string
+ ) => {
+ const actorId = userId();
+
+ if (!channelTagsEnabled() || !canLabelChannelId(channelId)) {
+ return;
+ }
+
+ const to = labelId
+ ? labels().find((label) => label.id === labelId)
+ : undefined;
+ const previous = fromLabelId
+ ? labels().find((label) => label.id === fromLabelId)
+ : undefined;
+
+ if (labelId && (!to || !canLabelChannel(labelChannelById(channelId), to))) {
+ return;
+ }
+
+ let scope: ChannelLabelScopeSelection;
+
+ if (to) {
+ scope = scopeForLabel(to);
+ } else if (previous) {
+ scope = scopeForLabel(previous);
+ } else {
+ scope = defaultScope();
+ }
+
+ const from = labels().find(
+ (label) =>
+ !label.rule &&
+ scopeForLabel(label) === scope &&
+ label.channelIds.includes(channelId)
+ );
+
+ if (to?.rule || from?.id === labelId) {
+ return;
+ }
+
+ if (labelId) {
+ setLabelOpen(labelId, true);
+ }
+
+ fireAndForget(
+ Telemetry.span('channels.section.assign', async (span) => {
+ span.setAttr('channel.id', channelId);
+ span.setAttr('section.scope', scope);
+
+ if (labelId) {
+ span.setAttr('section.id', labelId);
+ }
+
+ if (from) {
+ span.setAttr('section.previous_id', from.id);
+ }
+
+ try {
+ await mutationsForScope(scope).assign.mutateAsync({
+ channelId,
+ labelId,
+ actorId,
+ });
+
+ if (actorId !== userId()) {
+ return;
+ }
+
+ if (to) {
+ toast.success(
+ t('channelSections.movedChannel', {
+ channel: channelName(channelId),
+ name: to.name,
+ })
+ );
+ } else if (from) {
+ toast.success(
+ t('channelSections.removedChannel', {
+ channel: channelName(channelId),
+ name: from.name,
+ })
+ );
+ }
+ } catch (error) {
+ if (actorId === userId()) {
+ toast.failure(
+ errorMessage(error, t('channelSections.moveChannelFailed'))
+ );
+ }
+
+ throw error;
+ }
+ }),
+ 'channels-view'
+ );
+ };
+
+ const markLabelRead = async (label: ChannelLabel) => {
+ if (!channelTagsEnabled()) {
+ return;
+ }
+
+ const channelIds = new Set(
+ filterChannelLabelMembers(label.channelIds, channelsById())
+ );
+
+ if (channelIds.size === 0) {
+ return;
+ }
+
+ try {
+ await ensureNotificationSourceLoaded(notificationSource);
+ const unread = notificationSource
+ .notifications()
+ .filter(
+ (notification) =>
+ notification.entity_type === 'channel' &&
+ channelIds.has(notification.entity_id) &&
+ !notificationIsRead(notification)
+ );
+ await notificationSource.bulkMarkAsRead(unread);
+ } catch (error) {
+ toast.failure(
+ errorMessage(error, t('channelSections.markLabelReadFailed'))
+ );
+ }
+ };
+
+ return {
+ createLabel,
+ createSmartTag,
+ renameLabel,
+ deleteLabel,
+ setChannelLabel,
+ markLabelRead,
+ canLabelChannelId,
+ labelChannelById,
+ };
+}
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.ts
index 412fac1cbc..49bd965f75 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
@@ -98,7 +98,16 @@ export function useChannelRailScopeState(
return createMemo(() => {
const currentScope = scope();
const source = rail.sources[currentScope];
- const items = source.items();
+ const items =
+ currentScope === 'direct_messages'
+ ? rail.list.items
+ .all()
+ .flatMap((row) =>
+ row.kind === 'conversation' && row.scope === currentScope
+ ? [row.channel]
+ : []
+ )
+ : source.items();
// The Team channels section renders label headings between its channels,
// so its virtualizer indexes come from those rows, not the source.
const rows =
diff --git a/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.ts b/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.ts
new file mode 100644
index 0000000000..03927d7179
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/hooks/useChannelSectionNotifications.ts
@@ -0,0 +1,215 @@
+import { t } from '@app/lib/i18n';
+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import { toast } from '@core/component/Toast/Toast';
+import { useUserId } from '@core/context/user';
+import { Telemetry } from '@macro-inc/observability';
+import { openSnoozeNotifications } from '@notifications/SnoozeNotificationsDialog';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { type Accessor, createSignal, type Owner, onCleanup } from 'solid-js';
+import { fetchChannelGroupIds } from '../../../queries';
+import type { ChannelSectionKey } from '../../../types';
+
+type SectionNotificationOptions = {
+ enabled: Accessor<boolean>;
+ labelsAvailable: Accessor<boolean>;
+ labels: Accessor<readonly ChannelLabel[]>;
+ favorites: Accessor<readonly Favorite[]>;
+ dialogOwner: Accessor<Owner | null | undefined>;
+};
+
+export function useChannelSectionNotifications(
+ options: SectionNotificationOptions
+) {
+ const userId = useUserId();
+ const notificationSource = useGlobalNotificationSource();
+ const [pending, setPending] = createSignal<{ actorId: string }>();
+ const requests = new Set<AbortController>();
+ let disposed = false;
+
+ onCleanup(() => {
+ disposed = true;
+
+ for (const request of requests) {
+ request.abort();
+ }
+ });
+
+ const favoriteIds = () =>
+ options
+ .favorites()
+ .filter((favorite) => favorite.entityType === 'channel')
+ .map((favorite) => favorite.entityId);
+
+ const labelFor = (section: ChannelSectionKey) =>
+ options.labels().find((label) => section === `label:${label.id}`);
+
+ const sectionNotificationsDisabled = (section: ChannelSectionKey) => {
+ if (
+ disposed ||
+ !options.enabled() ||
+ !userId() ||
+ pending()?.actorId === userId()
+ ) {
+ return true;
+ }
+
+ if (section === 'favorites') {
+ return favoriteIds().length === 0;
+ }
+
+ if (!options.labelsAvailable()) {
+ return true;
+ }
+
+ if (section.startsWith('label:')) {
+ return !labelFor(section)?.channelIds.length;
+ }
+
+ return false;
+ };
+
+ const channelIdsFor = (
+ section: ChannelSectionKey,
+ signal: AbortSignal
+ ): string[] | Promise<string[]> => {
+ if (section === 'favorites') {
+ return [...new Set(favoriteIds())];
+ }
+
+ if (
+ section === 'channels' ||
+ section === 'team_channels' ||
+ section === 'direct_messages'
+ ) {
+ // Named channels assigned to custom sections no longer belong to the
+ // built-in section. DMs remain in their built-in section as well.
+ const excludedIds =
+ section === 'direct_messages'
+ ? []
+ : options.labels().flatMap((label) => label.channelIds);
+
+ return Telemetry.span('channels.section.members', () =>
+ fetchChannelGroupIds(section, excludedIds, signal)
+ );
+ }
+
+ return [...new Set(labelFor(section)?.channelIds ?? [])];
+ };
+
+ const updateSectionNotifications = async (
+ section: ChannelSectionKey,
+ action: 'mute' | 'unmute' | 'snooze'
+ ) => {
+ const actorId = userId();
+ const owner = options.dialogOwner();
+
+ if (!actorId || !owner || sectionNotificationsDisabled(section)) {
+ return;
+ }
+
+ const request = { actorId };
+ const controller = new AbortController();
+
+ const isCurrent = () =>
+ !disposed &&
+ options.enabled() &&
+ userId() === actorId &&
+ options.dialogOwner() === owner;
+
+ setPending(request);
+ requests.add(controller);
+
+ try {
+ await Telemetry.span('channels.section.notifications', async (span) => {
+ span.setAttr('section.id', section);
+ span.setAttr('notification.action', action);
+
+ const ids = channelIdsFor(section, controller.signal);
+ const channelIds = Array.isArray(ids) ? ids : await ids;
+
+ if (!isCurrent() || channelIds.length === 0) {
+ return;
+ }
+
+ span.setAttr('channel.ids', channelIds);
+ span.setAttr('notification.count', channelIds.length);
+
+ if (action === 'snooze') {
+ openSnoozeNotifications(
+ channelIds.map((id) => ({ item_type: 'channel', item_id: id })),
+ { owner }
+ );
+ return;
+ }
+
+ const muted = action === 'mute';
+ const results = await Promise.allSettled(
+ channelIds.map((id) =>
+ span.span('channels.section.notification.update', async (child) => {
+ child.setAttr('channel.id', id);
+
+ if (muted) {
+ await notificationSource.muteEntity({ type: 'channel', id });
+ } else {
+ await notificationSource.unmuteEntity({ type: 'channel', id });
+ }
+ })
+ )
+ );
+ const failed = results.filter(
+ (result) => result.status === 'rejected'
+ ).length;
+ const succeeded = results.length - failed;
+
+ span.setAttr('notification.failed_count', failed);
+
+ if (failed > 0) {
+ span.error('Some channel notification updates failed');
+ }
+
+ if (!isCurrent()) {
+ return;
+ }
+
+ if (failed > 0) {
+ toast.failure(
+ t(
+ muted
+ ? 'entityActions.toastMutedSome'
+ : 'entityActions.toastUnmutedSome',
+ { succeeded, count: results.length, failed }
+ )
+ );
+ return;
+ }
+
+ toast.success(
+ t(
+ muted
+ ? 'entityActions.toastMutedCount'
+ : 'entityActions.toastUnmutedCount',
+ { count: succeeded }
+ )
+ );
+ });
+ } catch (error) {
+ if (isCurrent()) {
+ toast.failure(t('channelSections.notificationsFailed'));
+ }
+
+ throw error;
+ } finally {
+ requests.delete(controller);
+ setPending((current) => (current === request ? undefined : current));
+ }
+ };
+
+ return {
+ sectionNotificationsDisabled,
+ muteSection: (section: ChannelSectionKey, muted: boolean) =>
+ updateSectionNotifications(section, muted ? 'mute' : 'unmute'),
+ snoozeSection: (section: ChannelSectionKey) =>
+ updateSectionNotifications(section, 'snooze'),
+ };
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelFavoriteRow.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelFavoriteRow.tsx
new file mode 100644
index 0000000000..e6243d73ff
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelFavoriteRow.tsx
@@ -0,0 +1,108 @@
+import { FavoriteIcon } from '@app/features/favorites/FavoriteIcon';
+import { useFavoriteDisplayName } from '@app/util/favorites';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import {
+ createDraggable,
+ createDroppable,
+ useDragDropContext,
+} from '@thisbeyond/solid-dnd';
+import { onCleanup, onMount, Show } from 'solid-js';
+import { ChannelFavoriteRow as FavoriteRow } from '../ChannelFavoriteRows';
+import { rowKeyForFavorite } from '../ChannelsRailContext';
+import type { useFavoriteReorder } from './useFavoriteReorder';
+
+type FavoriteRowProps = {
+ favorite: Favorite;
+ reorder: ReturnType<typeof useFavoriteReorder>;
+};
+
+export function ChannelFavoriteRow(props: FavoriteRowProps) {
+ return (
+ <Show when={rowKeyForFavorite(props.favorite)} keyed>
+ {(_key) => <DraggableFavoriteRow {...props} />}
+ </Show>
+ );
+}
+
+function DraggableFavoriteRow(props: FavoriteRowProps) {
+ const name = useFavoriteDisplayName(props.favorite);
+ const key = rowKeyForFavorite(props.favorite);
+ const data = {
+ dndScope: props.reorder.scope,
+ favoriteKey: key,
+ get name() {
+ return name();
+ },
+ overlayIcon: () => (
+ <FavoriteIcon favorite={props.favorite} class="size-4" />
+ ),
+ };
+
+ const draggable = createDraggable(`${props.reorder.scope}:drag:${key}`, data);
+ const droppable = createDroppable(`${props.reorder.scope}:drop:${key}`, {
+ ...data,
+ isDropTargetDisabled: () => !props.reorder.enabled(),
+ });
+ const [, actions] = useDragDropContext() ?? [];
+ let didDrag = false;
+
+ actions?.onDragStart(({ draggable: source }) => {
+ if (
+ source.data.dndScope === props.reorder.scope &&
+ source.data.favoriteKey === key
+ ) {
+ didDrag = true;
+ }
+ });
+
+ let root: HTMLDivElement | undefined;
+ const preventOpenAfterDrag = (event: MouseEvent) => {
+ if (!didDrag || event.detail === 0) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ onMount(() => root?.addEventListener('click', preventOpenAfterDrag, true));
+ onCleanup(() =>
+ root?.removeEventListener('click', preventOpenAfterDrag, true)
+ );
+
+ const dropEdge = () => props.reorder.dropEdge(key);
+
+ return (
+ <div
+ ref={(element) => {
+ root = element;
+ draggable.ref(element);
+ droppable.ref(element);
+ }}
+ {...(props.reorder.enabled() ? draggable.dragActivators : {})}
+ onPointerDown={() => {
+ didDrag = false;
+ }}
+ class="relative"
+ classList={{
+ 'opacity-50': draggable.isActiveDraggable,
+ }}
+ >
+ <FavoriteRow favorite={props.favorite} />
+ <Show when={dropEdge()}>
+ {(edge) => (
+ <div
+ aria-hidden="true"
+ class="pointer-events-none absolute inset-x-0 z-10 h-0.5 rounded-full bg-accent"
+ classList={{
+ 'top-0': edge() === 'top',
+ 'bottom-0': edge() === 'bottom',
+ }}
+ >
+ <span class="absolute -top-0.5 left-0 size-1.5 rounded-full bg-accent" />
+ </div>
+ )}
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsx
new file mode 100644
index 0000000000..630afd54a9
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelLabelRows.tsx
@@ -0,0 +1,266 @@
+import { t } from '@app/lib/i18n';
+import {
+ ContextMenuContent,
+ MenuGroup,
+ MenuItem,
+ MenuSeparator,
+ SubTrigger,
+} from '@core/component/ContextMenu';
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { ChannelEntity } from '@entity';
+import ChecksIcon from '@icon/system/regular/checks.svg';
+import PencilSimpleIcon from '@icon/system/regular/pencil-simple.svg';
+import PlusIcon from '@icon/system/regular/plus.svg';
+import TagIcon from '@icon/system/regular/tag.svg';
+import TagSimpleIcon from '@icon/system/regular/tag-simple.svg';
+import TrashIcon from '@icon/system/regular/trash.svg';
+import { ContextMenu } from '@kobalte/core/context-menu';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
+import { createDroppable } from '@thisbeyond/solid-dnd';
+import { Badge, cn } from '@ui';
+import { For, type JSX, Show } from 'solid-js';
+import { canLabelChannel } from '../../../core/channel-label-eligibility';
+import { ChannelLabelMenuItems as OriginalChannelLabelMenuItems } from '../ChannelLabelRows';
+import {
+ type ChannelLabelDropData,
+ rowKeyForLabel,
+ useChannelsRail,
+} from '../ChannelsRailContext';
+import { useChannelRailLabelState } from '../hooks/useChannelRailState';
+import { ChannelSectionHeading } from './ChannelSectionHeading';
+import {
+ ChannelSectionContextMenu,
+ ChannelSectionDropdown,
+} from './ChannelSectionMenu';
+
+/** One drop target and highlight around the full custom section. */
+export function ChannelLabelDropZone(props: {
+ label: ChannelLabel;
+ children: JSX.Element;
+}) {
+ const rail = useChannelsRail();
+ const droppable = createDroppable(
+ `${rail.railId}:channel-label:label:${props.label.id}`,
+ {
+ dragType: 'channel-label-target',
+ dndScope: rail.railId,
+ get target() {
+ return {
+ kind: props.label.rule ? ('smart-tag' as const) : ('label' as const),
+ 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 shrink-0 rounded-lg',
+ isDropTarget() && 'bg-selected ring-1 ring-inset ring-accent'
+ )}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+/** A custom section with the same heading and controls as built-in sections. */
+export function ChannelLabelRow(props: { label: ChannelLabel }) {
+ const rail = useChannelsRail();
+ const state = useChannelRailLabelState(() => props.label);
+
+ return (
+ <ChannelSectionContextMenu
+ section={rowKeyForLabel(props.label.id)}
+ actions={<ChannelLabelActions label={props.label} />}
+ >
+ <ChannelSectionHeading
+ id={state().domId}
+ label={props.label.name}
+ title={
+ props.label.rule
+ ? t('channelLabels.nameContains', {
+ text: props.label.rule.contains,
+ })
+ : props.label.name
+ }
+ open={state().open}
+ focused={state().focused}
+ unreadCount={state().unreadCount}
+ onToggle={() => rail.activateRow(rowKeyForLabel(props.label.id))}
+ badge={
+ <Show when={props.label.teamId}>
+ <Badge variant="secondary" size="xs">
+ {t('channelSections.sharedShort')}
+ </Badge>
+ </Show>
+ }
+ >
+ <ChannelSectionDropdown
+ section={rowKeyForLabel(props.label.id)}
+ label={props.label.name}
+ >
+ <ChannelLabelActions label={props.label} />
+ </ChannelSectionDropdown>
+ </ChannelSectionHeading>
+ </ChannelSectionContextMenu>
+ );
+}
+
+function ChannelLabelActions(props: { label: ChannelLabel }) {
+ const rail = useChannelsRail();
+
+ return (
+ <>
+ <MenuSeparator />
+ <MenuGroup>
+ <MenuItem
+ icon={PencilSimpleIcon}
+ text={
+ props.label.rule
+ ? t('channelLabels.editSmartLabel')
+ : t('channelSections.renameSection')
+ }
+ onClick={() =>
+ fireAndForget(rail.renameLabel(props.label), 'channels-view')
+ }
+ />
+ <MenuItem
+ icon={ChecksIcon}
+ text={t('channelLabels.markAllAsRead')}
+ disabled={rail.labelUnreadCount(props.label) === 0}
+ onClick={() => rail.markLabelRead(props.label)}
+ />
+ </MenuGroup>
+ <MenuSeparator />
+ <MenuItem
+ icon={TrashIcon}
+ text={t('channelSections.deleteSection')}
+ class="text-failure"
+ onClick={() =>
+ fireAndForget(rail.deleteLabel(props.label), 'channels-view')
+ }
+ />
+ </>
+ );
+}
+
+/** Moving a personal assignment never changes a shared assignment. */
+function SectionMenuItems(props: { channel: ChannelEntity }) {
+ const rail = useChannelsRail();
+ const labels = () =>
+ rail
+ .labels()
+ .filter((label) => !label.rule && canLabelChannel(props.channel, label));
+
+ return (
+ <Show
+ when={
+ rail.channelTagsEnabled() &&
+ canLabelChannel(props.channel) &&
+ rail.labelsAvailable()
+ }
+ >
+ <For
+ each={labels().filter((label) =>
+ label.channelIds.includes(props.channel.id)
+ )}
+ >
+ {(label) => (
+ <MenuItem
+ icon={TagSimpleIcon}
+ text={t('channelSections.removeFrom', { name: label.name })}
+ onClick={() =>
+ rail.setChannelLabel(props.channel.id, undefined, label.id)
+ }
+ />
+ )}
+ </For>
+ <ContextMenu.Sub>
+ <SubTrigger icon={TagIcon} text={t('channelSections.addToSection')} />
+ <ContextMenuContent
+ submenu
+ class="min-w-56 max-w-[22rem] text-xs text-ink-muted"
+ >
+ <For each={[false, true]}>
+ {(shared) => (
+ <Show
+ when={
+ !shared ||
+ (rail.canShareSections() &&
+ props.channel.channelType === 'team')
+ }
+ >
+ <div class="px-2 py-1 text-xs text-ink-extra-muted">
+ {shared
+ ? t('channelSections.shared')
+ : t('channelSections.personal')}
+ </div>
+ <For
+ each={labels().filter(
+ (label) => Boolean(label.teamId) === shared
+ )}
+ >
+ {(label) => (
+ <MenuItem
+ selectorType="checkbox"
+ checked={label.channelIds.includes(props.channel.id)}
+ text={label.name}
+ onChange={(checked) => {
+ if (checked) {
+ rail.setChannelLabel(props.channel.id, label.id);
+ return;
+ }
+
+ rail.setChannelLabel(
+ props.channel.id,
+ undefined,
+ label.id
+ );
+ }}
+ />
+ )}
+ </For>
+ <MenuItem
+ icon={PlusIcon}
+ text={t('channelSections.newSection')}
+ onClick={() =>
+ fireAndForget(
+ rail.createLabel(
+ [props.channel.id],
+ shared ? 'team' : 'personal'
+ ),
+ 'channels-view'
+ )
+ }
+ />
+ <MenuSeparator />
+ </Show>
+ )}
+ </For>
+ </ContextMenuContent>
+ </ContextMenu.Sub>
+ </Show>
+ );
+}
+
+export function ChannelLabelMenuItems(props: { channel: ChannelEntity }) {
+ const rail = useChannelsRail();
+
+ return (
+ <Show
+ when={rail.sectionsEnabled()}
+ fallback={<OriginalChannelLabelMenuItems channel={props.channel} />}
+ >
+ <SectionMenuItems channel={props.channel} />
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsx
new file mode 100644
index 0000000000..bcdbc1078a
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionHeading.tsx
@@ -0,0 +1,40 @@
+import { CollapsibleSection } from '@app/components/view-shell';
+import { cn } from '@ui';
+import { type JSX, Show } from 'solid-js';
+
+/** Shared heading for built-in and custom Chat sections. */
+export function ChannelSectionHeading(props: {
+ id: string;
+ label: string;
+ title?: string;
+ open: boolean;
+ focused: boolean;
+ unreadCount: number;
+ onToggle: () => void;
+ badge?: JSX.Element;
+ children?: JSX.Element;
+}) {
+ return (
+ <CollapsibleSection.Root open={props.open} onOpenChange={props.onToggle}>
+ <CollapsibleSection.Header
+ class={cn('rounded-lg pr-0', props.focused && 'bg-hover text-ink')}
+ >
+ <CollapsibleSection.Trigger
+ id={props.id}
+ role="treeitem"
+ tabIndex={-1}
+ title={props.title}
+ class={cn('flex-1', props.focused && 'text-ink')}
+ >
+ <span class="min-w-0 truncate">{props.label}</span>
+ {props.badge}
+ <CollapsibleSection.Indicator />
+ <Show when={props.unreadCount > 0}>
+ <span class="text-xs text-accent">{props.unreadCount}</span>
+ </Show>
+ </CollapsibleSection.Trigger>
+ <div class="flex shrink-0 items-center">{props.children}</div>
+ </CollapsibleSection.Header>
+ </CollapsibleSection.Root>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ChannelSectionMenu.tsx b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionMenu.tsx
new file mode 100644
index 0000000000..ac939949c2
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/ChannelSectionMenu.tsx
@@ -0,0 +1,219 @@
+import { ViewSidebar } from '@app/components/view-shell';
+import { t } from '@app/lib/i18n';
+import {
+ ContextMenuContent,
+ ContextMenuTrigger,
+ MENU_ITEM_CLASS,
+ MenuGroup,
+ MenuItem,
+ MenuSeparator,
+ SubTrigger,
+} from '@core/component/ContextMenu';
+import { fireAndForget } from '@core/util/fireAndForget';
+import BellIcon from '@icon/system/regular/bell.svg';
+import BellSlashIcon from '@icon/system/regular/bell-slash.svg';
+import ClockIcon from '@icon/system/regular/clock.svg';
+import SlidersIcon from '@icon/system/regular/sliders-horizontal.svg';
+import { ContextMenu } from '@kobalte/core/context-menu';
+import { DropdownMenu } from '@kobalte/core/dropdown-menu';
+import { Dropdown, SingleSelectCheck, ToggleSwitch } from '@ui';
+import { For, type JSX } from 'solid-js';
+import type {
+ ChannelSectionKey,
+ ChannelSectionPreferences,
+} from '../../../types';
+import { useChannelsRail } from '../ChannelsRailContext';
+
+export function ChannelSectionDropdown(props: {
+ section: ChannelSectionKey;
+ label: string;
+ children?: JSX.Element;
+}) {
+ const label = () => t('channelSections.optionsFor', { name: props.label });
+
+ return (
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ aria-label={label()}
+ tooltip={label()}
+ as={ViewSidebar.Control}
+ variant="ghost"
+ size="icon-sm"
+ onMouseDown={(event: MouseEvent) => event.stopPropagation()}
+ >
+ <SlidersIcon class="size-3.5" />
+ </Dropdown.Trigger>
+ <DropdownMenu.Portal>
+ <ContextMenuContent
+ contentComponent={DropdownMenu.Content}
+ class="min-w-44"
+ onCloseAutoFocus={(event) => {
+ if (document.querySelector('[role="dialog"]')) {
+ event.preventDefault();
+ }
+ }}
+ >
+ <ChannelSectionMenuItems section={props.section} />
+ {props.children}
+ </ContextMenuContent>
+ </DropdownMenu.Portal>
+ </Dropdown>
+ );
+}
+
+/** Share the standard context-menu surface and rows with the click menu. */
+export function ChannelSectionContextMenu(props: {
+ section: ChannelSectionKey;
+ children: JSX.Element;
+ actions?: JSX.Element;
+}) {
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger as="div" class="min-w-0">
+ {props.children}
+ </ContextMenuTrigger>
+ <ContextMenu.Portal>
+ <ContextMenuContent
+ class="min-w-44"
+ onCloseAutoFocus={(event) => {
+ if (document.querySelector('[role="dialog"]')) {
+ event.preventDefault();
+ }
+ }}
+ >
+ <ChannelSectionMenuItems section={props.section} />
+ {props.actions}
+ </ContextMenuContent>
+ </ContextMenu.Portal>
+ </ContextMenu>
+ );
+}
+
+/** Shared personal sort and unread controls for built-in and custom sections. */
+function ChannelSectionMenuItems(props: { section: ChannelSectionKey }) {
+ const rail = useChannelsRail();
+ const preferences = () => rail.sectionPreferences(props.section);
+ const options = () => {
+ const items: {
+ value: NonNullable<ChannelSectionPreferences['sort']>;
+ label: string;
+ }[] = [];
+
+ if (props.section === 'favorites') {
+ items.push({ value: 'manual', label: t('channelSections.customOrder') });
+ }
+
+ if (props.section === 'favorites' || props.section.startsWith('label:')) {
+ items.push({ value: 'name', label: t('channelSections.alphabetical') });
+ }
+
+ items.push(
+ { value: 'viewed_at', label: t('channelSections.lastViewed') },
+ { value: 'updated_at', label: t('channelSections.lastUpdated') },
+ { value: 'created_at', label: t('channelSections.dateCreated') }
+ );
+
+ return items;
+ };
+
+ return (
+ <>
+ <MenuGroup>
+ <ContextMenu.Sub>
+ <SubTrigger text={t('channelSections.sort')} />
+ <ContextMenuContent submenu class="min-w-44">
+ <MenuGroup>
+ <ContextMenu.RadioGroup
+ value={preferences().sort}
+ onChange={(value) => {
+ const option = options().find(
+ (option) => option.value === value
+ );
+
+ if (option) {
+ rail.setSectionPreferences(props.section, {
+ sort: option.value,
+ });
+ }
+ }}
+ >
+ <For each={options()}>
+ {(option) => (
+ <ContextMenu.RadioItem
+ class={MENU_ITEM_CLASS}
+ value={option.value}
+ closeOnSelect
+ >
+ <span class="flex-1">{option.label}</span>
+ <SingleSelectCheck
+ active={preferences().sort === option.value}
+ />
+ </ContextMenu.RadioItem>
+ )}
+ </For>
+ </ContextMenu.RadioGroup>
+ </MenuGroup>
+ </ContextMenuContent>
+ </ContextMenu.Sub>
+ <ContextMenu.Sub>
+ <SubTrigger text={t('channelSections.filter')} />
+ <ContextMenuContent submenu class="min-w-44">
+ <ContextMenu.CheckboxItem
+ class={MENU_ITEM_CLASS}
+ closeOnSelect={false}
+ checked={preferences().unreadOnly ?? false}
+ onChange={(unreadOnly) =>
+ rail.setSectionPreferences(props.section, { unreadOnly })
+ }
+ >
+ <span class="flex-1">{t('channelSections.unreadOnly')}</span>
+ <span
+ inert
+ aria-hidden="true"
+ class="pointer-events-none flex shrink-0 items-center"
+ >
+ <ToggleSwitch
+ checked={preferences().unreadOnly ?? false}
+ readOnly
+ />
+ </span>
+ </ContextMenu.CheckboxItem>
+ </ContextMenuContent>
+ </ContextMenu.Sub>
+ </MenuGroup>
+ <MenuSeparator />
+ <MenuGroup>
+ <MenuItem
+ icon={BellSlashIcon}
+ text={t('channelSections.muteAllChannels')}
+ disabled={rail.sectionNotificationsDisabled(props.section)}
+ onClick={() =>
+ fireAndForget(
+ rail.muteSection(props.section, true),
+ 'channels-view'
+ )
+ }
+ />
+ <MenuItem
+ icon={BellIcon}
+ text={t('channelSections.unmuteAllChannels')}
+ disabled={rail.sectionNotificationsDisabled(props.section)}
+ onClick={() =>
+ fireAndForget(
+ rail.muteSection(props.section, false),
+ 'channels-view'
+ )
+ }
+ />
+ <MenuItem
+ icon={ClockIcon}
+ text={t('channelSections.snoozeAllChannels')}
+ disabled={rail.sectionNotificationsDisabled(props.section)}
+ onClick={() =>
+ fireAndForget(rail.snoozeSection(props.section), 'channels-view')
+ }
+ />
+ </MenuGroup>
+ </>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx b/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx
new file mode 100644
index 0000000000..7028ffe77f
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/ExpandedChannelsRail.tsx
@@ -0,0 +1,629 @@
+import { SearchBar, ViewSidebar } from '@app/components/view-shell';
+import { SlackImportSidebar } from '@app/features/slack-import/slack-import-sidebar';
+import { t } from '@app/lib/i18n';
+import { createScrollTopFade } from '@core/util/createScrollTopFade';
+import { fireAndForget } from '@core/util/fireAndForget';
+import type { ChannelEntity } from '@entity';
+import { queryReadyGate } from '@queries/gate';
+import { useCurrentTeamQuery } from '@queries/team/teams';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { Button } from '@ui';
+import { tourTarget } from '@ui/components/Tour';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ For,
+ Match,
+ on,
+ onCleanup,
+ Show,
+ Switch,
+} from 'solid-js';
+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
+import {
+ CHANNEL_SECTION_MIN_HEIGHT,
+ CHANNEL_SECTION_ROW_HEIGHT,
+} from '../../../constants';
+import { canLabelChannel } from '../../../core/channel-label-eligibility';
+import { ChannelsLiveCallsSidebar } from '../../../live-calls-sidebar';
+import { CHANNELS_TOUR } from '../../../tour';
+import type { ChannelSectionKey, ChannelsGroup } from '../../../types';
+import { ConversationsCreateMenu } from '../../ConversationsCreateMenu';
+import { ChannelOption } from '../ChannelOption';
+import {
+ type ChannelRailRow,
+ domIdForRow,
+ rowKeyForSection,
+ useChannelsRail,
+} from '../ChannelsRailContext';
+import {
+ RailListError,
+ RailListLoading,
+ RailListLoadingMore,
+} from '../ChannelsRailSection';
+import { useChannelRailVirtualizer } from '../hooks/useChannelRailState';
+import {
+ type ChannelRailSectionRows,
+ groupChannelRailSections,
+} from './build-channel-rail-rows';
+import { ChannelFavoriteRow } from './ChannelFavoriteRow';
+import { ChannelLabelDropZone, ChannelLabelRow } from './ChannelLabelRows';
+import { ChannelSectionHeading } from './ChannelSectionHeading';
+import {
+ ChannelSectionContextMenu,
+ ChannelSectionDropdown,
+} from './ChannelSectionMenu';
+import { ResizableRailSection } from './ResizableRailSection';
+import { useFavoriteReorder } from './useFavoriteReorder';
+
+type ChannelRailSearch = {
+ isOpen: Accessor<boolean>;
+ query: Accessor<string>;
+ results: Accessor<readonly ChannelEntity[]>;
+ isLoading: Accessor<boolean>;
+ error: Accessor<unknown | undefined>;
+ open: () => void;
+ close: () => void;
+ setQuery: (query: string) => void;
+ registerInput: (element: HTMLInputElement) => void;
+ retry: () => Promise<void>;
+};
+
+function ExpandedHeader(props: { search: ChannelRailSearch }) {
+ const rail = useChannelsRail();
+
+ return (
+ <div class="flex shrink-0 flex-col">
+ <ViewSidebar.Header
+ searchLabel={t('channelSections.search')}
+ searchOpen={props.search.isOpen()}
+ onSearchOpenChange={(open) => {
+ if (open) {
+ props.search.open();
+ } else {
+ props.search.close();
+ }
+ }}
+ search={() => (
+ <SearchBar
+ ref={props.search.registerInput}
+ label={t('channelSections.search')}
+ placeholder={t('channelSections.search')}
+ value={props.search.query()}
+ hotkey="cmd+f"
+ onValueChange={props.search.setQuery}
+ onEscape={() => {
+ if (!props.search.query()) {
+ props.search.close();
+ }
+ }}
+ />
+ )}
+ >
+ <div class="flex min-w-0 items-center gap-1">
+ <ViewSidebar.CloseButton />
+ <ViewSidebar.Title>{t('channelSections.chat')}</ViewSidebar.Title>
+ </div>
+ </ViewSidebar.Header>
+ <ViewSidebar.Primary class="flex items-center gap-2">
+ <div class="min-w-0 flex-1">
+ <ConversationsCreateMenu
+ presentation="sidebar"
+ onCreateSection={
+ rail.channelTagsEnabled()
+ ? () => fireAndForget(rail.createLabel([]), 'channels-view')
+ : undefined
+ }
+ sectionDisabledReason={
+ !rail.labelsAvailable()
+ ? rail.labelsUnavailableReason()
+ : undefined
+ }
+ />
+ </div>
+ </ViewSidebar.Primary>
+ <Show when={rail.channelTagsEnabled() && !rail.labelsAvailable()}>
+ <div
+ class="flex items-center gap-2 px-3 text-xs text-ink-muted"
+ role="status"
+ >
+ <span class="min-w-0 flex-1">{rail.labelsUnavailableReason()}</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => fireAndForget(rail.retryLabels(), 'channels-view')}
+ >
+ {t('channelSections.retry')}
+ </Button>
+ </div>
+ </Show>
+ </div>
+ );
+}
+
+function SectionHeading(props: { group: 'favorites' | ChannelsGroup }) {
+ const rail = useChannelsRail();
+ const team = useCurrentTeamQuery(() => props.group === 'team_channels');
+ const title = () => {
+ if (props.group === 'team_channels' && queryReadyGate(team)) {
+ const teamName = team.data?.team.name;
+
+ if (teamName) {
+ return t('channelSections.namedTeamChannels', { name: teamName });
+ }
+ }
+
+ return t(`channelSections.${props.group}`);
+ };
+
+ const open = () => rail.isGroupOpen(props.group);
+ const key = () => rowKeyForSection(props.group);
+ const channelGroup = () =>
+ props.group === 'favorites' ? undefined : props.group;
+ const unreadCount = () => {
+ const group = channelGroup();
+ return group ? rail.channelActivity.unreadCount(group) : 0;
+ };
+
+ return (
+ <ChannelSectionContextMenu section={props.group}>
+ <ChannelSectionHeading
+ id={domIdForRow(rail.railId, key())}
+ title={title()}
+ label={title()}
+ open={open()}
+ focused={rail.list.focus.key() === key()}
+ unreadCount={unreadCount()}
+ onToggle={() => rail.toggleGroup(props.group)}
+ >
+ <ChannelSectionDropdown section={props.group} label={title()} />
+ </ChannelSectionHeading>
+ </ChannelSectionContextMenu>
+ );
+}
+
+function SectionStatus(props: { group: ChannelsGroup }) {
+ const rail = useChannelsRail();
+ const source = () => rail.sources[props.group];
+ const hasConversations = () =>
+ rail.list.items
+ .all()
+ .some(
+ (row) =>
+ row.kind === 'conversation' &&
+ row.group === props.group &&
+ !row.labelId
+ );
+
+ return (
+ <div>
+ <Switch>
+ <Match when={source().isLoading() || source().isLoadingMore()}>
+ <RailListLoadingMore variant="channel" />
+ </Match>
+ <Match when={source().error()}>
+ <RailListError retry={source().refresh} compact />
+ </Match>
+ <Match when={source().hasMore()}>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => fireAndForget(source().loadMore(), 'channels-view')}
+ >
+ {t('channelSections.loadMore')}
+ </Button>
+ </Match>
+ <Match when={!hasConversations()}>
+ <p class="px-(--sidebar-item-inset) py-2 text-xs text-ink-extra-muted">
+ {rail.sectionPreferences(props.group).unreadOnly
+ ? t('channelSections.noUnreadConversations')
+ : t('channelSections.empty')}
+ </p>
+ </Match>
+ </Switch>
+ </div>
+ );
+}
+
+function BrowseRow(props: {
+ row: ChannelRailRow;
+ favoriteReorder: ReturnType<typeof useFavoriteReorder>;
+}) {
+ const rail = useChannelsRail();
+
+ return (
+ <div
+ classList={{
+ 'pl-2': props.row.kind !== 'section' && props.row.kind !== 'label',
+ }}
+ >
+ <Switch>
+ <Match when={props.row.kind === 'section' ? props.row : undefined}>
+ {(row) => <SectionHeading group={row().group} />}
+ </Match>
+ <Match when={props.row.kind === 'status' ? props.row : undefined}>
+ {(row) => <SectionStatus group={row().group} />}
+ </Match>
+ <Match
+ when={props.row.kind === 'reference-status' ? props.row : undefined}
+ >
+ {(row) => (
+ <Show
+ when={row().state === 'loading'}
+ fallback={
+ <RailListError retry={rail.retryReferencedChannels} compact />
+ }
+ >
+ <RailListLoadingMore variant="channel" />
+ </Show>
+ )}
+ </Match>
+ <Match when={props.row.kind === 'label' ? props.row : undefined}>
+ {(row) => <ChannelLabelRow label={row().label} />}
+ </Match>
+ <Match when={props.row.kind === 'favorite' ? props.row : undefined}>
+ {(row) => (
+ <ChannelFavoriteRow
+ favorite={row().favorite}
+ reorder={props.favoriteReorder}
+ />
+ )}
+ </Match>
+ <Match when={props.row.kind === 'conversation' ? props.row : undefined}>
+ {(row) => (
+ <ChannelOption
+ channel={row().channel}
+ rowId={row().id}
+ labelId={row().labelId}
+ draggable={canLabelChannel(row().channel)}
+ />
+ )}
+ </Match>
+ </Switch>
+ </div>
+ );
+}
+
+type SectionHandle = {
+ root?: HTMLDivElement;
+ virtualizer?: VirtualizerHandle;
+};
+
+function BrowseSection(props: {
+ sectionKey: ChannelSectionKey;
+ section: ChannelRailSectionRows;
+ maxHeight: number;
+ favoriteReorder: ReturnType<typeof useFavoriteReorder>;
+ register: (key: ChannelSectionKey, handle: SectionHandle) => () => void;
+}) {
+ const rail = useChannelsRail();
+ const handle: SectionHandle = {};
+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
+ const [virtualizer, setVirtualizer] = createSignal<VirtualizerHandle>();
+ const size = createElementSize(scrollRoot);
+
+ onCleanup(props.register(props.sectionKey, handle));
+
+ const heading = () => props.section.heading;
+ const open = () => {
+ const row = heading();
+ return row.kind === 'label'
+ ? rail.isLabelOpen(row.label.id)
+ : rail.isGroupOpen(row.group);
+ };
+
+ const label = () => {
+ const row = heading();
+ return row.kind === 'label'
+ ? row.label.name
+ : t(`channelSections.${row.group}`);
+ };
+
+ const emptyMessage = () => {
+ if (rail.sectionPreferences(props.sectionKey).unreadOnly) {
+ return t('channelSections.noUnreadConversations');
+ }
+
+ const row = heading();
+
+ if (row.kind === 'section') {
+ return t('channelSections.emptyFavorites');
+ }
+
+ return row.label.rule
+ ? t('channelSections.emptySmartSection')
+ : t('channelSections.emptySection');
+ };
+
+ const focusIndex = () =>
+ props.section.rows.findIndex((row) => row.id === rail.list.focus.key());
+ const loadVisibleSections = () => {
+ const current = virtualizer();
+
+ if (!open() || !current) {
+ return;
+ }
+
+ const first = current.findItemIndex(
+ Math.max(0, current.scrollOffset - 100)
+ );
+ const last = current.findItemIndex(
+ current.scrollOffset + current.viewportSize + 150
+ );
+
+ for (const row of props.section.rows.slice(first, last + 1)) {
+ if (row.kind !== 'status') {
+ continue;
+ }
+
+ const source = rail.sources[row.group];
+
+ if (source.hasMore() && !source.isFetching() && !source.error()) {
+ fireAndForget(source.loadMore(), 'channels-view');
+ }
+ }
+ };
+
+ createEffect(
+ on([() => props.section.rows, open, virtualizer, () => size.height], () => {
+ if (!open()) {
+ return;
+ }
+
+ const frame = requestAnimationFrame(loadVisibleSections);
+ onCleanup(() => cancelAnimationFrame(frame));
+ })
+ );
+
+ const content = (
+ <ResizableRailSection
+ section={props.sectionKey}
+ label={label()}
+ open={open()}
+ maxHeight={props.maxHeight}
+ itemCount={
+ props.section.rows.filter(
+ (row) => row.kind === 'conversation' || row.kind === 'favorite'
+ ).length
+ }
+ rootRef={(element) => {
+ handle.root = element;
+ }}
+ scrollRef={(element) => {
+ setScrollRoot(element);
+
+ const row = heading();
+
+ if (row.kind === 'section') {
+ rail.registerScrollRef(row.group, element);
+ }
+ }}
+ header={
+ <BrowseRow row={heading()} favoriteReorder={props.favoriteReorder} />
+ }
+ >
+ <Show
+ when={props.section.rows.length > 0}
+ fallback={
+ <p class="py-2 pr-2 pl-4 text-xs text-ink-extra-muted">
+ {emptyMessage()}
+ </p>
+ }
+ >
+ <Virtualizer
+ ref={(current) => {
+ handle.virtualizer = current;
+ setVirtualizer(current);
+ }}
+ data={props.section.rows}
+ scrollRef={scrollRoot()}
+ itemSize={CHANNEL_SECTION_ROW_HEIGHT}
+ bufferSize={200}
+ keepMounted={focusIndex() >= 0 ? [focusIndex()] : undefined}
+ onScroll={loadVisibleSections}
+ >
+ {(row) => (
+ <BrowseRow row={row} favoriteReorder={props.favoriteReorder} />
+ )}
+ </Virtualizer>
+ </Show>
+ </ResizableRailSection>
+ );
+
+ return (
+ <Show
+ when={
+ props.section.heading.kind === 'label'
+ ? props.section.heading.label
+ : undefined
+ }
+ fallback={content}
+ >
+ {(label) => (
+ <ChannelLabelDropZone label={label()}>{content}</ChannelLabelDropZone>
+ )}
+ </Show>
+ );
+}
+
+function ExpandedBrowse() {
+ const rail = useChannelsRail();
+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
+ const scrollSize = createElementSize(scrollRoot);
+ const sections = createMemo(() =>
+ groupChannelRailSections(rail.list.items.all())
+ );
+ const keys = createMemo(() => [...sections().keys()]);
+ const handles = new Map<ChannelSectionKey, SectionHandle>();
+ const favoriteReorder = useFavoriteReorder(
+ () =>
+ sections()
+ .get('favorites')
+ ?.rows.flatMap((row) =>
+ row.kind === 'favorite' ? [row.favorite] : []
+ ) ?? []
+ );
+
+ createScrollTopFade(scrollRoot);
+
+ const register = (key: ChannelSectionKey, handle: SectionHandle) => {
+ handles.set(key, handle);
+
+ return () => {
+ if (handles.get(key) === handle) {
+ handles.delete(key);
+ }
+ };
+ };
+
+ onCleanup(
+ rail.registerBrowseScrollHandle({
+ scrollToIndex: (index, options) => {
+ const row = rail.list.items.at(index);
+
+ if (!row) {
+ return;
+ }
+
+ for (const [key, section] of sections()) {
+ const localIndex = section.rows.findIndex(
+ (item) => item.id === row.id
+ );
+
+ if (section.heading.id !== row.id && localIndex < 0) {
+ continue;
+ }
+
+ const handle = handles.get(key);
+
+ if (!handle) {
+ return;
+ }
+
+ if (localIndex >= 0) {
+ handle.virtualizer?.scrollToIndex(localIndex, options);
+ }
+
+ const container = scrollRoot();
+ if (container && handle.root) {
+ const bounds = handle.root.getBoundingClientRect();
+ const viewport = container.getBoundingClientRect();
+
+ if (bounds.top < viewport.top) {
+ container.scrollTop += bounds.top - viewport.top;
+ } else if (bounds.bottom > viewport.bottom) {
+ container.scrollTop += bounds.bottom - viewport.bottom;
+ }
+ }
+
+ return;
+ }
+ },
+ })
+ );
+
+ return (
+ <div class="flex min-h-0 flex-1 flex-col">
+ <div
+ ref={setScrollRoot}
+ class="scrollbar-hidden flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-(--sidebar-gutter)"
+ >
+ <For each={keys()}>
+ {(key) => (
+ <Show when={sections().get(key)}>
+ {(section) => (
+ <BrowseSection
+ sectionKey={key}
+ section={section()}
+ maxHeight={Math.max(
+ CHANNEL_SECTION_MIN_HEIGHT,
+ (scrollSize.height ?? 300) - 48
+ )}
+ favoriteReorder={favoriteReorder}
+ register={register}
+ />
+ )}
+ </Show>
+ )}
+ </For>
+ </div>
+ </div>
+ );
+}
+
+function ExpandedSearchResults(props: { search: ChannelRailSearch }) {
+ const [scrollRoot, setScrollRoot] = createSignal<HTMLDivElement>();
+ const pagination = useChannelRailVirtualizer(() => 'search');
+
+ createScrollTopFade(scrollRoot);
+
+ return (
+ <div
+ ref={setScrollRoot}
+ class="scrollbar-hidden min-h-0 flex-1 overflow-y-auto px-(--sidebar-gutter)"
+ >
+ <Show
+ when={props.search.isLoading() && props.search.results().length === 0}
+ >
+ <RailListLoading />
+ </Show>
+ <Show when={props.search.error()}>
+ <RailListError retry={props.search.retry} />
+ </Show>
+ <Virtualizer
+ ref={pagination.registerVirtualizer}
+ data={props.search.results()}
+ scrollRef={scrollRoot()}
+ itemSize={CHANNEL_SECTION_ROW_HEIGHT}
+ onScroll={pagination.loadMoreNearEnd}
+ >
+ {(channel) => <ChannelOption channel={channel} />}
+ </Virtualizer>
+ <Show
+ when={
+ !props.search.isLoading() &&
+ !props.search.error() &&
+ props.search.results().length === 0
+ }
+ >
+ <p class="px-2 py-6 text-center text-sm text-ink-muted">
+ {t('channelSections.noResults')}
+ </p>
+ </Show>
+ </div>
+ );
+}
+
+export function ExpandedChannelsRail(props: { search: ChannelRailSearch }) {
+ const rail = useChannelsRail();
+ const listTarget = tourTarget(CHANNELS_TOUR.list);
+
+ return (
+ <>
+ <ExpandedHeader search={props.search} />
+ <ChannelsLiveCallsSidebar />
+ <div
+ ref={(element) => {
+ rail.registerRootRef(element);
+ listTarget(element);
+ }}
+ role="tree"
+ tabIndex={-1}
+ aria-label={t('channelSections.conversations')}
+ aria-activedescendant={
+ rail.list.focus.key()
+ ? domIdForRow(rail.railId, rail.list.focus.key()!)
+ : undefined
+ }
+ class="flex min-h-0 flex-1 flex-col outline-none"
+ >
+ <Show when={props.search.isOpen()} fallback={<ExpandedBrowse />}>
+ <ExpandedSearchResults search={props.search} />
+ </Show>
+ </div>
+ <SlackImportSidebar />
+ </>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx b/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx
new file mode 100644
index 0000000000..fc18e7346a
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/ResizableRailSection.tsx
@@ -0,0 +1,205 @@
+import { t } from '@app/lib/i18n';
+import { useUserId } from '@core/context/user';
+import { createElementSize } from '@solid-primitives/resize-observer';
+import { createMemo, createSignal, type JSX, onCleanup, Show } from 'solid-js';
+import {
+ CHANNEL_SECTION_MAX_HEIGHT,
+ CHANNEL_SECTION_MIN_HEIGHT,
+ CHANNEL_SECTION_MIN_ITEMS,
+ CHANNEL_SECTION_ROW_HEIGHT,
+ clampChannelSectionHeight,
+} from '../../../constants';
+import type { ChannelSectionKey } from '../../../types';
+import { useChannelsRail } from '../ChannelsRailContext';
+
+/** Preview resizing locally; persist the final height with the section's preferences. */
+export function ResizableRailSection(props: {
+ section: ChannelSectionKey;
+ label: string;
+ open: boolean;
+ maxHeight: number;
+ itemCount: number;
+ header: JSX.Element;
+ children: JSX.Element;
+ rootRef: (element: HTMLDivElement) => void;
+ scrollRef: (element: HTMLDivElement) => void;
+}) {
+ const rail = useChannelsRail();
+ const userId = useUserId();
+ const account = createMemo(() => ({ id: userId() }));
+ const [viewport, setViewport] = createSignal<HTMLDivElement>();
+ const [content, setContent] = createSignal<HTMLDivElement>();
+ const contentSize = createElementSize(content);
+ const [preview, setPreview] = createSignal<number>();
+
+ const maximum = () =>
+ Math.min(
+ CHANNEL_SECTION_MAX_HEIGHT,
+ props.maxHeight,
+ contentSize.height ??
+ Math.max(1, props.itemCount) * CHANNEL_SECTION_ROW_HEIGHT
+ );
+ const resizable = () =>
+ props.itemCount > CHANNEL_SECTION_MIN_ITEMS &&
+ maximum() > CHANNEL_SECTION_MIN_HEIGHT;
+ const defaultHeight = () => {
+ if (props.section === 'favorites' || props.section === 'direct_messages') {
+ return Math.min(maximum(), 4 * CHANNEL_SECTION_ROW_HEIGHT);
+ }
+
+ return maximum();
+ };
+
+ const clamp = (height: number) =>
+ Math.min(maximum(), clampChannelSectionHeight(height));
+ const height = () => {
+ if (!resizable()) {
+ return maximum();
+ }
+
+ return clamp(
+ preview() ??
+ rail.sectionPreferences(props.section).height ??
+ defaultHeight()
+ );
+ };
+
+ let drag:
+ | {
+ pointer: number;
+ y: number;
+ height: number;
+ zoom: number;
+ account: ReturnType<typeof account>;
+ }
+ | undefined;
+
+ const finish = (event: PointerEvent, cancelled = false) => {
+ if (!drag || event.pointerId !== drag.pointer) {
+ return;
+ }
+
+ const current = drag;
+ drag = undefined;
+
+ if (
+ !cancelled &&
+ props.open &&
+ resizable() &&
+ current.account === account()
+ ) {
+ rail.setSectionPreferences(props.section, {
+ height: clamp(
+ current.height + (event.clientY - current.y) / current.zoom
+ ),
+ });
+ }
+
+ setPreview(undefined);
+ };
+
+ return (
+ <div ref={props.rootRef} class="min-w-0 shrink-0">
+ {props.header}
+ <Show when={props.open}>
+ <div
+ ref={(element) => {
+ setViewport(element);
+ props.scrollRef(element);
+ }}
+ class="min-h-0 overflow-y-auto"
+ style={{ height: `${height()}px` }}
+ >
+ <div ref={setContent} data-section-content>
+ {props.children}
+ </div>
+ </div>
+ <Show when={resizable()}>
+ {(_resizable) => {
+ onCleanup(() => {
+ drag = undefined;
+ setPreview(undefined);
+ });
+
+ return (
+ <button
+ type="button"
+ role="separator"
+ aria-orientation="horizontal"
+ aria-label={t('channelSections.resizeSection', {
+ name: props.label,
+ })}
+ aria-valuemin={CHANNEL_SECTION_MIN_HEIGHT}
+ aria-valuemax={maximum()}
+ aria-valuenow={Math.round(height())}
+ title={t('channelSections.resizeSectionHint')}
+ class="group flex h-3 w-full touch-none cursor-row-resize items-center justify-center outline-none hover:bg-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-edge-focus"
+ onPointerDown={(event) => {
+ const element = viewport();
+ if (event.button !== 0 || !element || drag) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ drag = {
+ pointer: event.pointerId,
+ y: event.clientY,
+ height: element.offsetHeight,
+ zoom:
+ element.getBoundingClientRect().height /
+ element.offsetHeight || 1,
+ account: account(),
+ };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }}
+ onPointerMove={(event) => {
+ if (!drag || event.pointerId !== drag.pointer) {
+ return;
+ }
+
+ if (drag.account !== account()) {
+ finish(event, true);
+ return;
+ }
+
+ setPreview(
+ clamp(drag.height + (event.clientY - drag.y) / drag.zoom)
+ );
+ }}
+ onPointerUp={(event) => finish(event)}
+ onPointerCancel={(event) => finish(event, true)}
+ onLostPointerCapture={(event) => finish(event, true)}
+ onMouseDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ onDblClick={() =>
+ rail.setSectionPreferences(props.section, {
+ height: undefined,
+ })
+ }
+ onKeyDown={(event) => {
+ if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ event.stopImmediatePropagation();
+
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
+ const step = event.shiftKey ? 100 : 20;
+
+ rail.setSectionPreferences(props.section, {
+ height: clamp(height() + direction * step),
+ });
+ }}
+ >
+ <span class="h-0.5 w-8 rounded-full bg-edge-muted group-hover:bg-accent group-focus-visible:bg-accent" />
+ </button>
+ );
+ }}
+ </Show>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx b/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx
new file mode 100644
index 0000000000..18dae344f4
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/SectionDialog.tsx
@@ -0,0 +1,316 @@
+import { t } from '@app/lib/i18n';
+import { fireAndForget } from '@core/util/fireAndForget';
+import HashIcon from '@icon/system/regular/hash.svg';
+import { useSmartTagPreviewQuery } from '@queries/channel-labels/channel-labels';
+import type { ChannelLabelRule } from '@service-storage/generated/schemas/channelLabelRule';
+import type { ChannelLabelScopeSelection } from '@service-storage/generated/schemas/channelLabelScopeSelection';
+import {
+ Button,
+ Dialog,
+ Input,
+ type ManagedDialogProps,
+ type OpenDialogOptions,
+ openDialog,
+ Surface,
+ ToggleSwitch,
+} from '@ui';
+import { type Accessor, createSignal, For, Show } from 'solid-js';
+
+export type SectionDialogValue = {
+ name: string;
+ scope: ChannelLabelScopeSelection;
+ rule?: ChannelLabelRule;
+};
+
+export type SectionDialogProps = {
+ scope?: ChannelLabelScopeSelection;
+ canShare: boolean;
+ initial?: { name: string; rule?: ChannelLabelRule };
+ onConfirm: (value: SectionDialogValue) => Promise<void>;
+};
+
+function SmartSectionPreview(props: {
+ pattern: Accessor<string>;
+ scope: ChannelLabelScopeSelection;
+}) {
+ const preview = useSmartTagPreviewQuery(props.pattern, props.scope);
+ const data = () => (preview.isSuccess ? preview.data : undefined);
+ const matches = () => data()?.channels ?? [];
+ const totalCount = () => data()?.totalCount ?? 0;
+ const overflowCount = () => totalCount() - matches().length;
+
+ return (
+ <section
+ aria-label={t('channelSections.matchedChannels')}
+ 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>{t('channelSections.matchedChannels')}</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">
+ {t('channelSections.matchingChannelsLoading')}
+ </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>{t('channelSections.matchesUnavailable')}</span>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ fireAndForget(preview.refetch(), 'channels-view')
+ }
+ >
+ {t('channelSections.retry')}
+ </Button>
+ </div>
+ }
+ >
+ <Show
+ when={totalCount()}
+ fallback={
+ <p class="px-2 py-2 text-xs text-ink-muted">
+ {t('channelSections.noMatchingChannels')}
+ </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">
+ {t('channelSections.moreChannelsMatched', {
+ count: overflowCount(),
+ })}
+ </p>
+ </Show>
+ </Show>
+ </Show>
+ </Show>
+ </section>
+ );
+}
+
+function SectionDialog(props: SectionDialogProps & ManagedDialogProps) {
+ const [name, setName] = createSignal(props.initial?.name ?? '');
+ const [scope, setScope] = createSignal<ChannelLabelScopeSelection>(
+ props.scope ?? 'personal'
+ );
+ const [kind, setKind] = createSignal<'manual' | 'smart'>(
+ props.initial?.rule ? 'smart' : 'manual'
+ );
+ const [pattern, setPattern] = createSignal(
+ props.initial?.rule?.contains ?? ''
+ );
+ const [saving, setSaving] = createSignal(false);
+ const [error, setError] = createSignal('');
+
+ const trimmedPattern = () => pattern().trim();
+ const canSubmit = () => {
+ if (name().trim().length === 0) {
+ return false;
+ }
+
+ if (kind() !== 'manual' && trimmedPattern().length === 0) {
+ return false;
+ }
+
+ if (!props.initial || name().trim() !== props.initial.name.trim()) {
+ return true;
+ }
+
+ return (
+ kind() === 'smart' && trimmedPattern() !== props.initial.rule?.contains
+ );
+ };
+
+ const submitLabel = () => {
+ if (saving()) {
+ return t('channelSections.saving');
+ }
+
+ return props.initial
+ ? t('channelSections.saveSection')
+ : t('channelSections.createSection');
+ };
+
+ const submit = async (event: SubmitEvent) => {
+ event.preventDefault();
+
+ if (!canSubmit() || saving()) {
+ return;
+ }
+
+ setSaving(true);
+ setError('');
+
+ try {
+ const value: SectionDialogValue = {
+ name: name().trim(),
+ scope: scope(),
+ };
+
+ if (kind() === 'smart') {
+ value.rule = { attribute: 'name', contains: trimmedPattern() };
+ }
+
+ await props.onConfirm(value);
+ props.onOpenChange(false);
+ } catch (error) {
+ setError(
+ error instanceof Error
+ ? error.message
+ : t('channelSections.saveSectionFailed')
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={(open) => {
+ if (!saving()) {
+ props.onOpenChange(open);
+ }
+ }}
+ class="w-[min(36rem,90vw)]"
+ visibleScrim
+ >
+ <Surface
+ depth={2}
+ class="flex max-h-[75dvh] flex-col overflow-y-auto rounded-xl text-ink"
+ >
+ <form
+ onSubmit={(event) => fireAndForget(submit(event), 'channels-view')}
+ aria-busy={saving()}
+ >
+ <div class="flex flex-col gap-4 px-5 py-4">
+ <div class="flex flex-col gap-1">
+ <Dialog.Title class="text-base font-semibold">
+ {props.initial
+ ? t('channelSections.editSection')
+ : t('channelSections.newSection')}
+ </Dialog.Title>
+ <Dialog.Description class="text-sm leading-5 text-ink-muted">
+ {t('channelSections.sectionDescription')}
+ </Dialog.Description>
+ </div>
+ <Input
+ aria-label={t('channelSections.sectionName')}
+ readOnly={saving()}
+ onFocus={(event) => event.currentTarget.select()}
+ placeholder={t('channelSections.sectionName')}
+ value={name()}
+ maxLength={80}
+ onInput={(event) => setName(event.currentTarget.value)}
+ />
+ <Show when={!props.initial}>
+ <ToggleSwitch
+ label={t('channelSections.newSmartSection')}
+ labelClass="text-sm text-ink"
+ checked={kind() === 'smart'}
+ onChange={(checked) => setKind(checked ? 'smart' : 'manual')}
+ disabled={saving()}
+ />
+ </Show>
+ <Show when={kind() === 'smart'}>
+ <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">
+ {t('channelSections.nameContains')}
+ </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={t('channelSections.patternExample')}
+ readOnly={saving()}
+ />
+ </label>
+ </Show>
+ <Show when={error()}>
+ <p role="alert" class="text-sm text-failure">
+ {error()}
+ </p>
+ </Show>
+ <Show when={kind() === 'smart' && trimmedPattern().length > 0}>
+ <Show when={scope()} keyed>
+ {(selectedScope) => (
+ <SmartSectionPreview
+ pattern={trimmedPattern}
+ scope={selectedScope}
+ />
+ )}
+ </Show>
+ </Show>
+ </div>
+ <div class="flex flex-wrap items-center justify-end gap-3 px-5 py-3">
+ <Show when={!props.initial && props.canShare}>
+ <ToggleSwitch
+ class="mr-auto shrink-0"
+ label={t('channelSections.shared')}
+ labelClass="text-xs text-ink-muted font-normal whitespace-nowrap"
+ checked={scope() === 'team'}
+ onChange={(checked) => setScope(checked ? 'team' : 'personal')}
+ disabled={saving()}
+ />
+ </Show>
+ <div class="ml-auto flex shrink-0 items-center gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={saving()}
+ onClick={() => props.onOpenChange(false)}
+ >
+ {t('channelSections.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ variant="primary"
+ disabled={!canSubmit() || saving()}
+ >
+ {submitLabel()}
+ </Button>
+ </div>
+ </div>
+ </form>
+ </Surface>
+ </Dialog>
+ );
+}
+
+export async function promptSection(
+ props: SectionDialogProps,
+ options?: OpenDialogOptions
+): Promise<void> {
+ const handle = openDialog(SectionDialog, props, options);
+ await handle.closed;
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts b/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts
new file mode 100644
index 0000000000..20541ef613
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/build-channel-rail-rows.ts
@@ -0,0 +1,416 @@
+import type { ChannelEntity } from '@entity';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { canLabelChannel } from '../../../core/channel-label-eligibility';
+import { sortChannels } from '../../../core/channel-sort';
+import type { ChannelsSourceScope } from '../../../queries';
+import type {
+ ChannelSectionKey,
+ ChannelSectionPreferences,
+ ChannelsQueryScope,
+ ChannelsRailSection,
+ ChannelsTab,
+} from '../../../types';
+import {
+ ALL_THREADS_ROW_ID,
+ type ChannelRailRow,
+ type ChannelSectionRow,
+ rowKeyForChannel,
+ rowKeyForFavorite,
+ rowKeyForLabel,
+} from '../ChannelsRailContext';
+
+export type ChannelRailItemsByScope = Record<
+ ChannelsQueryScope | 'threads',
+ readonly ChannelEntity[]
+> & {
+ favorites: readonly Favorite[];
+};
+
+const compareChannelName = (left: ChannelEntity, right: ChannelEntity) =>
+ left.name.localeCompare(right.name, undefined, { sensitivity: 'base' }) ||
+ left.id.localeCompare(right.id);
+
+/**
+ * Lay out top-level custom sections with their visible channels in A→Z order.
+ * Ungrouped channels remain available to the primary sections.
+ * 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 && canLabelChannel(channel, label)
+ )
+ .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;
+}
+
+type SectionOptions = {
+ preferences: Partial<Record<ChannelSectionKey, ChannelSectionPreferences>>;
+ channelById: (id: string) => ChannelEntity | undefined;
+ unreadChannelIds: ReadonlySet<string>;
+ /** Referenced-channel feedback; include custom sections only while expanded. */
+ referenceStatuses?: Partial<Record<ChannelSectionKey, 'loading' | 'error'>>;
+};
+
+/** Filter after assigning membership so hidden channels never leak into another section. */
+function applySectionPreferences(
+ rows: ChannelRailRow[],
+ options: SectionOptions
+): ChannelRailRow[] {
+ const result: ChannelRailRow[] = [];
+ let section: ChannelSectionKey | undefined;
+ let entries: ChannelRailRow[] = [];
+
+ const channel = (row: ChannelRailRow) => {
+ if (row.kind === 'conversation') {
+ return row.channel;
+ }
+
+ if (row.kind === 'favorite') {
+ return options.channelById(row.favorite.entityId);
+ }
+
+ return undefined;
+ };
+
+ const flush = () => {
+ const preference = section ? options.preferences[section] : undefined;
+ const defaultSort = section === 'favorites' ? 'manual' : undefined;
+ const sort = preference?.sort ?? defaultSort;
+ const visible = entries.filter((row) => {
+ if (row.kind !== 'conversation' && row.kind !== 'favorite') {
+ return true;
+ }
+
+ return (
+ !preference?.unreadOnly ||
+ options.unreadChannelIds.has(channel(row)?.id ?? '')
+ );
+ });
+
+ if (sort && sort !== 'manual') {
+ const channels = visible.flatMap((row) => channel(row) ?? []);
+ const ordered =
+ sort === 'name'
+ ? channels.sort(compareChannelName)
+ : sortChannels(channels, sort);
+ const positions = new Map(ordered.map((item, index) => [item.id, index]));
+
+ visible.sort(
+ (left, right) =>
+ (positions.get(channel(left)?.id ?? '') ?? positions.size) -
+ (positions.get(channel(right)?.id ?? '') ?? positions.size)
+ );
+ }
+
+ result.push(...visible);
+ entries = [];
+ };
+
+ for (const row of rows) {
+ if (row.kind === 'section' || row.kind === 'label') {
+ flush();
+ section = row.kind === 'label' ? `label:${row.label.id}` : row.group;
+ result.push(row);
+ } else {
+ entries.push(row);
+ }
+ }
+
+ flush();
+
+ let directMessageIndex = 0;
+
+ result.forEach((row, index) => {
+ if (row.kind === 'label') {
+ row.localIndex = index;
+ }
+
+ if (row.kind === 'conversation') {
+ row.localIndex =
+ row.group === 'direct_messages' ? directMessageIndex++ : index;
+ }
+ });
+
+ return result;
+}
+
+/**
+ * Keyboard-navigable rows in visual order. Collapsed sections contribute
+ * only their heading; restored list modes keep their flat row ordering.
+ */
+export function buildChannelRailRows(
+ tab: ChannelsTab,
+ expandedGroups: Record<ChannelsRailSection, boolean>,
+ items: ChannelRailItemsByScope,
+ channelSectionRows: readonly ChannelSectionRow[],
+ sectionOptions?: SectionOptions
+): ChannelRailRow[] {
+ if (tab === 'threads') {
+ return [
+ { kind: 'all-threads', id: ALL_THREADS_ROW_ID },
+ ...items.threads.map(
+ (channel, localIndex): ChannelRailRow => ({
+ kind: 'conversation',
+ id: rowKeyForChannel(channel.id),
+ scope: 'threads',
+ localIndex,
+ channel,
+ })
+ ),
+ ];
+ }
+
+ if (tab === 'recents') {
+ return items.recents.map((channel, localIndex) => ({
+ kind: 'conversation',
+ id: `channel:${channel.id}`,
+ scope: 'recents',
+ localIndex,
+ channel,
+ }));
+ }
+
+ const rows: ChannelRailRow[] = [];
+
+ const appendReferenceStatus = (
+ section: ChannelSectionKey,
+ group: 'favorites' | 'team_channels'
+ ) => {
+ const state = sectionOptions?.referenceStatuses?.[section];
+
+ if (state) {
+ rows.push({
+ kind: 'reference-status',
+ id: `reference-status:${section}`,
+ group,
+ state,
+ });
+ }
+ };
+
+ 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,
+ })
+ )
+ );
+ appendReferenceStatus('favorites', 'favorites');
+ }
+
+ 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: rowKeyForChannel(channel.id),
+ group: 'direct_messages',
+ scope: 'direct_messages',
+ localIndex,
+ channel,
+ })
+ )
+ );
+ rows.push({
+ kind: 'status',
+ id: 'status:direct_messages',
+ group: 'direct_messages',
+ });
+ }
+
+ const labelledIds = new Set(
+ channelSectionRows.flatMap((row) =>
+ row.kind === 'conversation' && row.labelId ? [row.channel.id] : []
+ )
+ );
+ // Membership still hides channels when their section is collapsed.
+ for (const row of channelSectionRows) {
+ if (row.kind === 'label') {
+ for (const id of row.label.channelIds) {
+ labelledIds.add(id);
+ }
+ }
+ }
+
+ for (const group of ['team_channels', 'channels'] as const) {
+ const channels = items[group].filter(
+ (channel) => !labelledIds.has(channel.id)
+ );
+
+ if (group === 'channels' && channels.length === 0) {
+ continue;
+ }
+
+ rows.push({ kind: 'section', id: `section:${group}`, group });
+
+ if (!expandedGroups[group]) {
+ continue;
+ }
+
+ for (const channel of channels) {
+ rows.push({
+ kind: 'conversation',
+ id: rowKeyForChannel(channel.id),
+ group,
+ scope: group,
+ localIndex: 0,
+ channel,
+ });
+ }
+
+ rows.push({ kind: 'status', id: `status:${group}`, group });
+ }
+
+ let previousLabelId: string | undefined;
+
+ for (const row of channelSectionRows) {
+ if (row.kind === 'label') {
+ if (previousLabelId) {
+ appendReferenceStatus(`label:${previousLabelId}`, 'team_channels');
+ }
+
+ previousLabelId = row.label.id;
+ rows.push({
+ kind: 'label',
+ id: rowKeyForLabel(row.label.id),
+ group: 'team_channels',
+ localIndex: 0,
+ label: row.label,
+ });
+ } else if (row.labelId) {
+ rows.push({
+ kind: 'conversation',
+ id: rowKeyForChannel(row.channel.id, row.labelId),
+ group: 'team_channels',
+ scope: 'team_channels',
+ localIndex: 0,
+ channel: row.channel,
+ labelId: row.labelId,
+ });
+ }
+ }
+
+ if (previousLabelId) {
+ appendReferenceStatus(`label:${previousLabelId}`, 'team_channels');
+ }
+
+ // Retain visual-order indexes for callers using the flat keyboard list.
+ rows.forEach((row, index) => {
+ if (
+ (row.kind === 'conversation' && row.group !== 'direct_messages') ||
+ row.kind === 'label'
+ ) {
+ row.localIndex = index;
+ }
+ });
+
+ return sectionOptions ? applySectionPreferences(rows, sectionOptions) : rows;
+}
+
+export type ChannelRailSectionRows = {
+ heading: Extract<ChannelRailRow, { kind: 'section' | 'label' }>;
+ rows: ChannelRailRow[];
+};
+
+/** Keep section identities stable while their independently scrolling rows change. */
+export function groupChannelRailSections(rows: readonly ChannelRailRow[]) {
+ const sections = new Map<ChannelSectionKey, ChannelRailSectionRows>();
+ let current: ChannelRailSectionRows | undefined;
+
+ for (const row of rows) {
+ if (row.kind === 'section' || row.kind === 'label') {
+ current = { heading: row, rows: [] };
+ sections.set(row.kind === 'label' ? row.id : row.group, current);
+ } else {
+ current?.rows.push(row);
+ }
+ }
+
+ return sections;
+}
+
+/** Page at the rendered section boundary, not a source tail hidden by a label. */
+export function getChannelRailPaginationScope(
+ row: ChannelRailRow,
+ rows: readonly ChannelRailRow[],
+ expanded: Readonly<Record<ChannelsRailSection, boolean>>
+): ChannelsSourceScope | undefined {
+ if (row.kind === 'section') {
+ if (row.group === 'favorites' || !expanded[row.group]) {
+ return;
+ }
+
+ const hasVisibleChannels = rows.some(
+ (item) =>
+ item.kind === 'conversation' &&
+ !item.labelId &&
+ item.scope === row.group
+ );
+
+ return hasVisibleChannels ? undefined : row.group;
+ }
+
+ if (row.kind !== 'conversation' || row.labelId) {
+ return;
+ }
+
+ const last = rows.findLast(
+ (item) =>
+ item.kind === 'conversation' && !item.labelId && item.scope === row.scope
+ );
+
+ return last?.id === row.id ? row.scope : undefined;
+}
diff --git a/apps/web/src/features/channels-view/components/rail/next/useFavoriteReorder.ts b/apps/web/src/features/channels-view/components/rail/next/useFavoriteReorder.ts
new file mode 100644
index 0000000000..238ae5c754
--- /dev/null
+++ b/apps/web/src/features/channels-view/components/rail/next/useFavoriteReorder.ts
@@ -0,0 +1,164 @@
+import { t } from '@app/lib/i18n';
+import { toast } from '@core/component/Toast/Toast';
+import { useUserId } from '@core/context/user';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
+import {
+ useFavoritesData,
+ useReorderFavoritesMutation,
+} from '@queries/favorites/favorites';
+import type { Favorite } from '@service-storage/generated/schemas/favorite';
+import { useDragDropContext } from '@thisbeyond/solid-dnd';
+import { type Accessor, createMemo, createSignal } from 'solid-js';
+import { rowKeyForFavorite, useChannelsRail } from '../ChannelsRailContext';
+
+/** Replace only visible favorite slots, preserving hidden and other-type favorites. */
+export function reorderVisibleFavorites(
+ all: readonly Favorite[],
+ visible: readonly Favorite[],
+ sourceKey: string,
+ targetKey: string
+): Favorite[] | undefined {
+ const source = visible.findIndex(
+ (item) => rowKeyForFavorite(item) === sourceKey
+ );
+ const target = visible.findIndex(
+ (item) => rowKeyForFavorite(item) === targetKey
+ );
+
+ if (source < 0 || target < 0 || source === target) {
+ return;
+ }
+
+ const keys = new Set(visible.map(rowKeyForFavorite));
+ const allKeys = new Set(all.map(rowKeyForFavorite));
+
+ if (visible.some((item) => !allKeys.has(rowKeyForFavorite(item)))) {
+ return;
+ }
+
+ const reordered = [...visible];
+ reordered.splice(target, 0, ...reordered.splice(source, 1));
+
+ let index = 0;
+
+ return all.map((item) =>
+ keys.has(rowKeyForFavorite(item)) ? reordered[index++] : item
+ );
+}
+
+export function useFavoriteReorder(visible: Accessor<readonly Favorite[]>) {
+ const rail = useChannelsRail();
+ const userId = useUserId();
+ const favorites = useFavoritesData();
+ const mutation = useReorderFavoritesMutation();
+ const [saving, setSaving] = createSignal(false);
+ const [state, actions] = useDragDropContext() ?? [];
+ const scope = `${rail.railId}:favorites`;
+ const account = createMemo(() => ({ id: userId() }));
+ let dragAccount: ReturnType<typeof account> | undefined;
+
+ const enabled = () =>
+ !!userId() &&
+ !saving() &&
+ rail.sectionPreferences('favorites').sort === 'manual' &&
+ favorites() !== undefined &&
+ visible().length > 1;
+
+ const dropEdge = (targetKey: string): 'top' | 'bottom' | undefined => {
+ const source = state?.active.draggable;
+ const target = state?.active.droppable;
+
+ if (
+ !enabled() ||
+ source?.data.dndScope !== scope ||
+ target?.data.dndScope !== scope ||
+ target.data.favoriteKey !== targetKey
+ ) {
+ return;
+ }
+
+ const items = visible();
+ const sourceIndex = items.findIndex(
+ (item) => rowKeyForFavorite(item) === source.data.favoriteKey
+ );
+ const targetIndex = items.findIndex(
+ (item) => rowKeyForFavorite(item) === targetKey
+ );
+
+ if (sourceIndex < 0 || targetIndex < 0 || sourceIndex === targetIndex) {
+ return;
+ }
+
+ return sourceIndex < targetIndex ? 'bottom' : 'top';
+ };
+
+ actions?.onDragStart(({ draggable }) => {
+ if (draggable.data.dndScope === scope) {
+ dragAccount = account();
+ }
+ });
+
+ const save = async (items: Favorite[], entityId: string) => {
+ const requestAccount = account();
+ setSaving(true);
+
+ try {
+ await Telemetry.span('channels.favorites.reorder', async (span) => {
+ span.setAttr('entity.id', entityId);
+ span.setAttr('entity.type', 'channel');
+ span.setAttr('favorites.count', items.length);
+ await mutation.mutateAsync({
+ favorites: items.map(({ entityType, entityId }) => ({
+ entityType,
+ entityId,
+ })),
+ });
+ });
+ } catch {
+ if (requestAccount === account()) {
+ toast.failure(t('channelSections.reorderFavoritesFailed'));
+ }
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ actions?.onDragEnd(({ draggable, droppable }) => {
+ if (!enabled() || dragAccount !== account() || !droppable) {
+ return;
+ }
+
+ if (
+ draggable.data.dndScope !== scope ||
+ droppable.data.dndScope !== scope
+ ) {
+ return;
+ }
+
+ const sourceKey = draggable.data.favoriteKey;
+ const targetKey = droppable.data.favoriteKey;
+
+ if (typeof sourceKey !== 'string' || typeof targetKey !== 'string') {
+ return;
+ }
+
+ const items = reorderVisibleFavorites(
+ favorites()?.favorites ?? [],
+ visible(),
+ sourceKey,
+ targetKey
+ );
+ const source = visible().find(
+ (item) => rowKeyForFavorite(item) === sourceKey
+ );
+
+ if (!items || !source) {
+ return;
+ }
+
+ fireAndForget(save(items, source.entityId), 'channels-view');
+ });
+
+ return { scope, enabled, dropEdge };
+}
diff --git a/apps/web/src/features/channels-view/constants.ts b/apps/web/src/features/channels-view/constants.ts
index affcc46046..cceb876cd0 100644
--- a/apps/web/src/features/channels-view/constants.ts
+++ b/apps/web/src/features/channels-view/constants.ts
@@ -5,6 +5,22 @@ export const CHANNELS_DEFAULT_RAIL_WIDTH = DEFAULT_ASIDE_LAYOUT.width;
export const CHANNELS_MIN_RAIL_WIDTH = DEFAULT_ASIDE_LAYOUT.min;
export const CHANNELS_MAX_RAIL_WIDTH = DEFAULT_ASIDE_LAYOUT.max;
+export const CHANNEL_SECTION_ROW_HEIGHT = 34;
+export const CHANNEL_SECTION_MIN_ITEMS = 2;
+export const CHANNEL_SECTION_MIN_HEIGHT =
+ CHANNEL_SECTION_ROW_HEIGHT * CHANNEL_SECTION_MIN_ITEMS;
+export const CHANNEL_SECTION_MAX_HEIGHT = 800;
+
+export function clampChannelSectionHeight(height: number): number {
+ if (!Number.isFinite(height)) return CHANNEL_SECTION_MAX_HEIGHT;
+ return Math.round(
+ Math.min(
+ CHANNEL_SECTION_MAX_HEIGHT,
+ Math.max(CHANNEL_SECTION_MIN_HEIGHT, height)
+ )
+ );
+}
+
export const CHANNELS_DEFAULT_SORT_BY = {
team_channels: 'updated_at',
channels: 'updated_at',
diff --git a/apps/web/src/features/channels-view/core/channel-label-eligibility.test.ts b/apps/web/src/features/channels-view/core/channel-label-eligibility.test.ts
index 1062f44a54..e329d888e7 100644
--- a/apps/web/src/features/channels-view/core/channel-label-eligibility.test.ts
+++ b/apps/web/src/features/channels-view/core/channel-label-eligibility.test.ts
@@ -6,14 +6,24 @@ import {
} from './channel-label-eligibility';
describe('channel label eligibility', () => {
- it('requires a known team channel', () => {
+ it('allows named conversations in personal sections but excludes DMs', () => {
expect(canLabelChannel({ channelType: 'team' })).toBe(true);
- expect(canLabelChannel({ channelType: 'public' })).toBe(false);
- expect(canLabelChannel({ channelType: 'private' })).toBe(false);
+ expect(canLabelChannel({ channelType: 'public' })).toBe(true);
+ expect(canLabelChannel({ channelType: 'private' })).toBe(true);
expect(canLabelChannel({ channelType: 'direct_message' })).toBe(false);
expect(canLabelChannel(undefined)).toBe(false);
});
+ it('keeps shared sections restricted to team channels', () => {
+ const shared = { teamId: 'team' };
+ expect(canLabelChannel({ channelType: 'team' }, shared)).toBe(true);
+ expect(canLabelChannel({ channelType: 'private' }, shared)).toBe(false);
+ expect(canLabelChannel({ channelType: 'public' }, shared)).toBe(false);
+ expect(canLabelChannel({ channelType: 'direct_message' }, shared)).toBe(
+ false
+ );
+ });
+
it('retains unloaded server memberships for unread activity while removing known non-team channels', () => {
const members = filterChannelLabelMembers(
['unloaded', 'public', 'team', 'private', 'dm'],
@@ -22,7 +32,8 @@ describe('channel label eligibility', () => {
['team', { channelType: 'team' }],
['private', { channelType: 'private' }],
['dm', { channelType: 'direct_message' }],
- ])
+ ]),
+ { teamId: 'team' }
);
expect(members).toEqual(['unloaded', 'team']);
diff --git a/apps/web/src/features/channels-view/core/channel-label-eligibility.ts b/apps/web/src/features/channels-view/core/channel-label-eligibility.ts
index ce632e06a8..66f82f1986 100644
--- a/apps/web/src/features/channels-view/core/channel-label-eligibility.ts
+++ b/apps/web/src/features/channels-view/core/channel-label-eligibility.ts
@@ -1,19 +1,27 @@
import type { ChannelEntity } from '@entity';
+import type { ChannelLabel } from '@service-storage/generated/schemas/channelLabel';
-/** Only team channels participate in manual or smart labels. */
+/** Personal sections accept named conversations; shared sections stay team-only. */
export function canLabelChannel(
- channel: Pick<ChannelEntity, 'channelType'> | undefined
+ channel: Pick<ChannelEntity, 'channelType'> | undefined,
+ label?: Pick<ChannelLabel, 'teamId'>
): boolean {
- return channel?.channelType === 'team';
+ if (label?.teamId) return channel?.channelType === 'team';
+ return (
+ channel?.channelType === 'team' ||
+ channel?.channelType === 'public' ||
+ channel?.channelType === 'private'
+ );
}
-/** Trust server memberships for unloaded channels; exclude known non-team channels. */
+/** Preserve authorized server memberships until the channel metadata arrives. */
export function filterChannelLabelMembers(
channelIds: readonly string[],
- channelsById: ReadonlyMap<string, Pick<ChannelEntity, 'channelType'>>
+ channelsById: ReadonlyMap<string, Pick<ChannelEntity, 'channelType'>>,
+ label?: Pick<ChannelLabel, 'teamId'>
): string[] {
return channelIds.filter((id) => {
const channel = channelsById.get(id);
- return channel === undefined || canLabelChannel(channel);
+ return channel === undefined || canLabelChannel(channel, label);
});
}
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.ts
index 80fed94658..3eae8dbbde 100644
--- a/apps/web/src/features/channels-view/core/smart-tags.test.ts
+++ b/apps/web/src/features/channels-view/core/smart-tags.test.ts
@@ -72,11 +72,20 @@ describe('smart tag matching', () => {
'excludes %s channels from smart matching and cached manual or smart memberships',
(channelType) => {
const nonTeam = channel('non-team', 'Support', channelType);
- expect(channelMatchesSmartTag(nonTeam, rule)).toBe(false);
+ expect(channelMatchesSmartTag(nonTeam, rule, { teamId: 'team' })).toBe(
+ false
+ );
const result = resolveChannelLabelMemberships(
[
- { ...label('manual', ['unloaded', 'non-team', 'team']), rule: null },
- label('smart', ['unloaded', 'non-team', 'team']),
+ {
+ ...label('manual', ['unloaded', 'non-team', 'team']),
+ teamId: 'team',
+ rule: null,
+ },
+ {
+ ...label('smart', ['unloaded', 'non-team', 'team']),
+ teamId: 'team',
+ },
],
[nonTeam, channel('team', 'Support')]
);
@@ -89,7 +98,14 @@ describe('smart tag matching', () => {
it('preserves the manual count of assignments outside the loaded viewer-relative IDs', () => {
const result = resolveChannelLabelMemberships(
- [{ ...label('manual', ['public', 'team']), rule: null, channelCount: 8 }],
+ [
+ {
+ ...label('manual', ['public', 'team']),
+ teamId: 'team',
+ rule: null,
+ channelCount: 8,
+ },
+ ],
[channel('public', 'Public', 'public'), channel('team', 'Support')]
);
expect(result[0].channelIds).toEqual(['team']);
@@ -114,4 +130,13 @@ describe('smart tag matching', () => {
expect(result[0].channelIds).toEqual(['unloaded', 'member']);
expect(result[0].channelCount).toBe(2);
});
+
+ it('matches private channels in personal sections without adding them to shared sections', () => {
+ const result = resolveChannelLabelMemberships(
+ [label('personal', []), { ...label('shared', []), teamId: 'team' }],
+ [channel('private', 'Support', 'private')]
+ );
+ expect(result[0].channelIds).toEqual(['private']);
+ expect(result[1].channelIds).toEqual([]);
+ });
});
diff --git a/apps/web/src/features/channels-view/core/smart-tags.ts b/apps/web/src/features/channels-view/core/smart-tags.ts
index 5279d03367..6d81cf5bfe 100644
--- a/apps/web/src/features/channels-view/core/smart-tags.ts
+++ b/apps/web/src/features/channels-view/core/smart-tags.ts
@@ -5,32 +5,32 @@ import { canLabelChannel } from './channel-label-eligibility';
export function channelMatchesSmartTag(
channel: ChannelEntity,
- rule: ChannelLabelRule
+ rule: ChannelLabelRule,
+ label?: Pick<ChannelLabel, 'teamId'>
): boolean {
return (
- canLabelChannel(channel) &&
+ canLabelChannel(channel, label) &&
rule.contains.length > 0 &&
channel.name.toLowerCase().includes(rule.contains.toLowerCase())
);
}
-/** Keep unloaded server matches, exclude non-team channels, and reflect live names. */
+/** Preserve authorized server matches and reflect live names within each scope. */
export function resolveChannelLabelMemberships(
labels: readonly ChannelLabel[],
channels: readonly ChannelEntity[]
): ChannelLabel[] {
const loadedIds = new Set(channels.map((channel) => channel.id));
- const ineligibleIds = new Set(
- channels
- .filter((channel) => !canLabelChannel(channel))
- .map((channel) => channel.id)
+ const channelsById = new Map(
+ channels.map((channel) => [channel.id, channel])
);
return labels.map((label) => {
const rule = label.rule;
if (!rule) {
- const channelIds = label.channelIds.filter(
- (id) => !ineligibleIds.has(id)
- );
+ const channelIds = label.channelIds.filter((id) => {
+ const channel = channelsById.get(id);
+ return !channel || canLabelChannel(channel, label);
+ });
return channelIds.length === label.channelIds.length
? label
: {
@@ -51,7 +51,7 @@ export function resolveChannelLabelMemberships(
.filter(
(channel) =>
(!label.teamId || serverIds.has(channel.id)) &&
- channelMatchesSmartTag(channel, rule)
+ channelMatchesSmartTag(channel, rule, label)
)
.map((channel) => channel.id),
]),
diff --git a/apps/web/src/features/channels-view/persistence.ts b/apps/web/src/features/channels-view/persistence.ts
index 881cb1f633..479c33a259 100644
--- a/apps/web/src/features/channels-view/persistence.ts
+++ b/apps/web/src/features/channels-view/persistence.ts
@@ -12,6 +12,7 @@ import { z } from 'zod';
import {
CHANNELS_DEFAULT_RAIL_WIDTH,
CHANNELS_DEFAULT_SORT_BY,
+ clampChannelSectionHeight,
clampChannelsRailWidth,
} from './constants';
import type { ChannelsViewState } from './types';
@@ -95,6 +96,24 @@ const channelsPreferencesSchema = z.object({
.default(CHANNELS_DEFAULT_SORT_BY.threads),
})
.default(CHANNELS_DEFAULT_SORT_BY),
+ sectionPreferences: z
+ .record(
+ z.string(),
+ z
+ .object({
+ sort: z
+ .enum(['viewed_at', 'updated_at', 'created_at', 'name', 'manual'])
+ .optional(),
+ unreadOnly: z.boolean().optional(),
+ height: z
+ .number()
+ .finite()
+ .transform(clampChannelSectionHeight)
+ .optional(),
+ })
+ .optional()
+ )
+ .default({}),
});
type ChannelsPreferences = z.infer<typeof channelsPreferencesSchema>;
@@ -103,6 +122,7 @@ const DEFAULT_CHANNELS_PREFERENCES = {
version: 1,
asideWidth: CHANNELS_DEFAULT_RAIL_WIDTH,
sortBy: CHANNELS_DEFAULT_SORT_BY,
+ sectionPreferences: {},
} satisfies ChannelsPreferences;
function selectEntryState(state: ChannelsViewState): ChannelsEntryState {
@@ -197,6 +217,7 @@ function createChannelsPreferencesStorage(options: {
version: 1,
asideWidth: clampChannelsRailWidth(state.asideWidth),
sortBy: state.sortBy,
+ sectionPreferences: state.sectionPreferences,
} satisfies ChannelsPreferences);
return {
@@ -219,12 +240,14 @@ function createChannelsPreferencesStorage(options: {
...current,
asideWidth: restored.asideWidth,
sortBy: restored.sortBy,
+ sectionPreferences: restored.sectionPreferences,
};
} catch {
return {
...current,
asideWidth: DEFAULT_CHANNELS_PREFERENCES.asideWidth,
sortBy: DEFAULT_CHANNELS_PREFERENCES.sortBy,
+ sectionPreferences: DEFAULT_CHANNELS_PREFERENCES.sectionPreferences,
};
}
},
diff --git a/apps/web/src/features/channels-view/queries.test.ts b/apps/web/src/features/channels-view/queries.test.ts
index d14d522002..ef190df930 100644
--- a/apps/web/src/features/channels-view/queries.test.ts
+++ b/apps/web/src/features/channels-view/queries.test.ts
@@ -1,6 +1,7 @@
import type { ChannelEntity } from '@entity/types/entity';
+import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';
import { QueryClient } from '@tanstack/query-core';
-import { createRoot } from 'solid-js';
+import { createMemo, createRoot, createSignal } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
const useSoupAstItemsQuery = vi.hoisted(() =>
@@ -17,6 +18,11 @@ const useSoupAstItemsQuery = vi.hoisted(() =>
)
);
+const fetchAllChannels = vi.hoisted(() =>
+ vi.fn<(signal?: AbortSignal) => Promise<ApiChannelWithLatest[]>>()
+);
+vi.mock('@queries/channel/channels', () => ({ fetchAllChannels }));
+
const graphqlSoup = vi.hoisted(() => ({ enabled: false }));
const createChannelDetailQuery = vi.hoisted(() =>
vi.fn((_channelId: () => string | undefined, enabled: () => boolean) => ({
@@ -45,7 +51,11 @@ vi.mock('@entity', () => ({
vi.mock('@core/context/user', () => ({ useUserId: () => () => 'user-1' }));
import { useChannelByIdQuery } from '@channel/Channel/channel-entity';
-import { resolveReferencedChannels, useChannelsSources } from './queries';
+import {
+ fetchChannelGroupIds,
+ resolveReferencedChannels,
+ useChannelsSources,
+} from './queries';
const channelEntity = (id: string) =>
({
@@ -56,6 +66,79 @@ const channelEntity = (id: string) =>
channelType: 'team',
}) as ChannelEntity;
+describe('built-in section notification membership', () => {
+ it('keeps joined channels in their section and excludes custom-section assignments', async () => {
+ fetchAllChannels.mockResolvedValue([
+ {
+ id: 'private',
+ channel_type: 'private',
+ is_participant: true,
+ created_at: '',
+ updated_at: '',
+ owner_id: '',
+ auto_join_team: false,
+ participants: [],
+ latest_message: null,
+ },
+ {
+ id: 'assigned',
+ channel_type: 'private',
+ is_participant: true,
+ created_at: '',
+ updated_at: '',
+ owner_id: '',
+ auto_join_team: false,
+ participants: [],
+ latest_message: null,
+ },
+ {
+ id: 'team',
+ channel_type: 'team',
+ is_participant: true,
+ created_at: '',
+ updated_at: '',
+ owner_id: '',
+ auto_join_team: false,
+ participants: [],
+ latest_message: null,
+ },
+ {
+ id: 'unjoined',
+ channel_type: 'team',
+ is_participant: false,
+ created_at: '',
+ updated_at: '',
+ owner_id: '',
+ auto_join_team: false,
+ participants: [],
+ latest_message: null,
+ },
+ {
+ id: 'dm',
+ channel_type: 'direct_message',
+ is_participant: true,
+ created_at: '',
+ updated_at: '',
+ owner_id: '',
+ auto_join_team: false,
+ participants: [],
+ latest_message: null,
+ },
+ ]);
+ const signal = new AbortController().signal;
+
+ expect(
+ await fetchChannelGroupIds('channels', ['assigned'], signal)
+ ).toEqual(['private']);
+ expect(
+ await fetchChannelGroupIds('team_channels', ['assigned'], signal)
+ ).toEqual(['team']);
+ expect(await fetchChannelGroupIds('direct_messages', [], signal)).toEqual([
+ 'dm',
+ ]);
+ expect(fetchAllChannels).toHaveBeenLastCalledWith(signal);
+ });
+});
describe('channel list query selection', () => {
it('refreshes a newly cached full edge instead of reusing it for 30 seconds', async () => {
useSoupAstItemsQuery.mockClear();
@@ -157,55 +240,77 @@ describe('channels resolved by id', () => {
const resolved = [channelEntity('design'), channelEntity('support')];
const settled = {
isEnabled: true,
- isLoading: false,
+ isPending: false,
error: undefined,
- entities: undefined,
+ data: undefined,
};
it('replaces the previous answer, dropping channels the lookup stops returning', () => {
expect(
resolveReferencedChannels(resolved, {
...settled,
- entities: [
- channelEntity('design'),
- { id: 'note', type: 'document' } as never,
- ],
+ data: {
+ entities: [
+ channelEntity('design'),
+ { id: 'note', type: 'document' } as never,
+ ],
+ },
})
).toEqual([channelEntity('design')]);
});
- it('keeps the previous answer while the lookup is disabled or loading', () => {
- expect(
- resolveReferencedChannels(resolved, {
- ...settled,
- isEnabled: false,
- entities: [],
- })
- ).toBe(resolved);
- expect(
- resolveReferencedChannels(resolved, {
- ...settled,
- isLoading: true,
- entities: [],
- })
- ).toBe(resolved);
+ it.each(['disabled', 'pending', 'failed'] as const)(
+ 'keeps the previous answer without reading %s query data',
+ (state) => {
+ expect(
+ resolveReferencedChannels(resolved, {
+ isEnabled: state !== 'disabled',
+ isPending: state === 'pending',
+ error: state === 'failed' ? new Error('page failed') : undefined,
+ get data(): { entities: ChannelEntity[] } {
+ throw new Error('An unavailable query resource was read');
+ },
+ })
+ ).toBe(resolved);
+ }
+ );
+
+ it('retains resolved rows while a changed lookup is pending and updates when it settles', () => {
+ const { dispose, result, setPending, setEntities } = createRoot(
+ (dispose) => {
+ const [pending, setPending] = createSignal(false);
+ const [entities, setEntities] = createSignal(resolved);
+ const query = {
+ ...settled,
+ get isPending() {
+ return pending();
+ },
+ get data() {
+ if (pending()) throw new Error('A pending query resource was read');
+ return { entities: entities() };
+ },
+ };
+ const result = createMemo<ChannelEntity[]>(
+ (previous) => resolveReferencedChannels(previous, query),
+ []
+ );
+ return { dispose, result, setPending, setEntities };
+ }
+ );
+ try {
+ const previous = result();
+ setPending(true);
+ setEntities([channelEntity('support')]);
+ expect(result()).toBe(previous);
+ setPending(false);
+ expect(result()).toEqual([channelEntity('support')]);
+ } finally {
+ dispose();
+ }
});
- it('keeps the previous answer when a page fails instead of emptying the rows', () => {
- expect(
- resolveReferencedChannels(resolved, {
- ...settled,
- error: new Error('page failed'),
- entities: [channelEntity('design')],
- })
- ).toBe(resolved);
- // A failed first page leaves no data behind at all.
- expect(
- resolveReferencedChannels(resolved, {
- ...settled,
- error: new Error('lookup failed'),
- })
- ).toBe(resolved);
+ it('keeps the previous answer when a settled lookup has no data', () => {
+ expect(resolveReferencedChannels(resolved, settled)).toBe(resolved);
});
});
diff --git a/apps/web/src/features/channels-view/queries.ts b/apps/web/src/features/channels-view/queries.ts
index f0fdd73d00..b93cd8337f 100644
--- a/apps/web/src/features/channels-view/queries.ts
+++ b/apps/web/src/features/channels-view/queries.ts
@@ -12,6 +12,18 @@ import {
isChannelEntity,
isChannelThreadEntity,
} from '@entity';
+import {
+ registerChannelListNotificationRefresh,
+ useChannelsByIdsQuery,
+} from '@queries/channel/by-ids';
+import { fetchAllChannels } from '@queries/channel/channels';
+
+export {
+ channelsByIdsQueryArgs,
+ useChannelsByIdsQuery,
+} from '@queries/channel/by-ids';
+
+import { queryReadyGate } from '@queries/gate';
import {
type SoupAstItemsQueryArgs,
type SoupAstParams,
@@ -22,6 +34,7 @@ import { sortChannels } from './core/channel-sort';
import { channelThreadsQueryArgs } from './core/channel-threads-query';
import type {
ChannelListSort,
+ ChannelsGroup,
ChannelsQueryScope,
ChannelsSortGroup,
} from './types';
@@ -122,53 +135,34 @@ export function filterChannelsForScope(
return channels.filter(CHANNELS_QUERY_DEFINITIONS[scope].matches);
}
-/**
- * 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] },
- })
- )
- ),
- };
-}
+/** Resolve full built-in membership without changing the rail's loaded pages. */
+export async function fetchChannelGroupIds(
+ group: ChannelsGroup,
+ excludedIds: readonly string[],
+ signal?: AbortSignal
+): Promise<string[]> {
+ const excluded = new Set(excludedIds);
+ const channels = await fetchAllChannels(signal);
+ const members = channels.filter((channel) => {
+ if (!channel.is_participant || excluded.has(channel.id)) {
+ return false;
+ }
-export function useChannelsByIdsQuery(channelIds: Accessor<readonly string[]>) {
- const query = useSoupAstItemsQuery(
- () => channelsByIdsQueryArgs(channelIds()),
- // Rail rows need only bounded unread evidence, like the channel lists.
- () => ({
- enabled: channelIds().length > 0,
- staleTime: 30_000,
- graphqlProjection: 'channel-list',
- })
- );
- // Drive the external paginated query until all requested matches are loaded.
- createEffect(() => {
- if (
- !query.isEnabled ||
- query.isLoading ||
- query.isFetching ||
- query.error ||
- !query.hasNextPage
- )
- return;
- fireAndForget(query.fetchNextPage(), 'channels-view');
+ if (group === 'team_channels') {
+ return channel.channel_type === 'team';
+ }
+
+ if (group === 'direct_messages') {
+ return channel.channel_type === 'direct_message';
+ }
+
+ return (
+ channel.channel_type !== 'team' &&
+ channel.channel_type !== 'direct_message'
+ );
});
- return query;
+
+ return [...new Set(members.map((channel) => channel.id))];
}
/**
@@ -183,15 +177,15 @@ export function resolveReferencedChannels(
previous: ChannelEntity[],
lookup: {
isEnabled: boolean;
- isLoading: boolean;
+ isPending: boolean;
error: unknown;
- entities: readonly EntityData[] | undefined;
+ data: { entities: readonly EntityData[] } | undefined;
}
): ChannelEntity[] {
- if (!lookup.isEnabled || lookup.isLoading || lookup.error || !lookup.entities)
+ if (!lookup.isEnabled || lookup.error || !queryReadyGate(lookup))
return previous;
- return lookup.entities.filter(isChannelEntity);
+ return lookup.data.entities.filter(isChannelEntity);
}
export function deduplicateChannels(
@@ -330,6 +324,7 @@ function useChannelsDataSource(
graphqlProjection: 'channel-list',
})
);
+ registerChannelListNotificationRefresh(query);
const items = createMemo<ChannelEntity[]>((previous) => {
if (!query.isEnabled || query.isPending) return previous;
diff --git a/apps/web/src/features/channels-view/tour.ts b/apps/web/src/features/channels-view/tour.ts
index 6ef776fef1..5dfba6d4ac 100644
--- a/apps/web/src/features/channels-view/tour.ts
+++ b/apps/web/src/features/channels-view/tour.ts
@@ -32,7 +32,7 @@ export const channelsTour = defineViewTour({
entryLabel: 'Show the channel list to continue',
title: 'Channels and DMs, together',
description:
- 'Organize work in shared channels, and use DMs for smaller conversations. All and Recent help you return to the right discussion.',
+ 'Browse your channels and direct messages, keep favorites close, and search for a conversation from the sidebar.',
},
{
target: CHANNELS_TOUR.create,
@@ -40,7 +40,7 @@ export const channelsTour = defineViewTour({
entryLabel: 'Show the channel list to continue',
title: 'Bring your team into the room',
description:
- 'Use the + beside Channels to create a shared space, or the + beside DMs to start a direct message. Choose the people who need the context.',
+ 'Use New to create a channel or start a direct message. Conversations you join appear in the sidebar.',
},
{
target: CHANNEL_TOUR.messages,
diff --git a/apps/web/src/features/channels-view/types.ts b/apps/web/src/features/channels-view/types.ts
index ea73dddcf5..6b1cebc53f 100644
--- a/apps/web/src/features/channels-view/types.ts
+++ b/apps/web/src/features/channels-view/types.ts
@@ -11,6 +11,14 @@ export type ChannelsSortGroup = ChannelsGroup | 'threads';
/** Collapsible sections of the All tab. */
export type ChannelsRailSection = 'favorites' | ChannelsGroup;
+export type ChannelSectionKey = ChannelsRailSection | `label:${string}`;
+export type ChannelSectionPreferences = {
+ sort?: ChannelListSort | 'name' | 'manual';
+ unreadOnly?: boolean;
+ /** Preferred expanded body height in pixels; absent means size to content. */
+ height?: number;
+};
+
export type ChannelsQueryScope = ChannelsGroup | 'recents';
export type ChannelsViewState = {
@@ -28,6 +36,9 @@ export type ChannelsViewState = {
*/
threadsChannelId: string | undefined;
sortBy: Record<ChannelsSortGroup, ChannelListSort>;
+ sectionPreferences: Partial<
+ Record<ChannelSectionKey, ChannelSectionPreferences>
+ >;
asideWidth: number;
};
diff --git a/apps/web/src/features/entity/queries/dss.test.tsx b/apps/web/src/features/entity/queries/dss.test.tsx
index 91d9c091b4..89ad2940d8 100644
--- a/apps/web/src/features/entity/queries/dss.test.tsx
+++ b/apps/web/src/features/entity/queries/dss.test.tsx
@@ -87,7 +87,7 @@ import {
GRAPHQL_SOUP_DELETE_MUTATION_KEY,
GRAPHQL_SOUP_DELETE_RETENTION_MS,
type GraphqlSoupDeleteContext,
- usePendingGraphqlSoupDeleteIds,
+ usePendingGraphqlSoupDeleteKeys,
} from '@queries/soup/graphql/optimistic-deletions';
import { BulkDeleteFailure } from './bulk-delete-result';
import {
@@ -116,7 +116,7 @@ function deferred<T>() {
function mount() {
let result!: {
mutation: ReturnType<typeof createBulkDeleteDssItemsMutation>;
- pendingIds: ReturnType<typeof usePendingGraphqlSoupDeleteIds>;
+ pendingKeys: ReturnType<typeof usePendingGraphqlSoupDeleteKeys>;
};
dispose = render(
() => (
@@ -124,7 +124,7 @@ function mount() {
{(() => {
result = {
mutation: createBulkDeleteDssItemsMutation(),
- pendingIds: usePendingGraphqlSoupDeleteIds(),
+ pendingKeys: usePendingGraphqlSoupDeleteKeys(),
};
return null;
})()}
@@ -313,7 +313,7 @@ describe('bulk delete GraphQL optimism', () => {
mocks.deleteItem.mockResolvedValueOnce(true);
const refreshed = deferred<void>();
mocks.refresh.mockReturnValue(refreshed.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
try {
await expect(
mutation.mutateAsync([failed, deleted])
@@ -324,13 +324,17 @@ describe('bulk delete GraphQL optimism', () => {
});
expect(soup()).toEqual(['failed', 'other']);
expect(search()).toEqual(['failed', 'other']);
- expect([...pendingIds()]).toEqual(['deleted']);
+ expect([...pendingKeys()]).toEqual(['GraphqlSoupDocument:deleted']);
expect(mocks.failure).toHaveBeenCalledWith(
'Deleted 1 of 2 items; 1 failed'
);
- expect(mocks.removeSoup).toHaveBeenLastCalledWith(new Set(['deleted']));
+ expect(mocks.removeSoup).toHaveBeenLastCalledWith(
+ new Set(['deleted']),
+ expect.any(Function)
+ );
expect(mocks.removeSearch).toHaveBeenLastCalledWith(
- new Set(['deleted'])
+ new Set(['deleted']),
+ expect.any(Function)
);
} finally {
refreshed.resolve();
@@ -461,14 +465,17 @@ describe('bulk delete GraphQL optimism', () => {
const refreshed = deferred<void>();
mocks.deleteItem.mockReturnValue(network.promise);
mocks.refresh.mockReturnValue(refreshed.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
const result = mutation.mutateAsync([
entity('task-1'),
entity('task-2'),
entity('channel', 'channel'),
]);
await vi.waitFor(() =>
- expect([...pendingIds()]).toEqual(['task-1', 'task-2'])
+ expect([...pendingKeys()]).toEqual([
+ 'GraphqlSoupDocument:task-1',
+ 'GraphqlSoupDocument:task-2',
+ ])
);
expect(mocks.deleteItem).toHaveBeenCalledTimes(2);
expect(mocks.refresh).not.toHaveBeenCalled();
@@ -476,9 +483,12 @@ describe('bulk delete GraphQL optimism', () => {
await expect(result).resolves.toEqual([true, true]);
await vi.waitFor(() => expect(mutation.isPending).toBe(false));
expect(mocks.refresh).toHaveBeenCalledWith({ throwOnError: true });
- expect([...pendingIds()]).toEqual(['task-1', 'task-2']);
+ expect([...pendingKeys()]).toEqual([
+ 'GraphqlSoupDocument:task-1',
+ 'GraphqlSoupDocument:task-2',
+ ]);
refreshed.resolve();
- await vi.waitFor(() => expect(pendingIds().size).toBe(0));
+ await vi.waitFor(() => expect(pendingKeys().size).toBe(0));
});
it('restores failed deletions even while revalidation is still pending', async () => {
@@ -487,28 +497,30 @@ describe('bulk delete GraphQL optimism', () => {
const refreshed = deferred<void>();
mocks.deleteItem.mockReturnValue(network.promise);
mocks.refresh.mockReturnValue(refreshed.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
const error = new Error('delete failed');
const result = expect(
mutation.mutateAsync([entity('task')])
).rejects.toThrow(error);
- await vi.waitFor(() => expect(pendingIds().has('task')).toBe(true));
+ await vi.waitFor(() =>
+ expect(pendingKeys().has('GraphqlSoupDocument:task')).toBe(true)
+ );
network.reject(error);
await vi.waitFor(() => expect(mocks.refresh).toHaveBeenCalledOnce());
expect(mocks.rollbackSoup).toHaveBeenCalledOnce();
expect(mocks.rollbackSearch).toHaveBeenCalledOnce();
expect(mocks.failure).toHaveBeenCalledWith('Failed to delete items');
- expect(pendingIds().has('task')).toBe(false);
+ expect(pendingKeys().has('GraphqlSoupDocument:task')).toBe(false);
await result;
refreshed.resolve();
- await vi.waitFor(() => expect(pendingIds().size).toBe(0));
+ await vi.waitFor(() => expect(pendingKeys().size).toBe(0));
});
it('revalidates partial boolean failures without treating every item as deleted', async () => {
mocks.deleteItem.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
const refreshed = deferred<void>();
mocks.refresh.mockReturnValue(refreshed.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
await expect(
mutation.mutateAsync([entity('deleted'), entity('retained')])
).rejects.toMatchObject({
@@ -516,11 +528,27 @@ describe('bulk delete GraphQL optimism', () => {
message: 'Deleted 1 of 2 items; 1 failed',
});
expect(mocks.refresh).toHaveBeenCalledOnce();
- expect([...pendingIds()]).toEqual(['deleted']);
+ expect([...pendingKeys()]).toEqual(['GraphqlSoupDocument:deleted']);
refreshed.resolve();
- await vi.waitFor(() => expect(pendingIds().size).toBe(0));
+ await vi.waitFor(() => expect(pendingKeys().size).toBe(0));
});
+ it('retains only the successful entity type when equal IDs have different outcomes', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.deleteItem.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
+ const refreshed = deferred<void>();
+ mocks.refresh.mockReturnValue(refreshed.promise);
+ const { mutation, pendingKeys } = mount();
+ await expect(
+ mutation.mutateAsync([
+ entity('shared', 'document'),
+ entity('shared', 'chat'),
+ ])
+ ).rejects.toBeInstanceOf(BulkDeleteFailure);
+ expect([...pendingKeys()]).toEqual(['GraphqlSoupDocument:shared']);
+ refreshed.resolve();
+ await vi.waitFor(() => expect(pendingKeys().size).toBe(0));
+ });
it.each([true, false])(
'latches the GraphQL flag at creation (initially %s)',
async (enabled) => {
@@ -529,11 +557,11 @@ describe('bulk delete GraphQL optimism', () => {
const refreshed = deferred<void>();
mocks.deleteItem.mockReturnValue(network.promise);
mocks.refresh.mockReturnValue(refreshed.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
mocks.graphqlEnabled.mockReturnValue(!enabled);
const result = mutation.mutateAsync([entity('task')]);
await vi.waitFor(() => expect(mocks.deleteItem).toHaveBeenCalledOnce());
- expect(pendingIds().has('task')).toBe(enabled);
+ expect(pendingKeys().has('GraphqlSoupDocument:task')).toBe(enabled);
const cached = client.getMutationCache().getAll()[0];
expect(cached.options.mutationKey).toEqual(
enabled ? GRAPHQL_SOUP_DELETE_MUTATION_KEY : undefined
@@ -549,7 +577,7 @@ describe('bulk delete GraphQL optimism', () => {
expect(mocks.refresh).toHaveBeenCalledTimes(enabled ? 1 : 0);
expect(mocks.graphqlEnabled).toHaveBeenCalledTimes(1);
refreshed.resolve();
- await vi.waitFor(() => expect(pendingIds().size).toBe(0));
+ await vi.waitFor(() => expect(pendingKeys().size).toBe(0));
}
);
@@ -590,14 +618,14 @@ describe('bulk delete GraphQL optimism', () => {
mocks.refresh
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValue(undefined);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
await mutation.mutateAsync([entity('task')]);
await vi.advanceTimersByTimeAsync(0);
expect(mutation.isPending).toBe(false);
- expect([...pendingIds()]).toEqual(['task']);
+ expect([...pendingKeys()]).toEqual(['GraphqlSoupDocument:task']);
await vi.advanceTimersByTimeAsync(1000);
expect(mocks.refresh).toHaveBeenCalledTimes(2);
- expect(pendingIds().size).toBe(0);
+ expect(pendingKeys().size).toBe(0);
await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DELETE_RETENTION_MS);
expect(mocks.refresh).toHaveBeenCalledTimes(2);
});
@@ -610,7 +638,7 @@ describe('bulk delete GraphQL optimism', () => {
.mockRejectedValueOnce(new Error('delete failed'))
.mockReturnValueOnce(slowSuccess.promise);
mocks.refresh.mockReturnValue(refreshed.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
const result = expect(
mutation.mutateAsync([entity('failed'), entity('deleted')])
).rejects.toThrow('Deleted 1 of 2 items; 1 failed');
@@ -618,9 +646,9 @@ describe('bulk delete GraphQL optimism', () => {
expect(mocks.refresh).not.toHaveBeenCalled();
slowSuccess.resolve(true);
await result;
- expect([...pendingIds()]).toEqual(['deleted']);
+ expect([...pendingKeys()]).toEqual(['GraphqlSoupDocument:deleted']);
refreshed.resolve();
- await vi.waitFor(() => expect(pendingIds().size).toBe(0));
+ await vi.waitFor(() => expect(pendingKeys().size).toBe(0));
});
it.each([false, true])(
@@ -630,7 +658,7 @@ describe('bulk delete GraphQL optimism', () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
const network = deferred<boolean>();
mocks.deleteItem.mockReturnValue(network.promise);
- const { mutation, pendingIds } = mount();
+ const { mutation, pendingKeys } = mount();
const result = mutation.mutateAsync([entity('task')]);
const settled = fails
? expect(result).rejects.toThrow('delete failed')
@@ -638,7 +666,7 @@ describe('bulk delete GraphQL optimism', () => {
await vi.waitFor(() => expect(mocks.deleteItem).toHaveBeenCalledOnce());
expect(mocks.removeSoup).toHaveBeenCalledWith(new Set(['task']));
expect(mocks.removeSearch).toHaveBeenCalledWith(new Set(['task']));
- expect(pendingIds().size).toBe(0);
+ expect(pendingKeys().size).toBe(0);
expect(
client.getMutationCache().getAll()[0].options.mutationKey
).toBeUndefined();
diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.ts
index 857b528f3b..192a619973 100644
--- a/apps/web/src/features/entity/queries/dss.ts
+++ b/apps/web/src/features/entity/queries/dss.ts
@@ -28,6 +28,7 @@ import {
removeSoupEntitiesFromQueriesReferencing,
} from '@queries/soup/cache';
import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-queries';
+import { soupEntityKey } from '@queries/soup/graphql/entity-input';
import {
createGraphqlSoupDeletion,
GRAPHQL_SOUP_DELETE_MUTATION_KEY,
@@ -98,6 +99,31 @@ async function settleGraphqlDeletes(
return results;
}
+function removeDssEntityCaches(entities: EntityData[], typeScoped: boolean) {
+ const ids = new Set(entities.map((entity) => entity.id));
+ const keys = new Set(
+ entities.flatMap((entity) => {
+ const key = soupEntityKey(entity);
+ return key ? [key] : [];
+ })
+ );
+ if (!typeScoped)
+ return {
+ keys,
+ soupSnapshot: removeSoupEntities(ids),
+ searchSnapshot: removeSearchEntities(ids),
+ };
+ return {
+ keys,
+ soupSnapshot: removeSoupEntities(ids, (item, id) =>
+ keys.has(soupEntityKey({ type: item.tag, id }) ?? '')
+ ),
+ searchSnapshot: removeSearchEntities(ids, (item, id) =>
+ keys.has(soupEntityKey({ type: item.type, id }) ?? '')
+ ),
+ };
+}
+
export function createBulkDeleteDssItemsMutation() {
const graphqlSoupEnabled = isFeatureEnabled(enableGraphqlSoup);
const isDeletable = (entity: EntityData) => {
@@ -166,14 +192,14 @@ export function createBulkDeleteDssItemsMutation() {
},
onMutate: async (entities: EntityData[]) => {
const deletable = entities.filter(isDeletable);
- const ids = new Set(deletable.map((e) => e.id));
- const soupSnapshot = removeSoupEntities(ids);
- const searchSnapshot = removeSearchEntities(ids);
+ const { keys, ...snapshots } = removeDssEntityCaches(
+ deletable,
+ graphqlSoupEnabled
+ );
return {
- soupSnapshot,
- searchSnapshot,
+ ...snapshots,
...(graphqlSoupEnabled
- ? { graphqlDeletion: createGraphqlSoupDeletion([...ids]) }
+ ? { graphqlDeletion: createGraphqlSoupDeletion([...keys]) }
: {}),
};
},
@@ -188,14 +214,15 @@ export function createBulkDeleteDssItemsMutation() {
}
const outcomes =
error instanceof BulkDeleteFailure ? error.results : results;
- const deletedIds = entities
+ const deletedKeys = entities
.filter(isDeletable)
- .flatMap((entity, index) =>
- outcomes?.[index] === true ? [entity.id] : []
- );
+ .flatMap((entity, index) => {
+ const key = soupEntityKey(entity);
+ return outcomes?.[index] === true && key ? [key] : [];
+ });
// API completion closes the mutation; display state survives it and
- // independently retries revalidation. Failed ids are restored now.
- context?.graphqlDeletion?.settle(deletedIds);
+ // independently retries revalidation. Failed keys are restored now.
+ context?.graphqlDeletion?.settle(deletedKeys);
}
: undefined,
onError: (error, entities, context) => {
@@ -208,17 +235,13 @@ export function createBulkDeleteDssItemsMutation() {
error instanceof BulkDeleteFailure &&
error.deletedEntities.length > 0;
if (partialFailure) {
- const deletedIds = new Set(
- error.deletedEntities.map((entity) => entity.id)
- );
// The legacy transactions hold whole snapshots. Restore failed rows,
// then reapply confirmed removals in one reactive batch so successes
// never reappear in REST fallback lists or search results.
batch(() => {
context?.soupSnapshot.rollback();
context?.searchSnapshot.rollback();
- removeSoupEntities(deletedIds);
- removeSearchEntities(deletedIds);
+ removeDssEntityCaches(error.deletedEntities, true);
});
} else {
context?.soupSnapshot.rollback();
diff --git a/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx b/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx
index 174009be1d..0772c718d6 100644
--- a/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx
+++ b/apps/web/src/features/notifications/SnoozeNotificationsDialog.tsx
@@ -1,6 +1,7 @@
import { toast } from '@core/component/Toast/Toast';
import { useDateSearch } from '@core/util/dateSearch/useDateSearch';
import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
import { useMuteItemMutation } from '@queries/notification/unsubscribes';
import type { UserUnsubscribe } from '@service-notification/generated/schemas/userUnsubscribe';
import {
@@ -58,6 +59,26 @@ function SnoozeNotificationsDialog(
);
},
});
+
+ const submit = (until: Date) =>
+ Telemetry.span('notifications.snooze', async (span) => {
+ span.setAttr(
+ 'notification.item_ids',
+ props.items.map((item) => item.item_id)
+ );
+ span.setAttr('notification.count', controller.remainingCount());
+
+ await controller.submit(until);
+
+ const error = controller.error();
+
+ if (error) {
+ span.error(error);
+ } else {
+ span.setAttr('notification.snoozed_until', until.toISOString());
+ }
+ });
+
return (
<SnoozePicker
{...props}
@@ -67,9 +88,7 @@ function SnoozeNotificationsDialog(
options={options()}
pending={controller.pending()}
error={controller.error()}
- onSelect={(until) =>
- fireAndForget(controller.submit(until), 'notifications')
- }
+ onSelect={(until) => fireAndForget(submit(until), 'notifications')}
/>
);
}
diff --git a/apps/web/src/lib/core/component/EntityIcon.test.tsx b/apps/web/src/lib/core/component/EntityIcon.test.tsx
index a82dbc55da..08fba87e7c 100644
--- a/apps/web/src/lib/core/component/EntityIcon.test.tsx
+++ b/apps/web/src/lib/core/component/EntityIcon.test.tsx
@@ -15,6 +15,7 @@ import FolderIcon from '@icon/system/regular/folder-simple.svg';
import GitPullRequestIcon from '@icon/system/regular/git-pull-request.svg';
import HashIcon from '@icon/system/regular/hash-straight.svg';
import ListChecksIcon from '@icon/system/regular/list-checks.svg';
+import LockIcon from '@icon/system/regular/lock-simple.svg';
import PhoneIcon from '@icon/system/regular/phone-call.svg';
import SparkleIcon from '@icon/system/regular/sparkle.svg';
import SpreadsheetIcon from '@icon/system/regular/table.svg';
@@ -64,7 +65,7 @@ const entityGlyphs: [
],
['task', { type: 'document', subType: { type: 'task' } }, ListChecksIcon],
['channel', { type: 'channel', channelType: 'public' }, HashIcon],
- ['message', { type: 'channel_message', channelType: 'private' }, HashIcon],
+ ['message', { type: 'channel_message', channelType: 'private' }, LockIcon],
['thread', { type: 'channel_thread', channelType: 'team' }, HashIcon],
[
'direct message',
diff --git a/apps/web/src/lib/core/component/EntityIcon.tsx b/apps/web/src/lib/core/component/EntityIcon.tsx
index 4c4693b3cc..5aca4dfadc 100644
--- a/apps/web/src/lib/core/component/EntityIcon.tsx
+++ b/apps/web/src/lib/core/component/EntityIcon.tsx
@@ -89,6 +89,7 @@ import GlobeIcon from '@icon/system/regular/globe.svg';
import HashStraight from '@icon/system/regular/hash-straight.svg';
import FileImage from '@icon/system/regular/image.svg';
import ListChecks from '@icon/system/regular/list-checks.svg';
+import LockSimple from '@icon/system/regular/lock-simple.svg';
import PaintBrushBroad from '@icon/system/regular/paint-brush-broad.svg';
import PenNib from '@icon/system/regular/pen-nib.svg';
import PhoneCall from '@icon/system/regular/phone-call.svg';
@@ -265,8 +266,8 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {
prettyName: 'Organization',
},
private: {
- icon: HashStraight,
- boldIcon: HashStraightBold,
+ icon: LockSimple,
+ boldIcon: LockSimple,
foreground: 'text-communication',
background: 'bg-communication/20',
prettyName: 'Private Channel',
@@ -705,7 +706,11 @@ export function getEntityIconType(entity: EntityIconData): EntityWithValidIcon {
{ type: 'channel' },
{ type: 'channel_message' },
{ type: 'channel_thread' },
- (e) => (e.channelType === 'direct_message' ? 'direct_message' : 'channel')
+ (e) => {
+ if (e.channelType === 'direct_message') return 'direct_message';
+ if (e.channelType === 'private') return 'private';
+ return 'channel';
+ }
)
.with({ type: 'email' }, (e) =>
e.hasIcsAttachment ? 'emailInvite' : e.isRead ? 'emailRead' : 'email'
diff --git a/apps/web/src/lib/core/component/RecipientSelector.tsx b/apps/web/src/lib/core/component/RecipientSelector.tsx
index f6c5e214c4..62a23f986f 100644
--- a/apps/web/src/lib/core/component/RecipientSelector.tsx
+++ b/apps/web/src/lib/core/component/RecipientSelector.tsx
@@ -399,6 +399,8 @@ export type RecipientSelectorProps<K extends CombinedRecipientKind> = {
/** Open the suggestions dropdown when the input gains focus (default true) */
openOnFocus?: boolean;
triggerMode?: ComboboxTriggerMode;
+ /** Retain a typed query when focus moves to an action beside the picker. */
+ noResetInputOnBlur?: boolean;
hideBorder?: boolean;
noPadding?: boolean;
includeSelf?: boolean;
@@ -809,6 +811,7 @@ export function RecipientSelector<K extends CombinedRecipientKind>(
value={props.selectedOptions as CombinedRecipientItem[]}
onChange={handleChange}
onInputChange={onInputChange}
+ noResetInputOnBlur={props.noResetInputOnBlur}
shouldFocusWrap
placeholder={
props.selectedOptions?.length === 0 || isMobile()
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 8695132acb..7876e96cb6 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -785,6 +785,14 @@ export const enableTagTeamSharing = defineFlag({
default: onInDev,
});
+// Redesigned Chat sidebar sections. On in development;
+// deployed environments defer to PostHog. Override with VITE_ENABLE_CHAT_SIDEBAR_SECTIONS.
+export const enableChatSidebarSections = defineFlag({
+ key: 'enable-chat-sidebar-sections',
+ env: 'ENABLE_CHAT_SIDEBAR_SECTIONS',
+ 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({
diff --git a/apps/web/src/lib/i18n/locales/en.ts b/apps/web/src/lib/i18n/locales/en.ts
index 951e978a63..14dd13d1b8 100644
--- a/apps/web/src/lib/i18n/locales/en.ts
+++ b/apps/web/src/lib/i18n/locales/en.ts
@@ -1,4 +1,5 @@
import channelLabels from './en/channel-labels';
+import channelSections from './en/channel-sections';
import commandMenu from './en/command-menu';
import commands from './en/commands';
import common from './en/common';
@@ -19,6 +20,7 @@ import viewMenus from './en/view-menus';
*/
export default {
channelLabels,
+ channelSections,
commandMenu,
commands,
common,
diff --git a/apps/web/src/lib/i18n/locales/en/channel-labels.ts b/apps/web/src/lib/i18n/locales/en/channel-labels.ts
index fff85d0c56..0f5c1d2f4b 100644
--- a/apps/web/src/lib/i18n/locales/en/channel-labels.ts
+++ b/apps/web/src/lib/i18n/locales/en/channel-labels.ts
@@ -2,6 +2,11 @@ export default {
// The channels rail groups channels under labels; smart labels group by rule.
newChannel: 'New channel',
newLabel: 'New label',
+ createLabel: 'Create label',
+ renameLabel: 'Rename label',
+ rename: 'Rename',
+ sharedScopeDescription: 'Labels are shared with everyone on your team.',
+ personalScopeDescription: 'Labels are private to your account.',
newLabelEllipsis: 'New label…',
newSmartLabel: 'New smart label',
editSmartLabel: 'Edit smart label',
diff --git a/apps/web/src/lib/i18n/locales/en/channel-sections.ts b/apps/web/src/lib/i18n/locales/en/channel-sections.ts
new file mode 100644
index 0000000000..031bd087b0
--- /dev/null
+++ b/apps/web/src/lib/i18n/locales/en/channel-sections.ts
@@ -0,0 +1,102 @@
+export default {
+ chat: 'Chat',
+ conversations: 'Conversations',
+ search: 'Search conversations',
+ favorites: 'Favorites',
+ team_channels: 'Team channels',
+ namedTeamChannels: '{{name}} channels',
+ channels: 'Channels',
+ direct_messages: 'Direct messages',
+ empty: 'No conversations yet',
+ emptyFavorites: 'Star conversations to keep them here.',
+ emptySection: 'Drag conversations here to organize them.',
+ emptySmartSection: 'No conversations match this rule.',
+ noResults: 'No matching conversations',
+ loadMore: 'Load more',
+ retry: 'Retry',
+ newSection: 'New section',
+ createSection: 'Create section',
+ renameSection: 'Rename section',
+ deleteSection: 'Delete section',
+ deleteConfirmTitle: 'Delete “{{name}}”?',
+ deleteConfirmBody:
+ '{{scopeDescription}} {{channelsText}} Nobody loses access to a channel.',
+ deleteSmartChannels:
+ 'Channels stop appearing in this smart label. Other labels are unchanged.',
+ deleteEmptyChannels: 'It has no channels in it.',
+ created: 'Created “{{name}}”',
+ updated: 'Updated “{{name}}”',
+ deleted: 'Deleted “{{name}}”',
+ movedChannel: 'Moved {{channel}} to “{{name}}”',
+ removedChannel: 'Removed {{channel}} from “{{name}}”',
+ unnamedChannel: 'the channel',
+ deleteLabelFailed: 'Failed to delete label',
+ moveChannelFailed: 'Failed to move channel',
+ markLabelReadFailed: 'Failed to mark channel label as read',
+ muteAllChannels: 'Mute all channels',
+ unmuteAllChannels: 'Unmute all channels',
+ snoozeAllChannels: 'Snooze all channels…',
+ notificationsFailed:
+ 'Could not update section notifications. Please try again.',
+ deleteForEveryone: 'Delete for everyone',
+ sectionName: 'Section name',
+ manageSections: 'Manage sections',
+ sections: 'Sections',
+ optionsFor: 'Options for {{name}}',
+ expandSection: 'Expand section',
+ collapseSection: 'Collapse section',
+ resizeSection: 'Resize {{name}}',
+ resizeSectionHint: 'Drag to resize. Double-click to reset.',
+ expandAllSections: 'Expand all sections',
+ collapseAllSections: 'Collapse all sections',
+ loading: 'Loading sections…',
+ noAccess: 'You do not have access to these sections.',
+ labelsNoAccess: 'You do not have access to these labels.',
+ unavailable: 'Sections are unavailable right now.',
+ ineligibleChannel: 'This conversation cannot be added to this section.',
+ conversationsRemain:
+ 'Its conversations remain available in other sections or in the channel list.',
+ newPersonalSection: 'Personal section',
+ newTeamSection: 'Shared section',
+ newSmartSection: 'Smart section',
+ newTeamSmartSection: 'Shared smart section',
+ sharedShort: 'Shared',
+ personal: 'Personal',
+ shared: 'Shared with team',
+ personalDescription: 'Only you can see and organize this section.',
+ teamDescription: 'Everyone on your team can see and organize this section.',
+ addToSection: 'Add to section',
+ removeFrom: 'Remove from “{{name}}”',
+ createChannelOrDirectMessage: 'Create channel or direct message',
+ newChannel: 'New channel',
+ newDirectMessage: 'New direct message',
+ editSection: 'Edit section',
+ sectionDescription: 'Organize conversations in a section.',
+ sectionVisibility: 'Visibility',
+ sectionKind: 'Section type',
+ manualSection: 'Manual section',
+ nameContains: 'Name contains',
+ patternExample: 'e.g. support',
+ matchedChannels: 'Matched channels',
+ matchingChannelsLoading: 'Matching channels…',
+ matchesUnavailable: 'Could not load matches.',
+ noMatchingChannels: 'No channels match yet.',
+ moreChannelsMatched: {
+ one: '+{{count}} more channel matched',
+ other: '+{{count}} more channels matched',
+ },
+ saving: 'Saving…',
+ saveSection: 'Save section',
+ saveSectionFailed: 'Could not save section. Please try again.',
+ sort: 'Sort',
+ filter: 'Filter',
+ lastViewed: 'Last viewed',
+ lastUpdated: 'Last updated',
+ dateCreated: 'Date created',
+ alphabetical: 'Alphabetical',
+ customOrder: 'Custom order',
+ reorderFavoritesFailed: 'Could not reorder favorites. Please try again.',
+ unreadOnly: 'Unread only',
+ noUnreadConversations: 'No unread conversations',
+ cancel: 'Cancel',
+};
diff --git a/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx b/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx
index a603318653..ef487c2cd0 100644
--- a/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx
+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.test.tsx
@@ -1,27 +1,39 @@
+import { catchToResult } from '@core/util/result';
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 { type QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { type Ok, ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { queryClient } from '../client';
import {
useChannelLabelsData,
useChannelLabelsQuery,
+ useSetChannelLabelMutation,
useSmartTagPreviewQuery,
} from './channel-labels';
import { channelLabelKeys } from './keys';
const mocks = vi.hoisted(() => ({
enabled: (): boolean => false,
+ userId: (): string => 'viewer',
list: vi.fn(),
preview: vi.fn(),
+ assign: vi.fn(),
}));
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => () => ({ enabled: mocks.enabled() }),
}));
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => mocks.userId(),
+}));
vi.mock('@service-storage/client', () => ({
storageServiceClient: {
- channelLabels: { list: mocks.list, preview: mocks.preview },
+ channelLabels: {
+ list: mocks.list,
+ preview: mocks.preview,
+ setChannelLabel: mocks.assign,
+ },
},
}));
vi.mock('../client', async () => {
@@ -30,6 +42,7 @@ vi.mock('../client', async () => {
});
const labels: ChannelLabelsList = {
+ scope: 'personal',
labels: [
{
id: 'support',
@@ -45,11 +58,17 @@ const labels: ChannelLabelsList = {
let client: QueryClient;
beforeEach(() => {
+ mocks.userId = () => 'viewer';
+ mocks.assign.mockReset().mockResolvedValue(ok(undefined));
mocks.list.mockReset().mockResolvedValue(ok(labels));
mocks.preview
.mockReset()
.mockResolvedValue(ok({ channels: [], totalCount: 0 }));
- client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client = queryClient;
+ client.setDefaultOptions({
+ queries: { retry: false },
+ mutations: { retry: false },
+ });
});
afterEach(() => {
cleanup();
@@ -60,7 +79,10 @@ 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);
+ client.setQueryData(
+ channelLabelKeys.list(undefined, 'viewer').queryKey,
+ labels
+ );
let data!: ReturnType<typeof useChannelLabelsData>;
let query!: ReturnType<typeof useChannelLabelsQuery>;
const Probe = () => {
@@ -77,7 +99,7 @@ describe('channel tag query rollout', () => {
expect(query.isEnabled).toBe(false);
expect(data()).toBeUndefined();
await client.invalidateQueries({
- queryKey: channelLabelKeys.list.queryKey,
+ queryKey: channelLabelKeys.list(undefined, 'viewer').queryKey,
});
expect(mocks.list).not.toHaveBeenCalled();
@@ -89,10 +111,62 @@ describe('channel tag query rollout', () => {
await waitFor(() => expect(query.isEnabled).toBe(false));
expect(data()).toBeUndefined();
await client.invalidateQueries({
- queryKey: channelLabelKeys.list.queryKey,
+ queryKey: channelLabelKeys.list(undefined, 'viewer').queryKey,
});
expect(mocks.list).toHaveBeenCalledTimes(1);
- expect(client.getQueryData(channelLabelKeys.list.queryKey)).toEqual(labels);
+ expect(
+ client.getQueryData(channelLabelKeys.list(undefined, 'viewer').queryKey)
+ ).toEqual(labels);
+ });
+
+ it('keeps personal and team list caches independent', async () => {
+ mocks.enabled = () => true;
+ const Probe = () => {
+ useChannelLabelsQuery('personal');
+ useChannelLabelsQuery('team');
+ return null;
+ };
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+ await waitFor(() => expect(mocks.list).toHaveBeenCalledTimes(2));
+ expect(mocks.list).toHaveBeenCalledWith('personal');
+ expect(mocks.list).toHaveBeenCalledWith('team');
+ expect(channelLabelKeys.list('personal').queryKey).not.toEqual(
+ channelLabelKeys.list('team').queryKey
+ );
+ });
+
+ it('gates the extra personal query without disabling the original label rollout', async () => {
+ mocks.enabled = () => true;
+ const [sectionsEnabled, setSectionsEnabled] = createSignal(false);
+ let personal!: ReturnType<typeof useChannelLabelsQuery>;
+ const Probe = () => {
+ useChannelLabelsQuery();
+ personal = useChannelLabelsQuery('personal', sectionsEnabled);
+ return null;
+ };
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+ await waitFor(() =>
+ expect(mocks.list).toHaveBeenCalledExactlyOnceWith(undefined)
+ );
+ expect(personal.isEnabled).toBe(false);
+ setSectionsEnabled(true);
+ await waitFor(() => expect(mocks.list).toHaveBeenCalledWith('personal'));
+ setSectionsEnabled(false);
+ await waitFor(() => expect(personal.isEnabled).toBe(false));
+ await client.invalidateQueries({
+ queryKey: channelLabelKeys.list('personal', 'viewer').queryKey,
+ });
+ expect(
+ mocks.list.mock.calls.filter(([scope]) => scope === 'personal')
+ ).toHaveLength(1);
});
it('only previews smart tags while enabled', async () => {
@@ -120,4 +194,80 @@ describe('channel tag query rollout', () => {
await client.invalidateQueries({ queryKey: channelLabelKeys._def });
expect(mocks.preview).toHaveBeenCalledTimes(1);
});
+ it('does not publish late reads into another account', async () => {
+ const [userId, setUserId] = createSignal('viewer');
+ mocks.userId = userId;
+ mocks.enabled = () => true;
+ let finish!: (result: Ok<ChannelLabelsList, never>) => void;
+ mocks.list.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ const otherLabels = { ...labels, labels: [] };
+ mocks.list.mockResolvedValueOnce(ok(otherLabels));
+ let data!: ReturnType<typeof useChannelLabelsData>;
+ const Probe = () => {
+ data = useChannelLabelsData('personal');
+ return null;
+ };
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+ await waitFor(() => expect(mocks.list).toHaveBeenCalledTimes(1));
+ setUserId('new-viewer');
+ await waitFor(() => expect(data()).toEqual([]));
+ finish(ok(labels));
+ await waitFor(() =>
+ expect(
+ client.getQueryData(
+ channelLabelKeys.list('personal', 'viewer').queryKey
+ )
+ ).toEqual(labels)
+ );
+ expect(data()).toEqual([]);
+ });
+
+ it('rejects queued assignments after an account change', async () => {
+ const [userId, setUserId] = createSignal('viewer');
+ mocks.userId = userId;
+ let finish!: (result: Ok<void, never>) => void;
+ mocks.assign.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ let assign!: ReturnType<typeof useSetChannelLabelMutation>;
+ const Probe = () => {
+ assign = useSetChannelLabelMutation('personal');
+ return null;
+ };
+ render(() => (
+ <QueryClientProvider client={client}>
+ <Probe />
+ </QueryClientProvider>
+ ));
+ const first = assign.mutateAsync({
+ actorId: 'viewer',
+ channelId: 'channel-1',
+ labelId: 'section-1',
+ });
+ await waitFor(() => expect(mocks.assign).toHaveBeenCalledTimes(1));
+ const second = catchToResult(() =>
+ assign.mutateAsync({
+ actorId: 'viewer',
+ channelId: 'channel-2',
+ labelId: 'section-2',
+ })
+ );
+ setUserId('new-viewer');
+ finish(ok(undefined));
+ await first;
+ expect((await second).isErr()).toBe(true);
+ expect(mocks.assign).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.ts
index 57a229e714..723a493484 100644
--- a/apps/web/src/lib/queries/channel-labels/channel-labels.ts
+++ b/apps/web/src/lib/queries/channel-labels/channel-labels.ts
@@ -1,10 +1,12 @@
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { enableChannelTags } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
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 { ChannelLabelScopeSelection } from '@service-storage/generated/schemas/channelLabelScopeSelection';
import type { ChannelLabelsList } from '@service-storage/generated/schemas/channelLabelsList';
import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
@@ -12,13 +14,18 @@ import { queryClient } from '../client';
import { withCallbacks } from '../utils';
import { channelLabelKeys } from './keys';
-export type { ChannelLabel };
+export type { ChannelLabel, ChannelLabelScopeSelection };
-function channelLabelsQueryOptions(enabled: boolean) {
+function channelLabelsQueryOptions(
+ enabled: boolean,
+ scope: ChannelLabelScopeSelection | undefined,
+ actorId: string | undefined
+) {
return queryOptions({
- queryKey: channelLabelKeys.list.queryKey,
- enabled,
- queryFn: () => throwOnErr(() => storageServiceClient.channelLabels.list()),
+ queryKey: channelLabelKeys.list(scope, actorId).queryKey,
+ enabled: enabled && Boolean(actorId),
+ queryFn: () =>
+ throwOnErr(() => storageServiceClient.channelLabels.list(scope)),
staleTime: 30_000,
refetchInterval: (query) =>
query.state.data?.labels.some((label) => label.rule) ? 30_000 : false,
@@ -27,27 +34,48 @@ function channelLabelsQueryOptions(enabled: boolean) {
}
/** Shared labels for team members; account-private labels otherwise. */
-export function useChannelLabelsQuery() {
+export function useChannelLabelsQuery(
+ scope?: ChannelLabelScopeSelection,
+ enabled: Accessor<boolean> = () => true
+) {
const channelTagsFlag = useFeatureFlag(enableChannelTags);
- return useQuery(() => channelLabelsQueryOptions(channelTagsFlag().enabled));
+ const userId = useUserId();
+ return useQuery(() =>
+ channelLabelsQueryOptions(
+ channelTagsFlag().enabled && enabled(),
+ scope,
+ userId()
+ )
+ );
}
/** Non-suspending view of labels, undefined until successfully loaded. */
-export function useChannelLabelsData(): Accessor<ChannelLabel[] | undefined> {
- const query = useChannelLabelsQuery();
+export function useChannelLabelsData(
+ scope?: ChannelLabelScopeSelection
+): Accessor<ChannelLabel[] | undefined> {
+ const query = useChannelLabelsQuery(scope);
return () =>
- query.isEnabled && query.isSuccess ? query.data.labels : undefined;
+ query.isEnabled && !query.isPending ? query.data?.labels : undefined;
}
-export function invalidateChannelLabels() {
+export function invalidateChannelLabels(
+ scope?: ChannelLabelScopeSelection,
+ actorId?: string
+) {
return queryClient.invalidateQueries({
- queryKey: channelLabelKeys.list.queryKey,
+ queryKey: actorId
+ ? channelLabelKeys.list(scope, actorId).queryKey
+ : channelLabelKeys.list._def,
});
}
-function writeLabels(update: (labels: ChannelLabel[]) => ChannelLabel[]) {
+function writeLabels(
+ scope: ChannelLabelScopeSelection | undefined,
+ actorId: string | undefined,
+ update: (labels: ChannelLabel[]) => ChannelLabel[]
+) {
queryClient.setQueryData<ChannelLabelsList>(
- channelLabelKeys.list.queryKey,
+ channelLabelKeys.list(scope, actorId).queryKey,
(previous) =>
previous ? { ...previous, labels: update(previous.labels) } : previous
);
@@ -56,19 +84,30 @@ function writeLabels(update: (labels: ChannelLabel[]) => ChannelLabel[]) {
// 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 });
+async function cancelLabelFetch(
+ scope: ChannelLabelScopeSelection | undefined,
+ actorId: string | undefined
+) {
+ await queryClient.cancelQueries({
+ queryKey: channelLabelKeys.list(scope, actorId).queryKey,
+ });
}
-function smartTagPreviewQueryOptions(contains: string, enabled: boolean) {
+function smartTagPreviewQueryOptions(
+ contains: string,
+ enabled: boolean,
+ scope: ChannelLabelScopeSelection | undefined,
+ actorId: string | undefined
+) {
return queryOptions({
- queryKey: channelLabelKeys.preview(contains).queryKey,
- enabled,
+ queryKey: channelLabelKeys.preview(contains, scope, actorId).queryKey,
+ enabled: enabled && Boolean(actorId),
queryFn: ({ signal }) =>
throwOnErr(() =>
storageServiceClient.channelLabels.preview(
{ attribute: 'name', contains },
- signal
+ signal,
+ scope
)
),
staleTime: 0,
@@ -76,8 +115,12 @@ function smartTagPreviewQueryOptions(contains: string, enabled: boolean) {
});
}
-export function useSmartTagPreviewQuery(pattern: Accessor<string>) {
+export function useSmartTagPreviewQuery(
+ pattern: Accessor<string>,
+ scope?: ChannelLabelScopeSelection
+) {
const channelTagsFlag = useFeatureFlag(enableChannelTags);
+ const userId = useUserId();
const debouncedPattern = debouncedDependent(pattern, 150);
return useQuery(() => {
const contains = pattern();
@@ -85,26 +128,46 @@ export function useSmartTagPreviewQuery(pattern: Accessor<string>) {
contains,
channelTagsFlag().enabled &&
contains.length > 0 &&
- contains === debouncedPattern()
+ contains === debouncedPattern(),
+ scope,
+ userId()
);
});
}
export type CreateChannelLabelArgs = {
+ actorId: string | undefined;
name: string;
channelIds: string[];
rule?: ChannelLabelRule;
};
-export function useCreateChannelLabelMutation() {
+export function useCreateChannelLabelMutation(
+ scope?: ChannelLabelScopeSelection
+) {
+ const userId = useUserId();
return useMutation(() => ({
scope: mutationScope,
- mutationFn: async (args: CreateChannelLabelArgs) =>
- await throwOnErr(() => storageServiceClient.channelLabels.create(args)),
+ mutationFn: async (args: CreateChannelLabelArgs) => {
+ if (!args.actorId || args.actorId !== userId())
+ throw new Error('The account has changed.');
+ return await throwOnErr(() =>
+ storageServiceClient.channelLabels.create(
+ {
+ name: args.name,
+ channelIds: args.channelIds,
+ rule: args.rule,
+ },
+ scope
+ )
+ );
+ },
...withCallbacks<ChannelLabel, Error, CreateChannelLabelArgs>({
- onSuccess: async (created) => {
- await cancelLabelFetch();
- writeLabels((labels) =>
+ onSuccess: async (created, args) => {
+ if (args.actorId !== userId()) return;
+ await cancelLabelFetch(scope, args.actorId);
+ if (args.actorId !== userId()) return;
+ writeLabels(scope, args.actorId, (labels) =>
labels
.map((label) => {
if (created.rule || label.rule) return label;
@@ -122,75 +185,119 @@ export function useCreateChannelLabelMutation() {
.concat(created)
);
},
- onSettled: () => invalidateChannelLabels(),
+ onSettled: (_data, _error, args) => {
+ if (args.actorId === userId())
+ return invalidateChannelLabels(scope, args.actorId);
+ },
}),
}));
}
export type RenameChannelLabelArgs = {
+ actorId: string | undefined;
labelId: string;
name: string;
rule?: ChannelLabelRule;
};
-export function useRenameChannelLabelMutation() {
+export function useRenameChannelLabelMutation(
+ scope?: ChannelLabelScopeSelection
+) {
+ const userId = useUserId();
return useMutation(() => ({
scope: mutationScope,
- mutationFn: async (args: RenameChannelLabelArgs) =>
- await throwOnErr(() =>
- storageServiceClient.channelLabels.rename(args.labelId, {
- name: args.name,
- rule: args.rule,
- })
- ),
+ mutationFn: async (args: RenameChannelLabelArgs) => {
+ if (!args.actorId || args.actorId !== userId())
+ throw new Error('The account has changed.');
+ return await throwOnErr(() =>
+ storageServiceClient.channelLabels.rename(
+ args.labelId,
+ {
+ name: args.name,
+ rule: args.rule,
+ },
+ scope
+ )
+ );
+ },
...withCallbacks<ChannelLabel, Error, RenameChannelLabelArgs>({
- onSuccess: async (renamed) => {
- await cancelLabelFetch();
- writeLabels((labels) =>
+ onSuccess: async (renamed, args) => {
+ if (args.actorId !== userId()) return;
+ await cancelLabelFetch(scope, args.actorId);
+ if (args.actorId !== userId()) return;
+ writeLabels(scope, args.actorId, (labels) =>
labels.map((label) => (label.id === renamed.id ? renamed : label))
);
},
- onSettled: () => invalidateChannelLabels(),
+ onSettled: (_data, _error, args) => {
+ if (args.actorId === userId())
+ return invalidateChannelLabels(scope, args.actorId);
+ },
}),
}));
}
-export type DeleteChannelLabelArgs = { labelId: string };
-export function useDeleteChannelLabelMutation() {
+export type DeleteChannelLabelArgs = {
+ labelId: string;
+ actorId: string | undefined;
+};
+export function useDeleteChannelLabelMutation(
+ scope?: ChannelLabelScopeSelection
+) {
+ const userId = useUserId();
return useMutation(() => ({
scope: mutationScope,
- mutationFn: async (args: DeleteChannelLabelArgs) =>
- await throwOnErr(() =>
- storageServiceClient.channelLabels.remove(args.labelId)
- ),
+ mutationFn: async (args: DeleteChannelLabelArgs) => {
+ if (!args.actorId || args.actorId !== userId())
+ throw new Error('The account has changed.');
+ return await throwOnErr(() =>
+ storageServiceClient.channelLabels.remove(args.labelId, scope)
+ );
+ },
...withCallbacks<void, Error, DeleteChannelLabelArgs>({
onSuccess: async (_data, args) => {
- await cancelLabelFetch();
- writeLabels((labels) =>
+ if (args.actorId !== userId()) return;
+ await cancelLabelFetch(scope, args.actorId);
+ if (args.actorId !== userId()) return;
+ writeLabels(scope, args.actorId, (labels) =>
labels.filter((label) => label.id !== args.labelId)
);
},
- onSettled: () => invalidateChannelLabels(),
+ onSettled: (_data, _error, args) => {
+ if (args.actorId === userId())
+ return invalidateChannelLabels(scope, args.actorId);
+ },
}),
}));
}
export type SetChannelLabelArgs = {
+ actorId: string | undefined;
channelId: string;
labelId: string | undefined;
};
-export function useSetChannelLabelMutation() {
+export function useSetChannelLabelMutation(scope?: ChannelLabelScopeSelection) {
+ const userId = useUserId();
return useMutation(() => ({
scope: mutationScope,
- mutationFn: async (args: SetChannelLabelArgs) =>
- await throwOnErr(() =>
- storageServiceClient.channelLabels.setChannelLabel(args.channelId, {
- labelId: args.labelId ?? null,
- })
- ),
+ mutationFn: async (args: SetChannelLabelArgs) => {
+ if (!args.actorId || args.actorId !== userId())
+ throw new Error('The account has changed.');
+ return await throwOnErr(() =>
+ storageServiceClient.channelLabels.setChannelLabel(
+ args.channelId,
+ {
+ labelId: args.labelId ?? null,
+ },
+ scope
+ )
+ );
+ },
...withCallbacks<void, Error, SetChannelLabelArgs>({
onSuccess: async (_data, args) => {
- await cancelLabelFetch();
- writeLabels((labels) =>
+ if (args.actorId !== userId()) return;
+ await cancelLabelFetch(scope, args.actorId);
+ if (args.actorId !== userId()) return;
+ writeLabels(scope, args.actorId, (labels) =>
labels.map((label) => {
if (label.rule) return label;
const channelIds = label.channelIds.filter(
@@ -209,7 +316,10 @@ export function useSetChannelLabelMutation() {
})
);
},
- onSettled: () => invalidateChannelLabels(),
+ onSettled: (_data, _error, args) => {
+ if (args.actorId === userId())
+ return invalidateChannelLabels(scope, args.actorId);
+ },
}),
}));
}
diff --git a/apps/web/src/lib/queries/channel-labels/keys.ts b/apps/web/src/lib/queries/channel-labels/keys.ts
index bcd5d215e8..f01bf50cad 100644
--- a/apps/web/src/lib/queries/channel-labels/keys.ts
+++ b/apps/web/src/lib/queries/channel-labels/keys.ts
@@ -1,6 +1,14 @@
import { createQueryKeys } from '@lukemorales/query-key-factory';
+import type { ChannelLabelScopeSelection } from '@service-storage/generated/schemas/channelLabelScopeSelection';
export const channelLabelKeys = createQueryKeys('channel-labels', {
- list: null,
- preview: (pattern: string) => [pattern],
+ list: (scope?: ChannelLabelScopeSelection, actorId?: string) => [
+ scope ?? 'default',
+ actorId ?? 'signed-out',
+ ],
+ preview: (
+ pattern: string,
+ scope?: ChannelLabelScopeSelection,
+ actorId?: string
+ ) => [scope ?? 'default', pattern, actorId ?? 'signed-out'],
});
diff --git a/apps/web/src/lib/queries/channel/by-ids.ts b/apps/web/src/lib/queries/channel/by-ids.ts
new file mode 100644
index 0000000000..13ebf9ad3e
--- /dev/null
+++ b/apps/web/src/lib/queries/channel/by-ids.ts
@@ -0,0 +1,152 @@
+import {
+ compileToAst,
+ defineQueryFilters,
+ queryStateFrom,
+} from '@app/features/next-soup/filters/filter-store';
+import { useUserId } from '@core/context/user';
+import { arrayEquals } from '@core/util/compareUtils';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { isChannelEntity } from '@entity';
+import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
+import { type Accessor, createEffect, createMemo, untrack } from 'solid-js';
+import { queryReadyGate } from '../gate';
+import {
+ type SoupAstItemsQuery,
+ type SoupAstItemsQueryArgs,
+ useSoupAstItemsQuery,
+} from '../soup/items';
+import { registerChannelNotificationRefresh } from './register-notification-refresh';
+
+const BATCH_SIZE = 500;
+
+export function channelsByIdsQueryArgs(
+ channelIds: readonly string[]
+): SoupAstItemsQueryArgs {
+ return {
+ params: {
+ limit: Math.min(BATCH_SIZE, Math.max(1, channelIds.length)),
+ sort_method: 'created_at',
+ },
+ body: compileToAst(
+ queryStateFrom(
+ defineQueryFilters({ include: { channelId: [...channelIds] } })
+ )
+ ),
+ };
+}
+
+/** Keep each channel list's bounded unread projection current, including cached rows. */
+export function registerChannelListNotificationRefresh(
+ query: SoupAstItemsQuery
+) {
+ return registerChannelNotificationRefresh(() => ({
+ client: getGraphqlSoupClient(),
+ queries: query.revalidationQueries ?? [],
+ reader: {
+ enabled: query.transport === 'graphql' && query.isEnabled,
+ fetching: query.isFetching,
+ filtered: true,
+ notificationIds: query.isPending
+ ? []
+ : (query.data?.entities ?? [])
+ .filter(isChannelEntity)
+ .flatMap((channel) =>
+ (channel.unreadNotifications ?? []).map(({ id }) => id)
+ ),
+ },
+ }));
+}
+
+/** One Soup owner supplies local rows, missing-record fetches, and unread updates. */
+export function useChannelsByIdsQuery(
+ channelIds: Accessor<readonly string[]>,
+ options: Accessor<{ cacheFirst?: boolean }> = () => ({})
+) {
+ const query = useSoupAstItemsQuery(
+ () => channelsByIdsQueryArgs(channelIds()),
+ () => ({
+ enabled: channelIds().length > 0,
+ staleTime: 30_000,
+ graphqlProjection: 'channel-list',
+ graphqlCacheFirstEntities: options().cacheFirst
+ ? channelIds().map((entityId) => ({ entityType: 'CHANNEL', entityId }))
+ : undefined,
+ })
+ );
+ registerChannelListNotificationRefresh(query);
+ createEffect(() => {
+ if (
+ !query.isEnabled ||
+ query.isPending ||
+ query.isFetching ||
+ query.fetchError ||
+ query.error ||
+ !query.hasNextPage
+ )
+ return;
+ fireAndForget(query.fetchNextPage(), 'channels-by-id');
+ });
+ return query;
+}
+
+/** Resolve an authoritative ID set without loading unrelated list pages. */
+export function useCachedChannelsByIds(
+ ids: Accessor<readonly string[]>,
+ enabled: Accessor<boolean>
+) {
+ const userId = useUserId();
+ const memberIds = createMemo(() => [...new Set(ids())].sort(), [], {
+ equals: arrayEquals,
+ });
+ const source = createMemo(() => {
+ const members = memberIds();
+ if (!enabled() || !userId()) return [];
+ return untrack(() => {
+ const batches = [];
+ for (let offset = 0; offset < members.length; offset += BATCH_SIZE) {
+ const batchIds = members.slice(offset, offset + BATCH_SIZE);
+ const query = useChannelsByIdsQuery(
+ () => batchIds,
+ () => ({ cacheFirst: true })
+ );
+ const channels = () =>
+ queryReadyGate(query)
+ ? query.data.entities.filter(isChannelEntity)
+ : [];
+ const unresolved = () => {
+ const loaded = new Set(channels().map((channel) => channel.id));
+ return batchIds.filter((id) => !loaded.has(id));
+ };
+ const error = () => query.fetchError ?? query.error;
+ const loading = () =>
+ !error() &&
+ (query.isPending || query.isFetching || query.hasNextPage);
+ batches.push({ query, channels, unresolved, error, loading });
+ }
+ return batches;
+ });
+ });
+ return {
+ channels: () => source().flatMap((batch) => batch.channels()),
+ pendingIds: () =>
+ new Set(
+ source().flatMap((batch) => (batch.loading() ? batch.unresolved() : []))
+ ),
+ failedIds: () =>
+ new Set(
+ source().flatMap((batch) => (batch.error() ? batch.unresolved() : []))
+ ),
+ isLoading: () => source().some((batch) => batch.loading()),
+ error: () =>
+ source()
+ .find((batch) => batch.error() && batch.unresolved().length)
+ ?.error(),
+ retry: async () => {
+ await Promise.all(
+ source()
+ .filter((batch) => batch.error() && batch.unresolved().length)
+ .map((batch) => batch.query.refresh())
+ );
+ },
+ };
+}
diff --git a/apps/web/src/lib/queries/soup/graphql/create-predicate-query.ts b/apps/web/src/lib/queries/soup/graphql/create-predicate-query.ts
index 013cf118cd..79f3068736 100644
--- a/apps/web/src/lib/queries/soup/graphql/create-predicate-query.ts
+++ b/apps/web/src/lib/queries/soup/graphql/create-predicate-query.ts
@@ -45,6 +45,12 @@ type LiveQueryHost = Pick<
'entityFilter' | 'onCacheChanged' | 'onCacheGenerationChanged'
>;
+export type PredicateQueryStatus =
+ | 'idle'
+ | 'loading'
+ | 'ready'
+ | 'unsupported'
+ | 'error';
/**
* Binds one cache-engine maintained view for `createSoupLiveQuery`. Owns
* subscription, coalescing, generation recovery, and keyed Solid rows.
@@ -57,9 +63,7 @@ export function createPredicateQuery<T extends object>(options: {
query: Accessor<PredicateQueryRequest<T> | undefined>;
}) {
const [data, setData] = createSignal<LiveQuerySnapshot<T>>();
- const [status, setStatus] = createSignal<
- 'idle' | 'loading' | 'ready' | 'unsupported' | 'error'
- >('idle');
+ const [status, setStatus] = createSignal<PredicateQueryStatus>('idle');
const [error, setError] = createSignal<unknown>();
let requestRefresh = () => {};
// A caller may derive a new request object from a query snapshot even when
diff --git a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts
index efc232b34f..a1f622cee0 100644
--- a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts
+++ b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts
@@ -1,5 +1,6 @@
import { fireAndForget } from '@core/util/fireAndForget';
import { Telemetry } from '@macro-inc/observability';
+import { until } from '@solid-primitives/promise';
import type { CombinedError } from '@urql/core';
import {
type Accessor,
@@ -8,8 +9,10 @@ import {
createEffect,
createMemo,
createSignal,
+ getOwner,
on,
onCleanup,
+ runWithOwner,
untrack,
} from 'solid-js';
import { NIL as NIL_UUID } from 'uuid';
@@ -18,6 +21,7 @@ import { createBrowserOfflineSignal } from '../../../core/util/connectivity';
import { isResponseFreeNetworkError } from '../../../core/util/request-error';
import { querySnapshot } from '../../../graphql-cache/exchange/live-query';
import { normalizedCacheResultMetadata } from '../../../graphql-cache/exchange/normalized-cache-exchange';
+import type { QueryRevalidation } from '../../../graphql-cache/exchange/optimistic';
import { selectRecords } from '../../../graphql-cache/exchange/record-selection';
import {
type CacheRevision,
@@ -45,12 +49,16 @@ import {
} from '../../../service-clients/service-storage/graphql-soup';
import { createUrqlInfiniteQuery } from '../../../urql-solid/create-urql-infinite-query';
import type { UrqlInfiniteData } from '../../../urql-solid/types';
-import { registerChannelNotificationRefresh } from '../../channel/register-notification-refresh';
import { registerGraphqlSoupRevalidations } from './active-queries';
import { createPredicateQuery } from './create-predicate-query';
+import {
+ buildGraphqlEntitiesSoupInput,
+ type SoupEntityRef,
+ soupEntityRefKey,
+} from './entity-input';
import { isCachedMailView } from './mail-view';
import {
- usePendingGraphqlSoupDeleteIds,
+ usePendingGraphqlSoupDeleteKeys,
withoutPendingSoupEntities,
} from './optimistic-deletions';
import { readSoupPage } from './read-soup-page';
@@ -72,6 +80,8 @@ export type SoupLiveQueryOptions = {
localOnly?: boolean;
/** Select bounded unread evidence for channel navigation. */
projection?: 'channel-list';
+ /** Select known entities locally, then fetch only missing records. */
+ cacheFirstEntities?: readonly SoupEntityRef[];
/** Include indexed non-email rows while server pages supply email. */
localReconciliation?: 'without-email';
};
@@ -91,7 +101,8 @@ export function createSoupLiveQuery(
request: Accessor<SoupLiveQueryInput | undefined>,
options: Accessor<SoupLiveQueryOptions> = () => ({})
) {
- const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();
+ const owner = getOwner();
+ const pendingDeleteKeys = usePendingGraphqlSoupDeleteKeys();
const offline = createBrowserOfflineSignal();
const [fetchingMailPage, setFetchingMailPage] = createSignal(false);
// The position of the last local Mail row loaded (a page's `endCursor`).
@@ -107,14 +118,31 @@ export function createSoupLiveQuery(
// keep the page current; incomplete or failed ones leave the network page.
const [localMailCurrent, setLocalMailCurrent] = createSignal(false);
- const firstPageInput = createMemo<GraphqlSoupInput | undefined>(() => {
+ const firstPageInput = createMemo(() => {
const input = request();
return input ? { initial: { ...input, expand: true } } : undefined;
});
+ type EntityHydration = {
+ scope: GraphqlSoupInput;
+ generation: number;
+ entities: readonly SoupEntityRef[];
+ input: GraphqlSoupInput | undefined;
+ };
+ const [entityHydration, setEntityHydration] = createSignal<EntityHydration>();
+ const cacheFirstEntities = () => options().cacheFirstEntities !== undefined;
+ const networkInput = () => {
+ if (!cacheFirstEntities()) return firstPageInput();
+ const hydration = entityHydration();
+ return hydration &&
+ hydration.scope === firstPageInput() &&
+ hydration.generation === cacheGeneration
+ ? hydration.input
+ : undefined;
+ };
const inputForCursor = (
cursor: string | null
): GraphqlSoupInput | undefined => {
- const input = firstPageInput();
+ const input = networkInput();
if (!input || !('initial' in input) || !input.initial) return;
if (cursor === null) return input;
return {
@@ -371,7 +399,7 @@ export function createSoupLiveQuery(
enabled:
queryOptions.enabled !== false &&
!queryOptions.localOnly &&
- firstInput !== undefined,
+ networkInput() !== undefined,
requestPolicy: queryOptions.networkPaused
? 'cache-only'
: 'cache-and-network',
@@ -454,52 +482,31 @@ export function createSoupLiveQuery(
};
});
+ const isEnabled = () =>
+ cacheFirstEntities()
+ ? options().enabled !== false && !options().localOnly && isSupported()
+ : query.isEnabled;
+
+ const revalidationQueries = (): QueryRevalidation[] => {
+ if (!isEnabled()) return [];
+ if (cacheFirstEntities()) {
+ const input = firstPageInput();
+ return input ? [{ document: queryDocument(), variables: { input } }] : [];
+ }
+ const cursors = new Set([null, ...(query.data?.pageParams ?? [])]);
+ return [...cursors].flatMap((cursor) => {
+ const input = inputForCursor(cursor);
+ return input ? [{ document: queryDocument(), variables: { input } }] : [];
+ });
+ };
onCleanup(
registerGraphqlSoupRevalidations(
- () => {
- if (!query.isEnabled) return [];
- const cursors = new Set([null, ...(query.data?.pageParams ?? [])]);
- return [...cursors].flatMap((cursor) => {
- const input = inputForCursor(cursor);
- return input
- ? [{ document: queryDocument(), variables: { input } }]
- : [];
- });
- },
+ revalidationQueries,
getGraphqlSoupClient,
() => cacheMaintained()
)
);
- registerChannelNotificationRefresh(() => ({
- client: getGraphqlSoupClient(),
- // urql retains loaded pages after errors; keep them registered for retry.
- queries:
- options().projection === 'channel-list'
- ? [...new Set([null, ...(query.data?.pageParams ?? [])])].flatMap(
- (cursor) => {
- const input = inputForCursor(cursor);
- return input
- ? [{ document: queryDocument(), variables: { input } }]
- : [];
- }
- )
- : [],
- reader: {
- enabled: query.isEnabled && !options().networkPaused,
- fetching: query.isFetching,
- filtered: true,
- notificationIds: query.isSuccess
- ? (query.data?.records() ?? []).flatMap((item) =>
- item.__typename === 'GraphqlSoupChannel' &&
- 'unreadNotifications' in item
- ? (item.unreadNotifications?.map((n) => n.id) ?? [])
- : []
- )
- : [],
- },
- }));
-
// Capture membership/sort evidence for each published projection, so a later
// cache revision cannot change the baseline of an in-flight reconciliation.
const serverRecords = createMemo(() =>
@@ -521,7 +528,7 @@ export function createSoupLiveQuery(
!input ||
!('initial' in input) ||
!input.initial ||
- hasUnpersistedPages(input)
+ (!cacheFirstEntities() && hasUnpersistedPages(input))
)
return;
const initial = input.initial;
@@ -622,10 +629,20 @@ export function createSoupLiveQuery(
undefined,
{ equals: arrayEquals }
);
- maintainedProjection = createMemo(() => {
+ maintainedProjection = createMemo<LocalProjection | undefined>((previous) => {
const snapshot = live.data();
const input = firstPageInput();
- if (!snapshot || !input || !maintainedQueryAvailable()) return;
+ if (!snapshot || !input || !maintainedQueryAvailable()) {
+ // A baseline refresh must not hide already selected members while the
+ // predicate incorporates the new server page.
+ if (
+ cacheFirstEntities() &&
+ previous?.input === input &&
+ previous?.generation === cacheGeneration
+ )
+ return previous;
+ return;
+ }
const withoutEmail = options().localReconciliation === 'without-email';
return {
input,
@@ -644,6 +661,44 @@ export function createSoupLiveQuery(
};
});
+ createEffect(() => {
+ const entities = options().cacheFirstEntities;
+ const input = firstPageInput();
+ if (!entities || !input) return;
+ if (options().enabled === false) return;
+ const current = entityHydration();
+ const cacheStatus = live.status();
+ const sameScope =
+ current?.scope === input && current.generation === cacheGeneration;
+ // Keep variables and continuation cursors fixed through success or retry.
+ if (sameScope && (query.isFetching || query.hasNextPage || query.error))
+ return;
+ if (
+ getGraphqlSoupCacheHost()?.liveQueries &&
+ localSource() &&
+ (cacheStatus === 'idle' || cacheStatus === 'loading')
+ )
+ return;
+ const known = new Set(liveRecords().map(soupItemKey));
+ const requested = sameScope ? current.entities : [];
+ const requestedKeys = new Set(requested.map(soupEntityRefKey));
+ const missing = entities.filter((entity) => {
+ const key = soupEntityRefKey(entity);
+ return key !== undefined && !known.has(key) && !requestedKeys.has(key);
+ });
+ if (sameScope && missing.length === 0) return;
+ const nextEntities = [...requested, ...missing];
+ const lookup = buildGraphqlEntitiesSoupInput(nextEntities);
+ setEntityHydration({
+ scope: input,
+ generation: cacheGeneration,
+ entities: nextEntities,
+ input: lookup?.initial
+ ? { initial: { ...input.initial, filters: lookup.initial.filters } }
+ : undefined,
+ });
+ });
+
createEffect(() => {
localEvaluationTrigger();
const revision = currentCacheRevision();
@@ -881,13 +936,16 @@ export function createSoupLiveQuery(
local.withoutEmail !== (options().localReconciliation === 'without-email')
)
return undefined;
+ if (cacheFirstEntities()) return local;
// A partial projection with no visible rows after pending deletes cannot
// prove that a folder is empty (it could contain only email). Keep initial
// loading/errors until the server establishes membership.
if (
local.withoutEmail &&
!query.data &&
- local.records.every((record) => pendingDeleteIds().has(record.id))
+ local.records.every((record) =>
+ pendingDeleteKeys().has(soupItemKey(record))
+ )
)
return undefined;
const keys = serverRecordKeys();
@@ -915,8 +973,19 @@ export function createSoupLiveQuery(
// or fails. Preserve covered decisions and local additions, then append new
// rows in server-page order until a successful reconciliation orders the union.
const displayData = createMemo((): GraphqlSoupItem[] | undefined => {
- if (networkIsAuthoritative()) return query.data?.records();
const local = displayLocalProjection();
+ if (networkIsAuthoritative()) {
+ const fetched = query.data?.records();
+ if (!cacheFirstEntities() || !local) return fetched;
+ return [
+ ...new Map(
+ [...local.records, ...(fetched ?? [])].map((record) => [
+ soupItemKey(record),
+ record,
+ ])
+ ).values(),
+ ];
+ }
if (!local) return query.data?.records();
// Mail merges new server evidence in its ordered through-read. Appending
// it here would bypass membership decisions and the local cursor order.
@@ -1001,18 +1070,28 @@ export function createSoupLiveQuery(
return {
cacheMaintained,
+ revalidationQueries,
+ /** Local predicate readiness is separate from network loading and membership completeness. */
+ cacheStatus: () =>
+ !getGraphqlSoupCacheHost()?.liveQueries || !localSource()
+ ? ('unsupported' as const)
+ : live.status(),
queryScope: () => JSON.stringify([firstPageInput(), cacheGeneration]),
localRevision: () => displayLocalProjection()?.mail?.revision,
localOptimistic: () => displayLocalProjection()?.mail?.optimistic ?? false,
data: createMemo(() => {
const records = displayData();
- return records && withoutPendingSoupEntities(records, pendingDeleteIds());
+ return (
+ records &&
+ withoutPendingSoupEntities(records, pendingDeleteKeys(), soupItemKey)
+ );
}),
fetchedRecords: () => query.data?.records() ?? [],
cachedMail,
error,
+ fetchError: () => query.error ?? undefined,
isSupported,
- isEnabled: () => query.isEnabled,
+ isEnabled,
isLoading: () => {
if (!query.isLoading) return false;
const local = displayLocalProjection();
@@ -1158,7 +1237,22 @@ export function createSoupLiveQuery(
});
},
refresh: async () => {
- if (firstPageInput() === undefined) return;
+ const input = firstPageInput();
+ if (input === undefined) return;
+ // A fully cached lookup still participates in explicit refreshes.
+ if (cacheFirstEntities() && !networkInput()) {
+ setEntityHydration({
+ scope: input,
+ generation: cacheGeneration,
+ entities: options().cacheFirstEntities ?? [],
+ input,
+ });
+ await runWithOwner(owner, () =>
+ until(() => !query.isFetching && (query.isSuccess || query.error))
+ );
+ if (query.error) throw query.error;
+ return;
+ }
// An explicit list refresh rebuilds the cursor chain in order. The
// notification queue observes isFetching and waits for this to finish.
await query.refetch({
diff --git a/apps/web/src/lib/queries/soup/graphql/done-projection.test.ts b/apps/web/src/lib/queries/soup/graphql/done-projection.test.ts
index 19683f656c..9bcdad79f9 100644
--- a/apps/web/src/lib/queries/soup/graphql/done-projection.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/done-projection.test.ts
@@ -133,7 +133,13 @@ it('does not restore into another filter/sort scope or over a deletion', () => {
project('signal', page([email('a')]), [done], true, deleted);
const undone = { ...done, done: false };
expect(
- project('signal', page([]), [undone], true, new Set(['a']))?.entities
+ project(
+ 'signal',
+ page([]),
+ [undone],
+ true,
+ new Set(['GraphqlSoupEmailThread:a'])
+ )?.entities
).toEqual([]);
expect(project('noise', page([]), [undone], true, deleted)?.entities).toEqual(
[]
diff --git a/apps/web/src/lib/queries/soup/graphql/done-projection.ts b/apps/web/src/lib/queries/soup/graphql/done-projection.ts
index fdcbe61b6f..9d204a4c8b 100644
--- a/apps/web/src/lib/queries/soup/graphql/done-projection.ts
+++ b/apps/web/src/lib/queries/soup/graphql/done-projection.ts
@@ -2,6 +2,7 @@ import type { EntityData } from '@entity/types/entity';
import type { Notification } from '@entity/types/notification';
import { onCleanup } from 'solid-js';
import type { SoupAstItemsData } from '../items';
+import { soupEntityKey } from './entity-input';
import { withoutPendingGraphqlSoupDeletes } from './optimistic-deletions';
import {
hasActivityAfterDone,
@@ -162,7 +163,7 @@ export function createGraphqlSoupDoneProjection() {
data: SoupAstItemsData | undefined,
pending: readonly PendingGraphqlSoupDone[],
excludesDone: boolean,
- deletedIds: ReadonlySet<string>
+ deletedKeys: ReadonlySet<string>
): SoupAstItemsData | undefined => {
detach();
if (scope !== queryScope) {
@@ -182,7 +183,7 @@ export function createGraphqlSoupDoneProjection() {
return undefined;
}
if (pending.length === 0) {
- return withoutPendingGraphqlSoupDeletes(data, deletedIds);
+ return withoutPendingGraphqlSoupDeletes(data, deletedKeys);
}
const latest = new Map<string, PendingGraphqlSoupDone>();
@@ -228,7 +229,7 @@ export function createGraphqlSoupDoneProjection() {
excludesDone &&
!current &&
snapshot &&
- !deletedIds.has(id)
+ !deletedKeys.has(soupEntityKey(snapshot.entity) ?? '')
) {
restoring.push(snapshot);
}
@@ -247,10 +248,14 @@ export function createGraphqlSoupDoneProjection() {
result = { ...result, entities };
}
return withoutPendingGraphqlSoupDeletes(
- result,
excludesDone
- ? withPendingDoneIds(deletedIds, result.entities, pending)
- : deletedIds
+ ? withoutPendingGraphqlSoupDeletes(
+ result,
+ withPendingDoneIds(new Set(), result.entities, pending),
+ 'id'
+ )
+ : result,
+ deletedKeys
);
};
}
diff --git a/apps/web/src/lib/queries/soup/graphql/entity-input.ts b/apps/web/src/lib/queries/soup/graphql/entity-input.ts
index 974de1c408..2435a0ec54 100644
--- a/apps/web/src/lib/queries/soup/graphql/entity-input.ts
+++ b/apps/web/src/lib/queries/soup/graphql/entity-input.ts
@@ -1,5 +1,9 @@
+import type { EntityData } from '@entity/types/entity';
import type { EntityType } from '@service-properties/generated/schemas/entityType';
+import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
+import type { SoupApiItem } from '@service-storage/generated/schemas/soupApiItem';
import type {
+ EntityRefInput,
GraphqlEntityFilterAst,
SoupInput,
} from '@service-storage/graphql/generated/graphql';
@@ -9,6 +13,64 @@ const NIL_ENTITY_ID = '00000000-0000-0000-0000-000000000000';
type OrExpr<T> = T | { or: { left: OrExpr<T>; right: OrExpr<T> } };
+/** A Soup entity with a known identity, independent of list membership. */
+export type SoupEntityRef = {
+ entityType: Exclude<EntityType, 'USER' | 'CONTACT'>;
+ entityId: string;
+};
+
+/** Match the normalized identity used by Soup records, including task documents. */
+export function soupEntityRefKey(entity: SoupEntityRef): string | undefined {
+ const typename = match(entity.entityType)
+ .with('DOCUMENT', 'TASK', () => 'GraphqlSoupDocument')
+ .with('PROJECT', () => 'GraphqlSoupProject')
+ .with('CHAT', () => 'GraphqlSoupChat')
+ .with('THREAD', () => 'GraphqlSoupEmailThread')
+ .with('CHANNEL', () => 'GraphqlSoupChannel')
+ .with('CALL_RECORD', () => 'GraphqlSoupCall')
+ .with('COMPANY', () => 'GraphqlSoupCrmCompany')
+ .with('CALENDAR_EVENT', () => 'GraphqlSoupCalendarEvent')
+ .with('INITIATIVE', () => 'GraphqlSoupInitiative')
+ .with('DATABASE_ROW', () => 'GraphqlSoupDatabaseRow')
+ .exhaustive(() => undefined);
+ return typename ? `${typename}:${entity.entityId}` : undefined;
+}
+
+/** Normalized identity for display entities and unified mutation targets. */
+export function soupEntityKey(entity: {
+ type:
+ | EntityData['type']
+ | EntityRefInput['type']
+ | SoupApiItem['tag']
+ | UnifiedSearchResponseItem['type'];
+ id: string | number;
+}): string | undefined {
+ const typename = match(entity.type)
+ .with('document', 'DOCUMENT', () => 'GraphqlSoupDocument')
+ .with('chat', 'CHAT', () => 'GraphqlSoupChat')
+ .with('project', 'PROJECT', () => 'GraphqlSoupProject')
+ .with('channel', 'CHANNEL', () => 'GraphqlSoupChannel')
+ .with(
+ 'email',
+ 'emailThread',
+ 'EMAIL_THREAD',
+ () => 'GraphqlSoupEmailThread'
+ )
+ .with('call', 'CALL', () => 'GraphqlSoupCall')
+ .with('agent_session', 'agentSession', () => 'GraphqlSoupAgentSession')
+ .with(
+ 'crm_company',
+ 'crmCompany',
+ 'company',
+ 'CRM_COMPANY',
+ () => 'GraphqlSoupCrmCompany'
+ )
+ .with('calendar_event', 'calendarEvent', () => 'GraphqlSoupCalendarEvent')
+ .with('initiative', 'INITIATIVE', () => 'GraphqlSoupInitiative')
+ .otherwise(() => undefined);
+ return typename ? `${typename}:${entity.id}` : undefined;
+}
+
// Balanced trees stay below the GraphQL filter ingress depth limit even for
// a full preview batch. A left-folded OR tree does not.
function or<T>(items: T[]): OrExpr<T> | undefined {
diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts b/apps/web/src/lib/queries/soup/graphql/grouped-items.ts
index 8cce81f59d..ebaa420b71 100644
--- a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts
+++ b/apps/web/src/lib/queries/soup/graphql/grouped-items.ts
@@ -35,7 +35,7 @@ import {
createGraphqlSoupAstItemsQuery,
type GraphqlSoupAstItemsQuery,
} from './items';
-import { usePendingGraphqlSoupDeleteIds } from './optimistic-deletions';
+import { usePendingGraphqlSoupDeleteKeys } from './optimistic-deletions';
import { usePendingGraphqlSoupDone } from './optimistic-done';
export type GraphqlGroupedSoupAstItemsQueryArgs = {
@@ -56,7 +56,7 @@ export function createGraphqlGroupedSoupAstItemsQuery(
args: Accessor<GraphqlGroupedSoupAstItemsQueryArgs>,
options: Accessor<GraphqlGroupedSoupAstItemsQueryOptions>
): GraphqlSoupAstItemsQuery {
- const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();
+ const pendingDeleteKeys = usePendingGraphqlSoupDeleteKeys();
const pendingDone = usePendingGraphqlSoupDone();
const projectDone = createGraphqlSoupDoneProjection();
const excludesDone = createMemo(() => soupQueryExcludesDone([args().body]));
@@ -218,7 +218,7 @@ export function createGraphqlGroupedSoupAstItemsQuery(
cachedMail() ?? projected(),
pendingDone(),
excludesDone(),
- pendingDeleteIds()
+ pendingDeleteKeys()
)
),
error,
diff --git a/apps/web/src/lib/queries/soup/graphql/items.test.ts b/apps/web/src/lib/queries/soup/graphql/items.test.ts
index 67772332d5..be2ade5ed9 100644
--- a/apps/web/src/lib/queries/soup/graphql/items.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/items.test.ts
@@ -10,6 +10,10 @@ import { type DocumentNode, print } from 'graphql';
import { createComputed, createRoot, createSignal } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { makeSubject } from 'wonka';
+import {
+ type LiveQueryUpdate,
+ parseCacheRevision,
+} from '../../../graphql-cache/protocol';
const getGraphqlSoupClientMock = vi.hoisted(() => vi.fn());
const getGraphqlSoupCacheHostMock = vi.hoisted(() => vi.fn());
@@ -74,6 +78,7 @@ import {
delegateChannelNotificationRefresh,
disposeChannelNotificationRefresh,
} from '../../channel/notification-refresh';
+import { registerChannelNotificationRefresh } from '../../channel/register-notification-refresh';
import { getActiveGraphqlSoupRevalidations } from './active-queries';
import { createSoupLiveQuery } from './create-soup-live-query';
import { createGraphqlSoupAstItemsQuery } from './items';
@@ -207,6 +212,360 @@ describe('createGraphqlSoupAstItemsQuery', () => {
});
});
+ it.each([
+ { entityType: 'CHANNEL', typename: 'GraphqlSoupChannel' },
+ { entityType: 'DOCUMENT', typename: 'GraphqlSoupDocument' },
+ ] as const)(
+ 'resolves an all-cached $entityType lookup without a network request',
+ async ({ entityType, typename }) => {
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ const key = `${typename}:cached`;
+ const changes = new Set<(revision: string) => void>();
+ const evaluation = deferred<LiveQueryUpdate>();
+ entityFilterMock.mockImplementation((args) =>
+ args.liveQuery?.release
+ ? Promise.resolve({ kind: 'unsupported' })
+ : evaluation.promise
+ );
+ getGraphqlSoupCacheHostMock.mockReturnValue({
+ liveQueries: true,
+ currentRevision: async () => REVISION_0,
+ entityFilter: entityFilterMock,
+ onCacheChanged: (callback: (revision: string) => void) => {
+ changes.add(callback);
+ return () => changes.delete(callback);
+ },
+ onCacheGenerationChanged: () => () => {},
+ });
+ const ready = deferred<void>();
+ const { query, dispose } = createRoot((dispose) => {
+ const query = createGraphqlSoupAstItemsQuery(
+ () => ({ params: {}, body: {} }),
+ () => ({
+ enabled: true,
+ ...(entityType === 'CHANNEL'
+ ? { projection: 'channel-list' as const }
+ : {}),
+ cacheFirstEntities: [{ entityType, entityId: 'cached' }],
+ })
+ );
+ createComputed(() => {
+ if (query.cacheStatus?.() === 'ready') ready.resolve();
+ });
+ return { query, dispose };
+ });
+ try {
+ expect(query.cacheStatus?.()).toBe('loading');
+ expect(entityFilterMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ baseline: [],
+ liveQuery: expect.any(Object),
+ })
+ );
+ expect(fake.executions).toHaveLength(0);
+ evaluation.resolve({
+ kind: 'live-query',
+ revision: parseCacheRevision(REVISION_0),
+ reset: true,
+ keys: [key],
+ upserts: [
+ {
+ recordKey: key,
+ record: {
+ __typename: typename,
+ id: 'cached',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ },
+ },
+ ],
+ patches: [],
+ removed: [],
+ retainedKeys: [],
+ optimistic: false,
+ });
+ await ready.promise;
+ expect(query.data()?.entities.map(({ id }) => id)).toEqual(['cached']);
+ expect(query.cacheStatus?.()).toBe('ready');
+ expect(query.isFetching()).toBe(false);
+ expect(query.isEnabled()).toBe(true);
+ expect(fake.executions).toHaveLength(0);
+ expect(getActiveGraphqlSoupRevalidations(fake.client)).toHaveLength(1);
+ const refresh = query.refresh();
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(1));
+ fake.executions[0].next(
+ graphqlSoupPage({
+ items: [{ __typename: typename, id: 'cached' }],
+ next_cursor: null,
+ })
+ );
+ await refresh;
+ expect(fake.executions).toHaveLength(1);
+ entityFilterMock.mockResolvedValue({
+ kind: 'live-query',
+ revision: parseCacheRevision(REVISION_2),
+ reset: true,
+ keys: [],
+ upserts: [],
+ patches: [],
+ removed: [],
+ retainedKeys: [],
+ optimistic: false,
+ });
+ for (const changed of changes) changed(REVISION_2);
+ await vi.waitFor(() => expect(query.data()?.entities).toEqual([]));
+ } finally {
+ dispose();
+ }
+ }
+ );
+
+ it('keeps cached entities and a stable missing-ID request through pagination and retry', async () => {
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ const cached = {
+ __typename: 'GraphqlSoupChannel' as const,
+ id: 'cached',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ };
+ const callbacks = new Set<(revision: string) => void>();
+ getGraphqlSoupCacheHostMock.mockReturnValue({
+ liveQueries: true,
+ currentRevision: async () => REVISION_0,
+ entityFilter: entityFilterMock,
+ onCacheChanged: (callback: (revision: string) => void) => {
+ callbacks.add(callback);
+ return () => callbacks.delete(callback);
+ },
+ onCacheGenerationChanged: () => () => {},
+ });
+ entityFilterMock.mockImplementation(async (args) => ({
+ kind: 'live-query',
+ revision: parseCacheRevision(REVISION_1),
+ reset: true,
+ keys: [
+ 'GraphqlSoupChannel:cached',
+ ...args.baseline.map(({ key }: { key: string }) => key),
+ ],
+ upserts: [{ recordKey: 'GraphqlSoupChannel:cached', record: cached }],
+ patches: [],
+ removed: [],
+ retainedKeys: args.baseline.map(({ key }: { key: string }) => key),
+ optimistic: false,
+ }));
+ const { query, dispose } = createRoot((dispose) => ({
+ query: createSoupLiveQuery(
+ () => ({ sortMethod: 'CREATED_AT', limit: 4 }),
+ () => ({
+ cacheFirstEntities: [
+ { entityType: 'CHANNEL', entityId: 'cached' },
+ { entityType: 'DOCUMENT', entityId: 'cached' },
+ { entityType: 'CHANNEL', entityId: 'first' },
+ { entityType: 'CHANNEL', entityId: 'second' },
+ ],
+ })
+ ),
+ dispose,
+ }));
+ try {
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(1));
+ const request = fake.executions[0].variables;
+ expect(JSON.stringify(request)).not.toContain('"channelId":"cached"');
+ expect(JSON.stringify(request)).toContain('"channelId":"first"');
+ expect(JSON.stringify(request)).toContain('"channelId":"second"');
+ expect(JSON.stringify(request)).toContain('"id":"cached"');
+ const persistence = deferred<string | undefined>();
+ fake.executions[0].next(
+ graphqlSoupPage({
+ items: [{ ...cached, id: 'first' }],
+ next_cursor: 'page-2',
+ }),
+ { source: 'live-network', persistence: persistence.promise }
+ );
+ expect(query.data()?.map((row) => row.id)).toEqual(['cached', 'first']);
+ const more = query.fetchNextPage();
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(2));
+ for (const callback of callbacks) callback(REVISION_1);
+ await vi.waitFor(() => expect(query.cacheStatus()).toBe('ready'));
+ expect(fake.executions).toHaveLength(2);
+ fake.executions[1].fail(
+ new CombinedError({ networkError: new Error('page unavailable') })
+ );
+ await more;
+ expect(query.data()?.map((row) => row.id)).toEqual(['cached', 'first']);
+ expect(query.fetchError()).toBeDefined();
+
+ const retry = query.refresh();
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(3));
+ expect(fake.executions[2].variables).toEqual(request);
+ fake.executions[2].next(
+ graphqlSoupPage({
+ items: [{ ...cached, id: 'first' }],
+ next_cursor: 'page-2',
+ })
+ );
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(4));
+ fake.executions[3].next(
+ graphqlSoupPage({
+ items: [
+ { ...cached, id: 'second' },
+ { ...cached, __typename: 'GraphqlSoupDocument', id: 'cached' },
+ ],
+ next_cursor: null,
+ })
+ );
+ await retry;
+ persistence.resolve(undefined);
+ expect(
+ query
+ .data()
+ ?.map((row) => `${row.__typename}:${row.id}`)
+ .sort()
+ ).toEqual([
+ 'GraphqlSoupChannel:cached',
+ 'GraphqlSoupChannel:first',
+ 'GraphqlSoupChannel:second',
+ 'GraphqlSoupDocument:cached',
+ ]);
+ expect(query.hasNextPage()).toBe(false);
+ expect(fake.executions).toHaveLength(4);
+ const deletion = createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:cached',
+ ]);
+ const pending = deferred<void>();
+ const mutation = queryClient.getMutationCache().build(queryClient, {
+ mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
+ onMutate: () => ({ graphqlDeletion: deletion }),
+ mutationFn: () => pending.promise,
+ onSettled: () => deletion.release(),
+ });
+ const completion = mutation.execute(undefined);
+ try {
+ await vi.waitFor(() =>
+ expect(
+ query
+ .data()
+ ?.map((row) => `${row.__typename}:${row.id}`)
+ .sort()
+ ).toEqual([
+ 'GraphqlSoupChannel:cached',
+ 'GraphqlSoupChannel:first',
+ 'GraphqlSoupChannel:second',
+ ])
+ );
+ } finally {
+ pending.resolve();
+ await completion;
+ }
+ expect(query.data()).toHaveLength(4);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('restarts missing-ID hydration after a cache generation changes', async () => {
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ const cached = {
+ __typename: 'GraphqlSoupChannel' as const,
+ id: 'cached',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ };
+ let hasCachedRow = true;
+ const generations = new Set<() => void>();
+ entityFilterMock.mockImplementation(async () => ({
+ kind: 'live-query',
+ revision: parseCacheRevision(REVISION_0),
+ reset: true,
+ keys: hasCachedRow ? ['GraphqlSoupChannel:cached'] : [],
+ upserts: hasCachedRow
+ ? [{ recordKey: 'GraphqlSoupChannel:cached', record: cached }]
+ : [],
+ patches: [],
+ removed: [],
+ retainedKeys: [],
+ optimistic: false,
+ }));
+ getGraphqlSoupCacheHostMock.mockReturnValue({
+ liveQueries: true,
+ currentRevision: async () => REVISION_0,
+ entityFilter: entityFilterMock,
+ onCacheChanged: () => () => {},
+ onCacheGenerationChanged: (callback: () => void) => {
+ generations.add(callback);
+ return () => generations.delete(callback);
+ },
+ });
+ const { query, dispose } = createRoot((dispose) => ({
+ query: createSoupLiveQuery(
+ () => ({ sortMethod: 'CREATED_AT', limit: 2 }),
+ () => ({
+ projection: 'channel-list',
+ cacheFirstEntities: [
+ { entityType: 'CHANNEL', entityId: 'cached' },
+ { entityType: 'CHANNEL', entityId: 'missing' },
+ ],
+ })
+ ),
+ dispose,
+ }));
+ try {
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(1));
+ hasCachedRow = false;
+ for (const changed of generations) changed();
+ await vi.waitFor(() => expect(query.cacheStatus()).toBe('ready'));
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(2));
+ expect(JSON.stringify(fake.executions[1].variables)).toContain(
+ '"channelId":"cached"'
+ );
+ fake.executions[0].next(
+ graphqlSoupPage({
+ items: [{ ...cached, id: 'stale' }],
+ next_cursor: null,
+ })
+ );
+ expect(query.data()?.some((row) => row.id === 'stale')).not.toBe(true);
+ fake.executions[1].next(
+ graphqlSoupPage({
+ items: [cached, { ...cached, id: 'missing' }],
+ next_cursor: null,
+ })
+ );
+ expect(query.data()?.map((row) => row.id)).toEqual(['cached', 'missing']);
+ } finally {
+ dispose();
+ }
+ });
+
+ it('fetches uncached channels without repeating a successful omission', async () => {
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ const { query, dispose } = createRoot((dispose) => ({
+ query: createSoupLiveQuery(
+ () => ({ sortMethod: 'CREATED_AT', limit: 1 }),
+ () => ({
+ projection: 'channel-list',
+ cacheFirstEntities: [{ entityType: 'CHANNEL', entityId: 'missing' }],
+ })
+ ),
+ dispose,
+ }));
+ try {
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(1));
+ fake.executions[0].next(
+ graphqlSoupPage({ items: [], next_cursor: null })
+ );
+ expect(query.data()).toEqual([]);
+ expect(query.isFetching()).toBe(false);
+ expect(fake.executions).toHaveLength(1);
+ } finally {
+ dispose();
+ }
+ });
+
it.each([
{ name: 'current host', supported: true, includesInvite: true },
{ name: 'older host omits row', supported: false, includesInvite: false },
@@ -1286,6 +1645,7 @@ describe('createGraphqlSoupAstItemsQuery', () => {
f.fake.executions[0].fail(f.error);
expect(f.query.data()?.entities).toHaveLength(empty ? 0 : 1);
expect(f.query.error()).toBeUndefined();
+ expect(f.query.fetchError?.()).toBe(f.error);
} finally {
f.dispose();
}
@@ -1556,7 +1916,9 @@ describe('createGraphqlSoupAstItemsQuery', () => {
'requires visible local rows before suppressing loading/errors unless server data exists: %s',
async (hasServerData) => {
const f = fixture();
- const deletion = createGraphqlSoupDeletion(['cached-document']);
+ const deletion = createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:cached-document',
+ ]);
const pending = deferred<void>();
const mutation = queryClient.getMutationCache().build(queryClient, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
@@ -1608,7 +1970,9 @@ describe('createGraphqlSoupAstItemsQuery', () => {
it('keeps a partial projection usable when only some cached rows are pending deletion', async () => {
const f = fixture([item('deleted'), item('visible')]);
- const deletion = createGraphqlSoupDeletion(['deleted']);
+ const deletion = createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:deleted',
+ ]);
const pending = deferred<void>();
const mutation = queryClient.getMutationCache().build(queryClient, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
@@ -1748,13 +2112,23 @@ describe('createGraphqlSoupAstItemsQuery', () => {
makeGraphqlSoupInputMock.mockImplementation(({ cursor }) =>
cursor ? { continuation: { cursor } } : { initial: { limit: 50 } }
);
- const { query, dispose } = createRoot((dispose) => ({
- dispose,
- query: createGraphqlSoupAstItemsQuery(
+ const { query, dispose } = createRoot((dispose) => {
+ const query = createGraphqlSoupAstItemsQuery(
() => ({ params: {}, body: {} }),
() => ({ enabled: true, projection: 'channel-list' })
- ),
- }));
+ );
+ registerChannelNotificationRefresh(() => ({
+ client: fake.client,
+ queries: query.revalidationQueries?.() ?? [],
+ reader: {
+ enabled: query.isEnabled(),
+ fetching: query.isFetching(),
+ filtered: true,
+ notificationIds: [],
+ },
+ }));
+ return { query, dispose };
+ });
const error = new CombinedError({ networkError: new Error('offline') });
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const pageData = graphqlSoupPage({ items: [], next_cursor: null });
@@ -1929,7 +2303,10 @@ describe('createGraphqlSoupAstItemsQuery', () => {
const mutation = queryClient.getMutationCache().build(queryClient, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
onMutate: () => ({
- graphqlDeletion: createGraphqlSoupDeletion(['a', 'b']),
+ graphqlDeletion: createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:a',
+ 'GraphqlSoupDocument:b',
+ ]),
}),
onSettled: (_data, _error, _vars, context) =>
context?.graphqlDeletion.release(),
diff --git a/apps/web/src/lib/queries/soup/graphql/items.ts b/apps/web/src/lib/queries/soup/graphql/items.ts
index dac53c3e8e..8d21cbc71e 100644
--- a/apps/web/src/lib/queries/soup/graphql/items.ts
+++ b/apps/web/src/lib/queries/soup/graphql/items.ts
@@ -1,6 +1,7 @@
import type { CombinedError } from '@urql/core';
import { type Accessor, createMemo } from 'solid-js';
import { arrayEquals } from '../../../core/util/compareUtils';
+import type { QueryRevalidation } from '../../../graphql-cache/exchange/optimistic';
import type { CacheRevision } from '../../../graphql-cache/protocol';
import {
type GraphqlSoupItem,
@@ -16,12 +17,13 @@ import {
} from '../transform-utils';
import { makeGraphqlSoupInput } from './ast';
import type { GroupedSoupPaging } from './create-grouped-soup-live-query';
+import type { PredicateQueryStatus } from './create-predicate-query';
import {
createSoupLiveQuery,
type SoupLiveQueryOptions,
} from './create-soup-live-query';
import { createGraphqlSoupDoneProjection } from './done-projection';
-import { usePendingGraphqlSoupDeleteIds } from './optimistic-deletions';
+import { usePendingGraphqlSoupDeleteKeys } from './optimistic-deletions';
import { usePendingGraphqlSoupDone } from './optimistic-done';
import { soupItemKey } from './reconciliation';
@@ -39,11 +41,16 @@ export type GraphqlSoupAstItemsQuery = {
groupedPaging?: GroupedSoupPaging;
/** Cache writes keep this list current. Grouped lists leave it out. */
cacheMaintained?: Accessor<boolean>;
+ /** Readiness of the local predicate, not proof of complete server membership. */
+ cacheStatus?: Accessor<PredicateQueryStatus>;
localRevision?: Accessor<CacheRevision | undefined>;
localOptimistic?: Accessor<boolean>;
+ revalidationQueries?: Accessor<readonly QueryRevalidation[]>;
data: Accessor<SoupAstItemsData | undefined>;
/** Latest GraphQL transport or application error. */
error: Accessor<CombinedError | undefined>;
+ /** Includes background failures hidden by the cached-data display policy. */
+ fetchError?: Accessor<CombinedError | undefined>;
/** False when the filter AST has no GraphQL translation. */
isSupported: Accessor<boolean>;
isEnabled: Accessor<boolean>;
@@ -77,7 +84,7 @@ export function createGraphqlSoupAstItemsQuery(
const source = createSoupLiveQuery(input, options);
const sortMethod = createMemo(() => args().params.sort_method);
const showForeign = createMemo(() => options().showSupportedForeignEntities);
- const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();
+ const pendingDeleteKeys = usePendingGraphqlSoupDeleteKeys();
const pendingDone = usePendingGraphqlSoupDone();
const projectDone = createGraphqlSoupDoneProjection();
const excludesDone = createMemo(() => soupQueryExcludesDone([args().body]));
@@ -187,7 +194,7 @@ export function createGraphqlSoupAstItemsQuery(
data(),
pendingDone(),
excludesDone(),
- pendingDeleteIds()
+ pendingDeleteKeys()
)
),
};
diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts
index 5e3c8f4fe1..108fd3477c 100644
--- a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.test.ts
@@ -1,3 +1,4 @@
+import type { ChannelEntity } from '@entity/types/entity';
import { QueryClient } from '@tanstack/solid-query';
import { createRoot } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -19,7 +20,7 @@ import {
GRAPHQL_SOUP_DELETE_MUTATION_KEY,
GRAPHQL_SOUP_DELETE_RETENTION_MS,
prepareGraphqlSoupRestore,
- usePendingGraphqlSoupDeleteIds,
+ usePendingGraphqlSoupDeleteKeys,
withoutPendingGraphqlSoupDeletes,
withoutPendingSoupEntities,
} from './optimistic-deletions';
@@ -69,7 +70,10 @@ function data(): SoupAstItemsData {
describe('GraphQL Soup deletion lifecycle', () => {
it('does not resurrect restored ids when an earlier deletion settles late', async () => {
refresh.mockReturnValue(new Promise<void>(() => {}));
- const deletion = createGraphqlSoupDeletion(['restored', 'sibling']);
+ const deletion = createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:restored',
+ 'GraphqlSoupDocument:sibling',
+ ]);
let started!: () => void;
const ready = new Promise<void>((resolve) => {
started = resolve;
@@ -85,16 +89,20 @@ describe('GraphQL Soup deletion lifecycle', () => {
started();
await network;
},
- onSettled: () => deletion.settle(['restored', 'sibling']),
+ onSettled: () =>
+ deletion.settle([
+ 'GraphqlSoupDocument:restored',
+ 'GraphqlSoupDocument:sibling',
+ ]),
});
const request = mutation.execute(undefined);
await ready;
try {
const confirmRestore = prepareGraphqlSoupRestore();
- confirmRestore(['restored']);
+ confirmRestore(['GraphqlSoupDocument:restored']);
finish();
await request;
- expect(deletion.ids()).toEqual(['sibling']);
+ expect(deletion.keys()).toEqual(['GraphqlSoupDocument:sibling']);
} finally {
deletion.release();
}
@@ -107,22 +115,22 @@ describe('GraphQL Soup deletion lifecycle', () => {
finishRefresh = resolve;
})
);
- const deletion = createGraphqlSoupDeletion(['deleted']);
+ const deletion = createGraphqlSoupDeletion(['GraphqlSoupDocument:deleted']);
const ids = createRoot((cleanup) => {
dispose = cleanup;
- return usePendingGraphqlSoupDeleteIds();
+ return usePendingGraphqlSoupDeleteKeys();
});
const mutation = client.getMutationCache().build(client, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
onMutate: () => ({ graphqlDeletion: deletion }),
mutationFn: async () => true,
- onSettled: () => deletion.settle(['deleted']),
+ onSettled: () => deletion.settle(['GraphqlSoupDocument:deleted']),
});
try {
await mutation.execute(undefined);
expect(mutation.state.status).toBe('success');
client.getMutationCache().remove(mutation);
- expect([...ids()]).toEqual(['deleted']);
+ expect([...ids()]).toEqual(['GraphqlSoupDocument:deleted']);
finishRefresh();
await vi.waitFor(() => expect(ids().size).toBe(0));
} finally {
@@ -133,15 +141,18 @@ describe('GraphQL Soup deletion lifecycle', () => {
it('bounds retries and expires retained ids even when every refresh fails', async () => {
vi.useFakeTimers();
refresh.mockRejectedValue(new Error('offline'));
- const deletion = createGraphqlSoupDeletion(['deleted', 'failed']);
- deletion.settle(['deleted']);
+ const deletion = createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:deleted',
+ 'GraphqlSoupDocument:failed',
+ ]);
+ deletion.settle(['GraphqlSoupDocument:deleted']);
await vi.advanceTimersByTimeAsync(3000);
expect(refresh).toHaveBeenCalledTimes(3);
- expect(deletion.ids()).toEqual(['deleted']);
+ expect(deletion.keys()).toEqual(['GraphqlSoupDocument:deleted']);
await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DELETE_RETENTION_MS - 3001);
- expect(deletion.ids()).toEqual(['deleted']);
+ expect(deletion.keys()).toEqual(['GraphqlSoupDocument:deleted']);
await vi.advanceTimersByTimeAsync(1);
- expect(deletion.ids()).toEqual([]);
+ expect(deletion.keys()).toEqual([]);
await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DELETE_RETENTION_MS);
expect(refresh).toHaveBeenCalledTimes(3);
});
@@ -154,10 +165,10 @@ describe('GraphQL Soup deletion lifecycle', () => {
reject = fail;
})
);
- const deletion = createGraphqlSoupDeletion(['deleted']);
- deletion.settle(['deleted']);
+ const deletion = createGraphqlSoupDeletion(['GraphqlSoupDocument:deleted']);
+ deletion.settle(['GraphqlSoupDocument:deleted']);
await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DELETE_RETENTION_MS);
- expect(deletion.ids()).toEqual([]);
+ expect(deletion.keys()).toEqual([]);
reject(new Error('late failure'));
await vi.advanceTimersByTimeAsync(GRAPHQL_SOUP_DELETE_RETENTION_MS);
expect(refresh).toHaveBeenCalledOnce();
@@ -177,16 +188,16 @@ describe('GraphQL Soup deletion lifecycle', () => {
finishSecond = resolve;
})
);
- const first = createGraphqlSoupDeletion(['shared']);
- const second = createGraphqlSoupDeletion(['shared']);
+ const first = createGraphqlSoupDeletion(['GraphqlSoupDocument:shared']);
+ const second = createGraphqlSoupDeletion(['GraphqlSoupDocument:shared']);
try {
- first.settle(['shared']);
- second.settle(['shared']);
+ first.settle(['GraphqlSoupDocument:shared']);
+ second.settle(['GraphqlSoupDocument:shared']);
finishFirst();
- await vi.waitFor(() => expect(first.ids()).toEqual([]));
- expect(second.ids()).toEqual(['shared']);
+ await vi.waitFor(() => expect(first.keys()).toEqual([]));
+ expect(second.keys()).toEqual(['GraphqlSoupDocument:shared']);
finishSecond();
- await vi.waitFor(() => expect(second.ids()).toEqual([]));
+ await vi.waitFor(() => expect(second.keys()).toEqual([]));
} finally {
first.release();
second.release();
@@ -200,11 +211,17 @@ describe('GraphQL Soup pending delete projection', () => {
expect(withoutPendingGraphqlSoupDeletes(original, new Set())).toBe(
original
);
- expect(withoutPendingGraphqlSoupDeletes(original, new Set(['other']))).toBe(
- original
- );
expect(
- withoutPendingGraphqlSoupDeletes(undefined, new Set(['a']))
+ withoutPendingGraphqlSoupDeletes(
+ original,
+ new Set(['GraphqlSoupDocument:other'])
+ )
+ ).toBe(original);
+ expect(
+ withoutPendingGraphqlSoupDeletes(
+ undefined,
+ new Set(['GraphqlSoupDocument:a'])
+ )
).toBeUndefined();
});
@@ -212,7 +229,7 @@ describe('GraphQL Soup pending delete projection', () => {
const original = data();
const filtered = withoutPendingGraphqlSoupDeletes(
original,
- new Set(['a', 'b'])
+ new Set(['GraphqlSoupDocument:a', 'GraphqlSoupDocument:b'])
)!;
expect(filtered.entities).toEqual([original.entities[2]]);
expect(filtered.groups?.[0]).toEqual({
@@ -231,6 +248,34 @@ describe('GraphQL Soup pending delete projection', () => {
);
});
+ it('removes deleted group members even when the row was already removed from the visible list', () => {
+ const original = { ...data(), entities: [] };
+ const filtered = withoutPendingGraphqlSoupDeletes(
+ original,
+ new Set(['GraphqlSoupDocument:a'])
+ );
+ expect(filtered?.groups?.[0].itemIds).toEqual(['b']);
+ expect(filtered?.groups?.[0].totalCount).toBe(9);
+ expect(Object.keys(filtered?.itemsById ?? {})).toEqual(['b', 'c']);
+ });
+
+ it('keeps a channel visible when a document with the same ID is deleted', () => {
+ const channel: ChannelEntity = {
+ id: 'a',
+ type: 'channel',
+ name: 'Channel',
+ ownerId: 'owner',
+ channelType: 'private',
+ };
+ const original = { ...data(), entities: [data().entities[0], channel] };
+ const filtered = withoutPendingGraphqlSoupDeletes(
+ original,
+ new Set(['GraphqlSoupDocument:a'])
+ );
+ expect(filtered?.entities).toEqual([channel]);
+ expect(filtered?.entities[0]).toBe(channel);
+ });
+
it('filters flat/local-reconciled rows while preserving unrelated rows and metadata', () => {
const original = {
...data(),
@@ -240,7 +285,7 @@ describe('GraphQL Soup pending delete projection', () => {
};
const filtered = withoutPendingGraphqlSoupDeletes(
original,
- new Set(['b'])
+ new Set(['GraphqlSoupDocument:b'])
)!;
expect(filtered.entities).toEqual([
original.entities[0],
@@ -257,7 +302,7 @@ describe('GraphQL Soup pending delete projection', () => {
it('keeps overlapping deletes hidden until each operation releases its ids', async () => {
const ids = createRoot((cleanup) => {
dispose = cleanup;
- return usePendingGraphqlSoupDeleteIds();
+ return usePendingGraphqlSoupDeleteKeys();
});
let releaseFirst!: () => void;
let releaseSecond!: () => void;
@@ -266,7 +311,10 @@ describe('GraphQL Soup pending delete projection', () => {
.build(client, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
onMutate: () => ({
- graphqlDeletion: createGraphqlSoupDeletion(['a', 'b']),
+ graphqlDeletion: createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:a',
+ 'GraphqlSoupDocument:b',
+ ]),
}),
onSettled: (_data, _error, _vars, context) =>
context?.graphqlDeletion.release(),
@@ -281,7 +329,10 @@ describe('GraphQL Soup pending delete projection', () => {
.build(client, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
onMutate: () => ({
- graphqlDeletion: createGraphqlSoupDeletion(['b', 'c']),
+ graphqlDeletion: createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:b',
+ 'GraphqlSoupDocument:c',
+ ]),
}),
onSettled: (_data, _error, _vars, context) =>
context?.graphqlDeletion.release(),
@@ -291,10 +342,21 @@ describe('GraphQL Soup pending delete projection', () => {
}),
})
.execute(undefined);
- await vi.waitFor(() => expect([...ids()]).toEqual(['a', 'b', 'c']));
+ await vi.waitFor(() =>
+ expect([...ids()]).toEqual([
+ 'GraphqlSoupDocument:a',
+ 'GraphqlSoupDocument:b',
+ 'GraphqlSoupDocument:c',
+ ])
+ );
releaseFirst();
await first;
- await vi.waitFor(() => expect([...ids()]).toEqual(['b', 'c']));
+ await vi.waitFor(() =>
+ expect([...ids()]).toEqual([
+ 'GraphqlSoupDocument:b',
+ 'GraphqlSoupDocument:c',
+ ])
+ );
releaseSecond();
await second;
await vi.waitFor(() => expect(ids().size).toBe(0));
diff --git a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts
index 83b369e8ca..9fba45e3b9 100644
--- a/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts
+++ b/apps/web/src/lib/queries/soup/graphql/optimistic-deletions.ts
@@ -4,6 +4,7 @@ import { type Accessor, batch, createMemo, createSignal } from 'solid-js';
import { queryClient } from '../../client';
import type { SoupAstItemsData } from '../items';
import { refreshActiveGraphqlSoupQueries } from './active-queries';
+import { soupEntityKey } from './entity-input';
import { graphqlSoupKeys } from './keys';
export const GRAPHQL_SOUP_DELETE_MUTATION_KEY = [
@@ -18,33 +19,33 @@ const RETAINED_DELETIONS_KEY = graphqlSoupKeys.retainedDeletions.queryKey;
type RetainedDeletions = GraphqlSoupDeletion[];
export type GraphqlSoupDeletion = {
- ids: Accessor<readonly string[]>;
- /** Restore failed ids immediately and revalidate the confirmed deletions. */
- settle: (deletedIds: readonly string[]) => void;
+ keys: Accessor<readonly string[]>;
+ /** Restore failed keys immediately and revalidate the confirmed deletions. */
+ settle: (deletedKeys: readonly string[]) => void;
release: () => void;
- /** Retire only ids confirmed restored after this deletion began. */
- restore: (ids: readonly string[]) => void;
+ /** Retire only keys confirmed restored after this deletion began. */
+ restore: (keys: readonly string[]) => void;
};
-/** Per-operation state outlives the mutation and its observers until revalidation. */
+/** Retain normalized `typename:id` keys until revalidation, release, or expiry. */
export function createGraphqlSoupDeletion(
- ids: readonly string[]
+ keys: readonly string[]
): GraphqlSoupDeletion {
- const [deletedIds, setDeletedIds] = createSignal(ids);
+ const [deletedKeys, setDeletedKeys] = createSignal(keys);
let settled = false;
let released = false;
let expiryTimer: ReturnType<typeof setTimeout> | undefined;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
- const restoredIds = new Set<string>();
+ const restoredKeys = new Set<string>();
const release = () => {
if (released) return;
released = true;
clearTimeout(expiryTimer);
clearTimeout(retryTimer);
- setDeletedIds([]);
+ setDeletedKeys([]);
queryClient.setQueryData<RetainedDeletions>(
RETAINED_DELETIONS_KEY,
- (retained) => retained?.filter((entry) => entry.ids !== deletedIds)
+ (retained) => retained?.filter((entry) => entry.keys !== deletedKeys)
);
};
const revalidate = async (attempt: number): Promise<void> => {
@@ -63,31 +64,31 @@ export function createGraphqlSoupDeletion(
}
};
const deletion: GraphqlSoupDeletion = {
- ids: deletedIds,
+ keys: deletedKeys,
release,
- restore: (ids) => {
+ restore: (keys) => {
if (released) return;
- for (const id of ids) restoredIds.add(id);
- setDeletedIds((previous) =>
- previous.filter((id) => !restoredIds.has(id))
+ for (const key of keys) restoredKeys.add(key);
+ setDeletedKeys((previous) =>
+ previous.filter((key) => !restoredKeys.has(key))
);
- if (deletedIds().length === 0) release();
+ if (deletedKeys().length === 0) release();
},
- settle: (successfulIds) => {
+ settle: (successfulKeys) => {
if (settled || released) return;
settled = true;
- setDeletedIds(
- [...new Set(successfulIds)].filter((id) => !restoredIds.has(id))
+ setDeletedKeys(
+ [...new Set(successfulKeys)].filter((key) => !restoredKeys.has(key))
);
- if (deletedIds().length === 0) {
+ if (deletedKeys().length === 0) {
release();
// Reconcile uncertain failures without retaining a failed deletion.
- if (ids.length > 0)
+ if (keys.length > 0)
fireAndForget(revalidate(0), 'soup-optimistic-deletions');
return;
}
// A mutation observer can detach before the API finishes, starting its
- // GC clock early. Keep confirmed ids outside that mutation's lifetime.
+ // GC clock early. Keep confirmed keys outside that mutation's lifetime.
queryClient.setQueryData<RetainedDeletions>(
RETAINED_DELETIONS_KEY,
(retained) => [...(retained ?? []), deletion]
@@ -120,9 +121,9 @@ export function prepareGraphqlSoupRestore() {
return deletion ? [deletion] : [];
}),
]);
- return (restoredIds: readonly string[]) =>
+ return (restoredKeys: readonly string[]) =>
batch(() => {
- for (const deletion of deletions) deletion.restore(restoredIds);
+ for (const deletion of deletions) deletion.restore(restoredKeys);
});
}
@@ -134,7 +135,7 @@ export type GraphqlSoupDeleteContext = {
/** Reflect pending and confirmed deletions in GraphQL views. Completed
* mutations retain their own tombstones until strict revalidation or expiry.
*/
-export function usePendingGraphqlSoupDeleteIds() {
+export function usePendingGraphqlSoupDeleteKeys() {
const retained = useQuery(
() => ({
queryKey: RETAINED_DELETIONS_KEY,
@@ -154,16 +155,16 @@ export function usePendingGraphqlSoupDeleteIds() {
},
select: (mutation) =>
(mutation.state.context as GraphqlSoupDeleteContext | undefined)
- ?.graphqlDeletion?.ids,
+ ?.graphqlDeletion?.keys,
}),
() => queryClient
);
return createMemo<ReadonlySet<string>>(
() =>
new Set([
- ...deletions().flatMap((ids) => ids?.() ?? []),
+ ...deletions().flatMap((keys) => keys?.() ?? []),
...(retained.isSuccess
- ? retained.data.flatMap((entry) => entry.ids())
+ ? retained.data.flatMap((entry) => entry.keys())
: []),
])
);
@@ -172,25 +173,52 @@ export function usePendingGraphqlSoupDeleteIds() {
/** Preserve unaffected rows and array identity, including when no delete is pending. */
export function withoutPendingSoupEntities<T extends { id: string }>(
entities: T[],
- deletedIds: ReadonlySet<string>
+ deletedKeys: ReadonlySet<string>,
+ keyOf: (entity: T) => string | undefined = (entity) => entity.id
): T[] {
- if (
- deletedIds.size === 0 ||
- !entities.some((entity) => deletedIds.has(entity.id))
- )
- return entities;
- return entities.filter((entity) => !deletedIds.has(entity.id));
+ const deleted = (entity: T) => {
+ const key = keyOf(entity);
+ return key !== undefined && deletedKeys.has(key);
+ };
+ if (deletedKeys.size === 0 || !entities.some(deleted)) return entities;
+ return entities.filter((entity) => !deleted(entity));
}
-/** Applies only at the GraphQL display boundary, after local/server reconciliation. */
+/** Apply typed deletions after reconciliation; ID-only selectors remain available for Done. */
export function withoutPendingGraphqlSoupDeletes(
data: SoupAstItemsData | undefined,
- deletedIds: ReadonlySet<string>
+ deletedKeys: ReadonlySet<string>,
+ identity: 'entity' | 'id' = 'entity'
): SoupAstItemsData | undefined {
- if (!data || deletedIds.size === 0) return data;
- const entities = withoutPendingSoupEntities(data.entities, deletedIds);
+ const keyOf =
+ identity === 'entity'
+ ? soupEntityKey
+ : (entity: { id: string }) => entity.id;
+ if (!data || deletedKeys.size === 0) return data;
+ const entities = withoutPendingSoupEntities(
+ data.entities,
+ deletedKeys,
+ keyOf
+ );
+ const visibleIds = new Set(entities.map(({ id }) => id));
+ const removedIds = new Set(
+ data.entities.filter(({ id }) => !visibleIds.has(id)).map(({ id }) => id)
+ );
+ const itemsById = data.itemsById;
+ const removedItemIds: string[] = [];
+ for (const [id, item] of Object.entries(itemsById ?? {})) {
+ const key =
+ identity === 'entity' ? soupEntityKey({ type: item.tag, id }) : id;
+ if (key !== undefined && deletedKeys.has(key)) {
+ removedIds.add(id);
+ removedItemIds.push(id);
+ } else {
+ removedIds.delete(id);
+ }
+ }
+ if (entities === data.entities && removedIds.size === 0) return data;
const groups = data.groups?.map((group) => {
- const itemIds = group.itemIds.filter((id) => !deletedIds.has(id));
+ const itemIds = group.itemIds.filter((id) => !removedIds.has(id));
const removed = group.itemIds.length - itemIds.length;
return removed === 0
? group
@@ -200,20 +228,9 @@ export function withoutPendingGraphqlSoupDeletes(
totalCount: Math.max(0, group.totalCount - removed),
};
});
- const itemsById = data.itemsById;
- const removedItemIds = itemsById
- ? Object.keys(itemsById).filter((id) => deletedIds.has(id))
- : [];
- if (
- entities === data.entities &&
- groups?.every((group, index) => group === data.groups?.[index]) !== false &&
- removedItemIds.length === 0
- ) {
- return data;
- }
const remainingItems =
removedItemIds.length > 0 ? { ...itemsById } : itemsById;
- if (remainingItems && removedItemIds.length > 0) {
+ if (remainingItems) {
for (const id of removedItemIds) delete remainingItems[id];
}
return { ...data, entities, groups, itemsById: remainingItems };
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts
index 74a3261313..43391457ad 100644
--- a/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts
+++ b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.test.ts
@@ -62,7 +62,7 @@ import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';
import type { GroupSoupQueryVariables } from '@service-storage/graphql/generated/graphql';
import { createGraphqlGroupedSoupQueries } from './create-graphql-grouped-soup-queries';
-type TestItem = { id: string; name: string };
+type TestItem = { id: string; name: string; type: 'document' };
type TestPage = {
items: Record<string, TestItem>;
groups: Array<
@@ -137,7 +137,7 @@ function makeFakeClient(): {
};
}
-const item = (id: string): TestItem => ({ id, name: id });
+const item = (id: string): TestItem => ({ id, name: id, type: 'document' });
const group = (
key: string,
itemIds: string[],
@@ -243,7 +243,10 @@ describe('createGraphqlGroupedSoupQueries', () => {
.build(queryClient, {
mutationKey: GRAPHQL_SOUP_DELETE_MUTATION_KEY,
onMutate: () => ({
- graphqlDeletion: createGraphqlSoupDeletion(['a-1', 'a-2']),
+ graphqlDeletion: createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:a-1',
+ 'GraphqlSoupDocument:a-2',
+ ]),
}),
onSettled: (_data, _error, _vars, context) =>
context?.graphqlDeletion.release(),
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.ts b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.ts
index 820fb19083..096e8f78b3 100644
--- a/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.ts
+++ b/apps/web/src/lib/queries/soup/grouped/graphql/create-graphql-grouped-soup-queries.ts
@@ -3,8 +3,9 @@ import { keyArray } from '@solid-primitives/keyed';
import { type Accessor, createMemo } from 'solid-js';
import { createKeyedProjection } from '../../create-keyed-projection';
import type { GroupedSoupPaging } from '../../graphql/create-grouped-soup-live-query';
+import { soupEntityKey } from '../../graphql/entity-input';
import {
- usePendingGraphqlSoupDeleteIds,
+ usePendingGraphqlSoupDeleteKeys,
withoutPendingSoupEntities,
} from '../../graphql/optimistic-deletions';
import type { SoupApiItemFilter, SoupAstItemsGroupedPage } from '../../items';
@@ -33,7 +34,7 @@ type CreateGraphqlGroupedSoupQueriesArgs = {
export function createGraphqlGroupedSoupQueries(
args: CreateGraphqlGroupedSoupQueriesArgs
) {
- const pendingDeleteIds = usePendingGraphqlSoupDeleteIds();
+ const pendingDeleteKeys = usePendingGraphqlSoupDeleteKeys();
const rows = createKeyedProjection(
() => Object.entries(args.initialPage()?.items ?? {}),
([id]) => id,
@@ -63,7 +64,8 @@ export function createGraphqlGroupedSoupQueries(
const entity = byId().get(id);
return entity ? [entity] : [];
}),
- pendingDeleteIds()
+ pendingDeleteKeys(),
+ soupEntityKey
),
})
),
diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.ts
index c2e4c3d3d4..7cc8eba2f3 100644
--- a/apps/web/src/lib/queries/soup/items.ts
+++ b/apps/web/src/lib/queries/soup/items.ts
@@ -31,8 +31,11 @@ import {
useInfiniteQuery,
} from '@tanstack/solid-query';
import { type Accessor, onCleanup } from 'solid-js';
+import type { QueryRevalidation } from '../../graphql-cache/exchange/optimistic';
import { queryClient } from '../client';
import { registerActiveGraphqlSoupQuery } from './graphql/active-queries';
+import type { PredicateQueryStatus } from './graphql/create-predicate-query';
+import type { SoupEntityRef } from './graphql/entity-input';
import { createGraphqlGroupedSoupAstItemsQuery } from './graphql/grouped-items';
import { createGraphqlSoupAstItemsQuery } from './graphql/items';
import { soupPageTimestamp } from './page-timestamp';
@@ -72,6 +75,8 @@ interface SoupItemsQueryOptions {
staleTime?: StaleTime;
/** Channel navigation reads bounded unread evidence, not notification history. */
graphqlProjection?: 'channel-list';
+ /** Known entity identities for cache-first lookups. */
+ graphqlCacheFirstEntities?: readonly SoupEntityRef[];
/** Seed mixed lists from indexed non-email members; keep the full server query. */
graphqlLocalReconciliation?: 'without-email';
meta?: {
@@ -353,6 +358,7 @@ export type SoupAstItemsQuery = {
readonly groupedPaging?: import('./graphql/create-grouped-soup-live-query').GroupedSoupPaging;
readonly data: SoupAstItemsData | undefined;
readonly error: Error | null;
+ readonly fetchError?: Error | null;
/** Includes paused initial requests, whose data resource is not readable yet. */
readonly isPending: boolean;
readonly isLoading: boolean;
@@ -367,6 +373,9 @@ export type SoupAstItemsQuery = {
readonly isEnabled: boolean;
readonly hasNextPage: boolean;
readonly transport: SoupAstItemsQueryTransport;
+ readonly cacheStatus?: PredicateQueryStatus;
+ /** GraphQL reads used by transport-specific revalidation subscribers. */
+ readonly revalidationQueries?: readonly QueryRevalidation[];
fetchNextPage(): Promise<void>;
refetch(): Promise<void>;
/** Discards continuation pages while retaining the initial page. */
@@ -403,6 +412,7 @@ export function useSoupAstItemsQuery(
networkPaused: options?.().networkPaused,
keepPreviousData: options?.().keepPreviousData,
projection: options?.().graphqlProjection,
+ cacheFirstEntities: options?.().graphqlCacheFirstEntities,
localReconciliation: options?.().graphqlLocalReconciliation,
showSupportedForeignEntities: options?.().showSupportedForeignEntities,
})
@@ -486,6 +496,11 @@ export function useSoupAstItemsQuery(
? (activeGraphqlQuery().error() ?? null)
: (restQuery.error ?? null);
},
+ get fetchError() {
+ if (!usesGraphql()) return restQuery.error ?? null;
+ const query = activeGraphqlQuery();
+ return query.fetchError?.() ?? query.error() ?? null;
+ },
get isPending() {
if (!usesGraphql()) return restQuery.isPending;
const query = activeGraphqlQuery();
@@ -532,6 +547,16 @@ export function useSoupAstItemsQuery(
get transport() {
return usesGraphql() ? 'graphql' : 'rest';
},
+ get cacheStatus() {
+ return usesGraphql()
+ ? (activeGraphqlQuery().cacheStatus?.() ?? 'unsupported')
+ : 'unsupported';
+ },
+ get revalidationQueries() {
+ return usesGraphql()
+ ? (activeGraphqlQuery().revalidationQueries?.() ?? [])
+ : [];
+ },
async fetchNextPage() {
if (usesGraphql()) {
await activeGraphqlQuery().fetchNextPage();
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/grouped-operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/grouped-operations.ts
index f2260ea586..9f155cfdb4 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/grouped-operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/grouped-operations.ts
@@ -354,16 +354,28 @@ export function insertGroupQueries(
}
}
+function matchingRemovalIds(
+ entityIds: Set<string>,
+ items: Record<string, SoupApiItem>,
+ matches: ((item: SoupApiItem, id: string) => boolean) | undefined
+): Set<string> {
+ if (!matches) return entityIds;
+ return new Set(
+ [...entityIds].filter((id) => items[id] && matches(items[id], id))
+ );
+}
/** Removes items from a grouped parent page's item pool and group memberships. */
export function removeGroupedPage(
page: SoupAstItemsGroupedPage,
- entityIds: Set<string>
+ entityIds: Set<string>,
+ matches?: (item: SoupApiItem, id: string) => boolean
) {
+ const removedIds = matchingRemovalIds(entityIds, page.items, matches);
const groups: GroupMeta[] = [];
let changed = false;
for (const group of page.groups) {
- const itemIds = group.itemIds.filter((id) => !entityIds.has(id));
+ const itemIds = group.itemIds.filter((id) => !removedIds.has(id));
const removed = group.itemIds.length - itemIds.length;
if (removed === 0) {
@@ -381,7 +393,7 @@ export function removeGroupedPage(
const items: Record<string, SoupApiItem> = {};
for (const [id, item] of Object.entries(page.items)) {
- if (entityIds.has(id)) {
+ if (removedIds.has(id)) {
changed = true;
continue;
}
@@ -395,7 +407,8 @@ export function removeGroupedPage(
/** Removes items from all expanded group queries while preserving unaffected pages. */
export function removeGroupQueries(
entityIds: Set<string>,
- keyFilter?: (key: QueryKey) => boolean
+ keyFilter?: (key: QueryKey) => boolean,
+ matches?: (item: SoupApiItem, id: string) => boolean
) {
const queries = queryClient.getQueryCache().findAll({
queryKey: soupKeys.groupedGroup._def,
@@ -411,11 +424,12 @@ export function removeGroupQueries(
const pages = [];
for (const page of prev.pages) {
- const itemIds = page.group.itemIds.filter((id) => !entityIds.has(id));
+ const removedIds = matchingRemovalIds(entityIds, page.items, matches);
+ const itemIds = page.group.itemIds.filter((id) => !removedIds.has(id));
const removed = page.group.itemIds.length - itemIds.length;
let items = page.items;
- for (const id of entityIds) {
+ for (const id of removedIds) {
if (id in items) {
const { [id]: _, ...rest } = items;
items = { ...rest };
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
index 3bab4036f5..c0c1848fcc 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.test.ts
@@ -433,6 +433,24 @@ describe('removeSoupEntities', () => {
expect(getSoupItemId(cached.pages[1].items[0])).toBe('d-2');
});
+ it('keeps another entity type with the same ID when removal is scoped', () => {
+ seedSoupQuery(
+ mockSoupCache([[mockDocumentItem('shared'), mockChannelItem('shared')]])
+ );
+ const transaction = removeSoupEntities(
+ new Set(['shared']),
+ (item) => item.tag === 'document'
+ );
+ expect(getSoupQuery()!.pages[0].items.map((item) => item.tag)).toEqual([
+ 'channel',
+ ]);
+ transaction.rollback();
+ expect(getSoupQuery()!.pages[0].items.map((item) => item.tag)).toEqual([
+ 'document',
+ 'channel',
+ ]);
+ });
+
it('rollback restores removed items', () => {
seedSoupQuery(
mockSoupCache([[mockDocumentItem('d-1'), mockChatItem('c-1')]])
@@ -584,6 +602,28 @@ describe('removeSearchEntities', () => {
expect(cached.pages[1].results).toHaveLength(0);
});
+ it('keeps search results of other types with the same ID', () => {
+ seedSearchQuery(
+ mockSearchCache([
+ [
+ mockSearchResult('document', 'shared'),
+ mockSearchResult('chat', 'shared'),
+ ],
+ ])
+ );
+ const transaction = removeSearchEntities(
+ new Set(['shared']),
+ (item) => item.type === 'document'
+ );
+ expect(getSearchQuery()!.pages[0].results.map((item) => item.type)).toEqual(
+ ['chat']
+ );
+ transaction.rollback();
+ expect(getSearchQuery()!.pages[0].results.map((item) => item.type)).toEqual(
+ ['document', 'chat']
+ );
+ });
+
it('rollback restores removed search results', () => {
seedSearchQuery(
mockSearchCache([
@@ -937,6 +977,23 @@ describe('removeSoupEntities — grouped cache', () => {
expect(done.totalCount).toBe(3);
});
+ it('keeps grouped membership when the matching ID has another type', () => {
+ const key = seedGroupedAstQuery(
+ mockGroupedParentCache(
+ [mockTaskItem('shared', 'in_progress')],
+ [buildGroup('in_progress', ['shared'], 1, 0)]
+ )
+ );
+ removeSoupEntities(new Set(['shared']), (item) => item.tag === 'chat');
+ const cached =
+ testQueryClient.getQueryData<
+ InfiniteData<SoupAstItemsGroupedPage, unknown>
+ >(key)!;
+ expect(cached.pages[0].groups[0].itemIds).toEqual(['shared']);
+ expect(cached.pages[0].groups[0].totalCount).toBe(1);
+ expect(cached.pages[0].items.shared).toBeDefined();
+ });
+
it('rollback restores grouped cache', () => {
const items = [mockTaskItem('a-1', 'in_progress')];
const groups = [buildGroup('in_progress', ['a-1'], 1, 0)];
diff --git a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
index b2b4ba703e..3af3c80a18 100644
--- a/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
+++ b/apps/web/src/lib/queries/soup/normalized-cache/operations.ts
@@ -392,10 +392,17 @@ export function insertSoupEntity(item: SoupApiItem): SoupTransaction {
return { rollback: () => restoreSnapshot(previous) };
}
-export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {
+export function removeSoupEntities(
+ entityIds: Set<string>,
+ matches?: (item: SoupApiItem, id: string) => boolean
+): SoupTransaction {
cancelSoupQueries();
const previous = snapshotSoup();
+ const shouldRemove = (item: SoupApiItem) => {
+ const id = getSoupItemId(item);
+ return entityIds.has(id) && (!matches || matches(item, id));
+ };
queryClient.setQueriesData<SoupItemsInfiniteData>(
{
@@ -406,9 +413,7 @@ export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {
return {
...prev,
pages: prev.pages.map((page) => {
- const items = page.items.filter(
- (item) => !entityIds.has(getSoupItemId(item))
- );
+ const items = page.items.filter((item) => !shouldRemove(item));
if (items.length === page.items.length) return page;
return { ...page, items };
}),
@@ -430,9 +435,7 @@ export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {
const pages = prev.pages.map((page) => {
if (page.kind !== 'flat') return page;
- const items = page.items.filter(
- (item) => !entityIds.has(getSoupItemId(item))
- );
+ const items = page.items.filter((item) => !shouldRemove(item));
if (items.length === page.items.length) return page;
@@ -445,7 +448,7 @@ export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {
// Grouped AST queries only use the first parent page. Group membership is
// fully represented there by `groups[].itemIds`, so update that page once.
- const nextPage = removeGroupedPage(firstPage, entityIds);
+ const nextPage = removeGroupedPage(firstPage, entityIds, matches);
return nextPage === firstPage
? prev
@@ -453,7 +456,7 @@ export function removeSoupEntities(entityIds: Set<string>): SoupTransaction {
}
);
- removeGroupQueries(entityIds);
+ removeGroupQueries(entityIds, undefined, matches);
return { rollback: () => restoreSnapshot(previous) };
}
@@ -681,7 +684,10 @@ function removeSoupEntitiesWhere(
return { rollback: () => restoreSnapshot(previous) };
}
-export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {
+export function removeSearchEntities(
+ entityIds: Set<string>,
+ matches?: (item: UnifiedSearchResponseItem, id: string) => boolean
+): SoupTransaction {
queryClient.cancelQueries({ queryKey: soupKeys.search._def });
const previous = queryClient.getQueriesData<SoupSearchInfiniteData>({
@@ -695,9 +701,13 @@ export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {
return {
...prev,
pages: prev.pages.map((page) => {
- const results = page.results.filter(
- (result) => !entityIds.has(getSearchResultId(result))
- );
+ const results = page.results.filter((result) => {
+ const id = getSearchResultId(result);
+ return (
+ !entityIds.has(id) ||
+ (matches !== undefined && !matches(result, id))
+ );
+ });
return results.length === page.results.length
? page
: { ...page, results };
diff --git a/apps/web/src/lib/queries/storage/entity-mutations.test.ts b/apps/web/src/lib/queries/storage/entity-mutations.test.ts
index a13ede9a4e..9ad0c20da1 100644
--- a/apps/web/src/lib/queries/storage/entity-mutations.test.ts
+++ b/apps/web/src/lib/queries/storage/entity-mutations.test.ts
@@ -56,8 +56,12 @@ afterEach(() => queryClient.clear());
it('shows a confirmed restore immediately while retaining unrelated and newer deletes', async () => {
mocks.refresh.mockReturnValue(new Promise<void>(() => {}));
- const earlier = createGraphqlSoupDeletion(['restored', 'sibling']);
- earlier.settle(['restored', 'sibling']);
+ const earlier = createGraphqlSoupDeletion([
+ 'GraphqlSoupDocument:restored',
+ 'GraphqlSoupDocument:sibling',
+ 'GraphqlSoupChat:restored',
+ ]);
+ earlier.settle(earlier.keys());
let finish!: () => void;
const network = new Promise<void>((resolve) => {
finish = resolve;
@@ -85,13 +89,16 @@ it('shows a confirmed restore immediately while retaining unrelated and newer de
},
});
const restore = restoreEntity({ type: 'DOCUMENT', id: 'restored' });
- const newer = createGraphqlSoupDeletion(['restored']);
- newer.settle(['restored']);
+ const newer = createGraphqlSoupDeletion(['GraphqlSoupDocument:restored']);
+ newer.settle(['GraphqlSoupDocument:restored']);
try {
finish();
await restore;
- expect(earlier.ids()).toEqual(['sibling']);
- expect(newer.ids()).toEqual(['restored']);
+ expect(earlier.keys()).toEqual([
+ 'GraphqlSoupDocument:sibling',
+ 'GraphqlSoupChat:restored',
+ ]);
+ expect(newer.keys()).toEqual(['GraphqlSoupDocument:restored']);
} finally {
earlier.release();
newer.release();
@@ -100,8 +107,8 @@ it('shows a confirmed restore immediately while retaining unrelated and newer de
it('keeps prior deletion markers when the server refuses restoration', async () => {
mocks.refresh.mockReturnValue(new Promise<void>(() => {}));
- const deletion = createGraphqlSoupDeletion(['deleted']);
- deletion.settle(['deleted']);
+ const deletion = createGraphqlSoupDeletion(['GraphqlSoupDocument:deleted']);
+ deletion.settle(['GraphqlSoupDocument:deleted']);
mocks.mutation.mockReturnValue({
toPromise: async () => ({
data: {
@@ -121,7 +128,7 @@ it('keeps prior deletion markers when the server refuses restoration', async ()
await expect(
restoreEntity({ type: 'DOCUMENT', id: 'deleted' })
).rejects.toBeDefined();
- expect(deletion.ids()).toEqual(['deleted']);
+ expect(deletion.keys()).toEqual(['GraphqlSoupDocument:deleted']);
} finally {
deletion.release();
}
diff --git a/apps/web/src/lib/queries/storage/entity-mutations.ts b/apps/web/src/lib/queries/storage/entity-mutations.ts
index 24c5317578..f664220aa9 100644
--- a/apps/web/src/lib/queries/storage/entity-mutations.ts
+++ b/apps/web/src/lib/queries/storage/entity-mutations.ts
@@ -22,7 +22,9 @@ import {
} from '@service-storage/graphql-entity-mutations';
import { match } from 'ts-pattern';
import { refreshActiveGraphqlSoupQueries } from '../soup/graphql/active-queries';
+import { soupEntityKey } from '../soup/graphql/entity-input';
import { prepareGraphqlSoupRestore } from '../soup/graphql/optimistic-deletions';
+import { soupItemKey } from '../soup/graphql/reconciliation';
// Membership changes need a refresh even when the normalized cache is disabled.
// A failed refresh must not turn a committed write into a retryable UI failure.
@@ -46,10 +48,11 @@ export async function trashEntity(entity: EntityRefInput) {
export async function restoreEntity(entity: EntityRefInput) {
const confirmRestore = prepareGraphqlSoupRestore();
const result = await restoreGraphqlEntity(entity);
+ const restoredKey = soupEntityKey(entity);
confirmRestore([
- String(entity.id),
+ ...(restoredKey ? [restoredKey] : []),
...result.effects.flatMap((effect) =>
- effect.__typename === 'SoupUpdated' ? [effect.item.id] : []
+ effect.__typename === 'SoupUpdated' ? [soupItemKey(effect.item)] : []
),
]);
refreshSoup();
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index 7d781609c7..ffdb9e589b 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -54,6 +54,7 @@ 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 { ChannelLabelScopeSelection } from './generated/schemas/channelLabelScopeSelection';
import type { ChannelLabelsList } from './generated/schemas/channelLabelsList';
import { ChannelType } from './generated/schemas/channelType';
import {
@@ -2623,37 +2624,54 @@ export const storageServiceClient = {
},
channelLabels: {
- async preview(rule: ChannelLabelRule, signal?: AbortSignal) {
- return await dssFetch<SmartTagPreview>('/channel-labels/preview', {
- method: 'POST',
- body: JSON.stringify(rule),
- signal,
- });
+ async preview(
+ rule: ChannelLabelRule,
+ signal?: AbortSignal,
+ scope?: ChannelLabelScopeSelection
+ ) {
+ return await dssFetch<SmartTagPreview>(
+ `/channel-labels/preview${scope ? `?scope=${scope}` : ''}`,
+ { 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');
+ /** Omitted scope selects the caller's team when available, otherwise personal labels. */
+ async list(scope?: ChannelLabelScopeSelection) {
+ return await dssFetch<ChannelLabelsList>(
+ `/channel-labels${scope ? `?scope=${scope}` : ''}`
+ );
},
- async create(params: CreateChannelLabelRequest) {
- return await dssFetch<ChannelLabel>('/channel-labels', {
- method: 'POST',
- body: JSON.stringify(params),
- });
+ async create(
+ params: CreateChannelLabelRequest,
+ scope?: ChannelLabelScopeSelection
+ ) {
+ return await dssFetch<ChannelLabel>(
+ `/channel-labels${scope ? `?scope=${scope}` : ''}`,
+ { method: 'POST', body: JSON.stringify(params) }
+ );
},
- async rename(labelId: string, params: RenameChannelLabelRequest) {
+ async rename(
+ labelId: string,
+ params: RenameChannelLabelRequest,
+ scope?: ChannelLabelScopeSelection
+ ) {
return await dssFetch<ChannelLabel>(
- `/channel-labels/${encodeURIComponent(labelId)}`,
+ `/channel-labels/${encodeURIComponent(labelId)}${scope ? `?scope=${scope}` : ''}`,
{ method: 'PATCH', body: JSON.stringify(params) }
);
},
- async remove(labelId: string) {
- return await dssFetch(`/channel-labels/${encodeURIComponent(labelId)}`, {
- method: 'DELETE',
- });
+ async remove(labelId: string, scope?: ChannelLabelScopeSelection) {
+ return await dssFetch(
+ `/channel-labels/${encodeURIComponent(labelId)}${scope ? `?scope=${scope}` : ''}`,
+ { method: 'DELETE' }
+ );
},
- async setChannelLabel(channelId: string, params: SetChannelLabelRequest) {
+ async setChannelLabel(
+ channelId: string,
+ params: SetChannelLabelRequest,
+ scope?: ChannelLabelScopeSelection
+ ) {
return await dssFetch(
- `/channel-labels/channels/${encodeURIComponent(channelId)}`,
+ `/channel-labels/channels/${encodeURIComponent(channelId)}${scope ? `?scope=${scope}` : ''}`,
{ method: 'PUT', body: JSON.stringify(params) }
);
},
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelScopeSelection.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelScopeSelection.ts
new file mode 100644
index 0000000000..372b1c1905
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/channelLabelScopeSelection.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Requested label namespace. Omission retains the deployed automatic selection.
+ */
+export type ChannelLabelScopeSelection =
+ (typeof ChannelLabelScopeSelection)[keyof typeof ChannelLabelScopeSelection];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ChannelLabelScopeSelection = {
+ personal: 'personal',
+ team: 'team',
+} as const;
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.ts
index 5dc2ed1912..406d6274b2 100644
--- 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.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { ChannelLabel } from './channelLabel';
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
import type { ChannelLabelsListTeamId } from './channelLabelsListTeamId';
/**
@@ -13,6 +14,8 @@ import type { ChannelLabelsListTeamId } from './channelLabelsListTeamId';
export interface ChannelLabelsList {
/** Every label of the scope, whether or not the caller sees channels in it. */
labels: ChannelLabel[];
+ /** Resolved label namespace. */
+ scope: ChannelLabelScopeSelection;
/** Team scope, or `None` for private labels. */
teamId?: ChannelLabelsListTeamId;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelParams.ts
new file mode 100644
index 0000000000..879e0fd197
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelLabelParams.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type CreateChannelLabelParams = {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteChannelLabelParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteChannelLabelParams.ts
new file mode 100644
index 0000000000..cad6db0358
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/deleteChannelLabelParams.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type DeleteChannelLabelParams = {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+};
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.ts
index 582967d91b..a0a8d0fa66 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
@@ -357,6 +357,7 @@ export * from './channelLabelRule';
export * from './channelLabelRuleOneOf';
export * from './channelLabelRuleOneOfAttribute';
export * from './channelLabelRuleProperty';
+export * from './channelLabelScopeSelection';
export * from './channelLabelsList';
export * from './channelLabelsListTeamId';
export * from './channelLabelTeamId';
@@ -526,6 +527,7 @@ export * from './createCanvasDocumentRequest';
export * from './createCanvasDocumentRequestProjectId';
export * from './createCanvasDocumentResponse';
export * from './createCanvasHandler200';
+export * from './createChannelLabelParams';
export * from './createChannelLabelRequest';
export * from './createChannelLabelRequestRule';
export * from './createChannelRequest';
@@ -681,6 +683,7 @@ export * from './dataType';
export * from './dateOperator';
export * from './dateRange';
export * from './dateRangeOperator';
+export * from './deleteChannelLabelParams';
export * from './deleteEntityMentionResponse';
export * from './deleteProjectHandler200';
export * from './deleteProjectHandler200DataOneOf';
@@ -1321,6 +1324,7 @@ export * from './layoutProblemOneOfThree';
export * from './layoutProblemOneOfThreeKind';
export * from './leaveCallResponse';
export * from './linkShare';
+export * from './listChannelLabelsParams';
export * from './listDatabaseWebhooksResponse';
export * from './listEmailRemindersParams';
export * from './listedDatabase';
@@ -1574,6 +1578,7 @@ export * from './preSaveDocumentResponse';
export * from './preSaveDocumentResponseData';
export * from './presenceOperator';
export * from './presignedUrl';
+export * from './previewSmartTagParams';
export * from './project';
export * from './projectCreatedAt';
export * from './projectDeletedAt';
@@ -1660,6 +1665,7 @@ export * from './reactionInputNonce';
export * from './recentlyDeletedResponseData';
export * from './registerUploads';
export * from './removeParticipantsRequest';
+export * from './renameChannelLabelParams';
export * from './renameChannelLabelRequest';
export * from './renameChannelLabelRequestRule';
export * from './renamePipeline';
@@ -1758,6 +1764,7 @@ export * from './sessionSettledMetadataLastTurn';
export * from './sessionSource';
export * from './sessionStoppedMetadata';
export * from './sessionStoppedMetadataTurnInFlight';
+export * from './setChannelLabelParams';
export * from './setChannelLabelRequest';
export * from './setChannelLabelRequestLabelId';
export * from './setChannelPictureRequest';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listChannelLabelsParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listChannelLabelsParams.ts
new file mode 100644
index 0000000000..1a4dbeb3af
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listChannelLabelsParams.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type ListChannelLabelsParams = {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/previewSmartTagParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/previewSmartTagParams.ts
new file mode 100644
index 0000000000..22bcdd9d0a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/previewSmartTagParams.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type PreviewSmartTagParams = {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelParams.ts
new file mode 100644
index 0000000000..41bd179137
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/renameChannelLabelParams.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type RenameChannelLabelParams = {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+};
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelParams.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelParams.ts
new file mode 100644
index 0000000000..99a01edffe
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/setChannelLabelParams.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ChannelLabelScopeSelection } from './channelLabelScopeSelection';
+
+export type SetChannelLabelParams = {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+};
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.ts
index c6bde8be67..3854b5b45f 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
@@ -3088,6 +3088,15 @@ export const ingestTranscriptBody = zod
/**
* @summary List the caller's shared or private labels.
*/
+export const listChannelLabelsQueryParams = zod.object({
+ scope: zod
+ .enum(['personal', 'team'])
+ .optional()
+ .describe(
+ '`personal` selects private labels; `team` requires team membership.'
+ ),
+});
+
export const listChannelLabelsResponse = zod
.object({
labels: zod
@@ -3151,6 +3160,11 @@ export const listChannelLabelsResponse = zod
.describe(
'Every label of the scope, whether or not the caller sees channels in it.'
),
+ scope: zod
+ .enum(['personal', 'team'])
+ .describe(
+ 'Requested label namespace. Omission retains the deployed automatic selection.'
+ ),
teamId: zod
.uuid()
.nullish()
@@ -3161,6 +3175,15 @@ export const listChannelLabelsResponse = zod
/**
* @summary Create a label for the caller's authorized scope.
*/
+export const createChannelLabelQueryParams = zod.object({
+ scope: zod
+ .enum(['personal', 'team'])
+ .optional()
+ .describe(
+ '`personal` selects private labels; `team` requires team membership.'
+ ),
+});
+
export const createChannelLabelBody = zod
.object({
channelIds: zod
@@ -3248,6 +3271,15 @@ export const setChannelLabelParams = zod.object({
channel_id: zod.uuid().describe('The channel id.'),
});
+export const setChannelLabelQueryParams = zod.object({
+ scope: zod
+ .enum(['personal', 'team'])
+ .optional()
+ .describe(
+ '`personal` selects private labels; `team` requires team membership.'
+ ),
+});
+
export const setChannelLabelBody = zod
.object({
labelId: zod
@@ -3262,6 +3294,15 @@ export const setChannelLabelBody = zod
/**
* @summary Preview visible channels matched by a smart tag, without creating it.
*/
+export const previewSmartTagQueryParams = zod.object({
+ scope: zod
+ .enum(['personal', 'team'])
+ .optional()
+ .describe(
+ '`personal` selects private labels; `team` requires team membership.'
+ ),
+});
+
export const previewSmartTagBody = zod
.object({
attribute: zod.enum(['name']),
@@ -3303,6 +3344,15 @@ export const deleteChannelLabelParams = zod.object({
label_id: zod.uuid().describe('The label id.'),
});
+export const deleteChannelLabelQueryParams = zod.object({
+ scope: zod
+ .enum(['personal', 'team'])
+ .optional()
+ .describe(
+ '`personal` selects private labels; `team` requires team membership.'
+ ),
+});
+
/**
* @summary Rename a label of the caller's authorized scope.
*/
@@ -3310,6 +3360,15 @@ export const renameChannelLabelParams = zod.object({
label_id: zod.uuid().describe('The label id.'),
});
+export const renameChannelLabelQueryParams = zod.object({
+ scope: zod
+ .enum(['personal', 'team'])
+ .optional()
+ .describe(
+ '`personal` selects private labels; `team` requires team membership.'
+ ),
+});
+
export const renameChannelLabelBody = zod
.object({
name: zod.string().describe('New display name.'),
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index b377f726eb..46d9b03c14 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -3019,6 +3019,17 @@
"tags": ["channel_labels"],
"summary": "List the caller's shared or private labels.",
"operationId": "list_channel_labels",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
+ }
+ ],
"responses": {
"200": {
"description": "",
@@ -3066,6 +3077,17 @@
"tags": ["channel_labels"],
"summary": "Create a label for the caller's authorized scope.",
"operationId": "create_channel_label",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -3165,6 +3187,15 @@
"type": "string",
"format": "uuid"
}
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
}
],
"requestBody": {
@@ -3239,6 +3270,17 @@
"tags": ["channel_labels"],
"summary": "Preview visible channels matched by a smart tag, without creating it.",
"operationId": "preview_smart_tag",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -3318,6 +3360,15 @@
"type": "string",
"format": "uuid"
}
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
}
],
"responses": {
@@ -3380,6 +3431,15 @@
"type": "string",
"format": "uuid"
}
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
}
],
"requestBody": {
@@ -23669,10 +23729,15 @@
],
"description": "An attribute rule that automatically groups matching channels."
},
+ "ChannelLabelScopeSelection": {
+ "type": "string",
+ "description": "Requested label namespace. Omission retains the deployed automatic selection.",
+ "enum": ["personal", "team"]
+ },
"ChannelLabelsList": {
"type": "object",
"description": "The authorized scope's labels in manual order.",
- "required": ["labels"],
+ "required": ["scope", "labels"],
"properties": {
"labels": {
"type": "array",
@@ -23681,6 +23746,10 @@
},
"description": "Every label of the scope, whether or not the caller sees channels in it."
},
+ "scope": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection",
+ "description": "Resolved label namespace."
+ },
"teamId": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 43bb37506f..16feb2bf66 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -15,6 +15,7 @@ interface ImportMetaEnv {
readonly VITE_PERF_LOG?: string;
readonly VITE_ENABLE_REMINDERS?: string;
readonly VITE_ENABLE_ROUTINE_SHARING?: string;
+ readonly VITE_ENABLE_CHAT_SIDEBAR_SECTIONS?: string;
readonly VITE_ENABLE_CALENDAR_MEETING_NOTES?: string;
readonly VITE_DISABLE_BROWSER_TURSO_CACHE?: string;
readonly VITE_ENABLE_WHATSAPP_LINKED?: string;
diff --git a/crates/channel_labels/AGENTS.md b/crates/channel_labels/AGENTS.md
index 251586565d..1be0803b8e 100644
--- a/crates/channel_labels/AGENTS.md
+++ b/crates/channel_labels/AGENTS.md
@@ -35,11 +35,11 @@ Chat sidebar, following the standard hexagonal crate layout.
## Gotchas
-- Every team member sees the same labels in the same order; only per-member
+- Omitted scope selects team for members and personal otherwise; explicit personal labels accept visible team, public, and private channels, never DMs.
+- Every team member sees the same team labels in the same order; only per-member
channel *visibility inside* a label differs — don't make label ordering
per-user.
-- Labels are restricted to team channels (#6801) — don't extend them to
- non-team channels without revisiting that fix.
+- Team labels remain restricted to channels in the same team; personal labels require active channel membership.
## Related
diff --git a/crates/channel_labels/Cargo.toml b/crates/channel_labels/Cargo.toml
index e69c10b5f8..e730caf2ed 100644
--- a/crates/channel_labels/Cargo.toml
+++ b/crates/channel_labels/Cargo.toml
@@ -16,7 +16,7 @@ inbound = [
"ports",
]
outbound = ["ports"]
-ports = ["dep:tokio", "dep:tracing"]
+ports = ["dep:tokio"]
postgres = ["dep:sqlx", "outbound"]
[dependencies]
@@ -33,7 +33,7 @@ serde = { workspace = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
tokio = { workspace = true, optional = true }
-tracing = { workspace = true, optional = true }
+tracing = { workspace = true }
utoipa = { workspace = true, optional = true }
uuid = { workspace = true, features = ["serde", "v7"] }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/channel_labels/src/domain/models.rs b/crates/channel_labels/src/domain/models.rs
index 08a5f13f2a..59b5a25d8f 100644
--- a/crates/channel_labels/src/domain/models.rs
+++ b/crates/channel_labels/src/domain/models.rs
@@ -92,6 +92,8 @@ pub struct ChannelLabel {
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ChannelLabelsList {
+ /// Resolved label namespace.
+ pub scope: ChannelLabelScopeSelection,
/// 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.
@@ -137,6 +139,17 @@ pub enum SetChannelLabelOutcome {
SmartTagReadOnly,
}
+/// Requested label namespace. Omission retains the deployed automatic selection.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelLabelScopeSelection {
+ /// Labels private to the authenticated account.
+ Personal,
+ /// Labels shared by the authenticated member's team.
+ Team,
+}
+
/// Namespace in which channel labels and assignments are isolated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChannelLabelsScope {
@@ -147,15 +160,11 @@ pub enum ChannelLabelsScope {
}
impl ChannelLabelsScope {
- /// Whether a channel's owning team permits grouping it in this namespace.
- /// Non-team channels have no owning team and cannot be labelled. Shared
- /// labels accept only their own team's channels; private labels accept any
- /// team channel the viewer participates in.
- pub fn can_label_channel(&self, channel_team_id: Option<Uuid>) -> bool {
- match (self, channel_team_id) {
- (Self::Team(team_id), Some(channel_team_id)) => *team_id == channel_team_id,
- (Self::User(_), Some(_)) => true,
- (_, None) => false,
+ /// Whether a visible channel can be assigned in this namespace.
+ pub fn can_label_channel(&self, channel_type: &str, channel_team_id: Option<Uuid>) -> bool {
+ match self {
+ Self::Team(team_id) => channel_type == "team" && channel_team_id == Some(*team_id),
+ Self::User(_) => matches!(channel_type, "team" | "public" | "private"),
}
}
@@ -167,6 +176,14 @@ impl ChannelLabelsScope {
}
}
+ /// Public selection corresponding to this authorized namespace.
+ pub fn selection(&self) -> ChannelLabelScopeSelection {
+ match self {
+ Self::Team(_) => ChannelLabelScopeSelection::Team,
+ Self::User(_) => ChannelLabelScopeSelection::Personal,
+ }
+ }
+
/// Team owning this namespace, if shared.
pub fn team_id(&self) -> Option<Uuid> {
match self {
@@ -197,6 +214,7 @@ impl ChannelLabelsReceipt {
pub fn from_access(
user_id: MacroUserIdStr<'static>,
receipt: Option<EntityAccessReceipt<MemberTeamRole>>,
+ selection: Option<ChannelLabelScopeSelection>,
) -> Result<Self, ChannelLabelsError> {
let scope = match receipt {
Some(receipt) => {
@@ -210,7 +228,15 @@ impl ChannelLabelsReceipt {
}
let team_id = Uuid::parse_str(&receipt.entity().entity_id)
.map_err(|_| ChannelLabelsError::Unauthorized)?;
- ChannelLabelsScope::Team(team_id)
+ match selection {
+ Some(ChannelLabelScopeSelection::Personal) => {
+ ChannelLabelsScope::User(user_id.clone())
+ }
+ _ => ChannelLabelsScope::Team(team_id),
+ }
+ }
+ None if selection == Some(ChannelLabelScopeSelection::Team) => {
+ return Err(ChannelLabelsError::Unauthorized);
}
None => ChannelLabelsScope::User(user_id.clone()),
};
diff --git a/crates/channel_labels/src/domain/models/test.rs b/crates/channel_labels/src/domain/models/test.rs
index df5247ae2f..a21a9dc9bc 100644
--- a/crates/channel_labels/src/domain/models/test.rs
+++ b/crates/channel_labels/src/domain/models/test.rs
@@ -7,16 +7,26 @@ fn shared_labels_accept_only_channels_owned_by_their_team() {
let team_id = Uuid::now_v7();
let scope = ChannelLabelsScope::Team(team_id);
- assert!(scope.can_label_channel(Some(team_id)));
- assert!(!scope.can_label_channel(Some(Uuid::now_v7())));
- assert!(!scope.can_label_channel(None));
+ assert!(scope.can_label_channel("team", Some(team_id)));
+ assert!(!scope.can_label_channel("team", Some(Uuid::now_v7())));
+ assert!(!scope.can_label_channel("direct_message", None));
}
#[test]
-fn private_labels_accept_team_channels_and_reject_non_team_channels() {
+fn private_labels_accept_team_channels_and_reject_direct_messages() {
let user_id = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
let scope = ChannelLabelsScope::User(user_id);
- assert!(scope.can_label_channel(Some(Uuid::now_v7())));
- assert!(!scope.can_label_channel(None));
+ assert!(scope.can_label_channel("team", Some(Uuid::now_v7())));
+ assert!(!scope.can_label_channel("direct_message", None));
+}
+
+#[test]
+fn personal_scope_accepts_visible_channel_types_except_dms() {
+ let user = MacroUserIdStr::try_from("macro|[email protected]".to_owned()).unwrap();
+ let scope = ChannelLabelsScope::User(user);
+ for channel_type in ["team", "public", "private"] {
+ assert!(scope.can_label_channel(channel_type, None));
+ }
+ assert!(!scope.can_label_channel("direct_message", None));
}
diff --git a/crates/channel_labels/src/domain/ports.rs b/crates/channel_labels/src/domain/ports.rs
index c82562a866..c287d93fa6 100644
--- a/crates/channel_labels/src/domain/ports.rs
+++ b/crates/channel_labels/src/domain/ports.rs
@@ -14,7 +14,7 @@ pub trait ChannelLabelsRepo: Send + Sync + 'static {
type Err: Send + std::fmt::Debug;
/// Every label of the scope in manual order. `channel_ids` on each label
- /// is restricted to eligible team channels `viewer` participates in. Shared
+ /// is restricted to eligible channels `viewer` participates in. Shared
/// labels include only their own team's channels. Manual counts include all
/// eligible assignments; smart counts include only the viewer's active matches.
/// Smart memberships are evaluated from current attributes, including matches
diff --git a/crates/channel_labels/src/domain/service.rs b/crates/channel_labels/src/domain/service.rs
index d229d701a0..b9290e1580 100644
--- a/crates/channel_labels/src/domain/service.rs
+++ b/crates/channel_labels/src/domain/service.rs
@@ -53,7 +53,7 @@ fn channel_write_result(outcome: SetChannelLabelOutcome) -> Result<(), ChannelLa
Err(ChannelLabelsError::NotFound("label not found"))
}
SetChannelLabelOutcome::ChannelNotLabelable => Err(ChannelLabelsError::BadRequest(
- "only team channels in this label's scope can be added to a label".to_string(),
+ "channel is not eligible for this label's scope".to_string(),
)),
SetChannelLabelOutcome::SmartTagReadOnly => Err(ChannelLabelsError::BadRequest(
"smart tag membership is determined by its rule".to_string(),
@@ -112,7 +112,7 @@ where
R: ChannelLabelsRepo,
anyhow::Error: From<R::Err>,
{
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn list_labels(
&self,
receipt: &ChannelLabelsReceipt,
@@ -124,7 +124,7 @@ where
.map_err(anyhow::Error::from)?)
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn create_label(
&self,
receipt: &ChannelLabelsReceipt,
@@ -155,7 +155,7 @@ where
)
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn rename_label(
&self,
receipt: &ChannelLabelsReceipt,
@@ -193,7 +193,7 @@ where
)
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn delete_label(
&self,
receipt: &ChannelLabelsReceipt,
@@ -211,7 +211,7 @@ where
}
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn set_channel_label(
&self,
receipt: &ChannelLabelsReceipt,
@@ -222,7 +222,7 @@ where
.await
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn preview_smart_tag(
&self,
receipt: &ChannelLabelsReceipt,
diff --git a/crates/channel_labels/src/domain/service/test.rs b/crates/channel_labels/src/domain/service/test.rs
index 9a756a6a6b..3b4258f0a6 100644
--- a/crates/channel_labels/src/domain/service/test.rs
+++ b/crates/channel_labels/src/domain/service/test.rs
@@ -239,7 +239,7 @@ async fn creation_and_assignment_report_ineligible_channels() {
for result in [created.map(|_| ()), assigned] {
assert!(matches!(
result,
- Err(ChannelLabelsError::BadRequest(message)) if message.contains("only team channels")
+ Err(ChannelLabelsError::BadRequest(message)) if message.contains("not eligible")
));
}
}
@@ -428,7 +428,7 @@ async fn set_channel_label_maps_repo_outcomes() {
#[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 receipt = ChannelLabelsReceipt::from_access(actor.clone(), None, None).unwrap();
let repo = FakeRepo::default();
let service = ChannelLabelsServiceImpl::new(repo.clone());
let channel = Uuid::now_v7();
@@ -461,7 +461,7 @@ fn cannot_use_another_users_team_receipt() {
model_entity::EntityType::Team,
);
assert!(matches!(
- ChannelLabelsReceipt::from_access(actor, Some(access)),
+ ChannelLabelsReceipt::from_access(actor, Some(access), None),
Err(ChannelLabelsError::Unauthorized)
));
}
@@ -554,3 +554,37 @@ async fn rules_can_be_edited_only_on_existing_smart_tags() {
.unwrap();
assert_eq!(repo.calls().len(), 1);
}
+
+#[test]
+fn explicit_scope_requires_verified_team_membership() {
+ use crate::domain::models::ChannelLabelScopeSelection;
+ let actor = MacroUserIdStr::try_from(USER_ID.to_owned()).unwrap();
+ assert!(matches!(
+ ChannelLabelsReceipt::from_access(
+ actor.clone(),
+ None,
+ Some(ChannelLabelScopeSelection::Team)
+ ),
+ Err(ChannelLabelsError::Unauthorized)
+ ));
+ let personal = ChannelLabelsReceipt::from_access(
+ actor.clone(),
+ None,
+ Some(ChannelLabelScopeSelection::Personal),
+ )
+ .unwrap();
+ assert!(matches!(personal.scope(), ChannelLabelsScope::User(id) if id == &actor));
+ let access =
+ entity_access::domain::models::EntityAccessReceipt::dangerously_assert_authenticated_user(
+ actor.clone(),
+ &Uuid::now_v7().to_string(),
+ model_entity::EntityType::Team,
+ );
+ let personal = ChannelLabelsReceipt::from_access(
+ actor.clone(),
+ Some(access),
+ Some(ChannelLabelScopeSelection::Personal),
+ )
+ .unwrap();
+ assert!(matches!(personal.scope(), ChannelLabelsScope::User(id) if id == &actor));
+}
diff --git a/crates/channel_labels/src/inbound/axum_router.rs b/crates/channel_labels/src/inbound/axum_router.rs
index a68aa82486..d0fdbdff34 100644
--- a/crates/channel_labels/src/inbound/axum_router.rs
+++ b/crates/channel_labels/src/inbound/axum_router.rs
@@ -7,7 +7,7 @@ use std::sync::Arc;
use axum::{
Json, Router,
- extract::{FromRef, Path, State},
+ extract::{FromRef, Path, Query, State},
http::StatusCode,
response::IntoResponse,
routing::{delete, get, patch, post, put},
@@ -25,8 +25,8 @@ use uuid::Uuid;
use crate::domain::{
models::{
- ChannelLabel, ChannelLabelRule, ChannelLabelsError, ChannelLabelsList,
- ChannelLabelsReceipt, NewChannelLabel, SmartTagPreview,
+ ChannelLabel, ChannelLabelRule, ChannelLabelScopeSelection, ChannelLabelsError,
+ ChannelLabelsList, ChannelLabelsReceipt, NewChannelLabel, SmartTagPreview,
},
ports::ChannelLabelsService,
};
@@ -117,6 +117,14 @@ where
.with_state(state)
}
+/// Optional scope shared by every label endpoint.
+#[derive(Debug, Default, Deserialize, utoipa::IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct ChannelLabelScopeQuery {
+ /// `personal` selects private labels; `team` requires team membership.
+ pub scope: Option<ChannelLabelScopeSelection>,
+}
+
/// Request body for creating a label.
#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
@@ -173,6 +181,7 @@ pub struct ChannelLabelChannelPathParams {
tag = "channel_labels",
operation_id = "list_channel_labels",
path = "/channel-labels",
+ params(ChannelLabelScopeQuery),
responses(
(status = 200, body = ChannelLabelsList),
(status = 401, body = ErrorResponse),
@@ -185,6 +194,7 @@ 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>,
+ Query(scope): Query<ChannelLabelScopeQuery>,
) -> Result<Json<ChannelLabelsList>, ChannelLabelsError>
where
S: ChannelLabelsService,
@@ -194,9 +204,11 @@ where
let receipt = ChannelLabelsReceipt::from_access(
user.authorization.macro_user_id,
access.entity_access_receipt,
+ scope.scope,
)?;
let labels = state.service.list_labels(&receipt).await?;
Ok(Json(ChannelLabelsList {
+ scope: receipt.scope().selection(),
team_id: receipt.scope().team_id(),
labels,
}))
@@ -208,6 +220,7 @@ where
tag = "channel_labels",
operation_id = "create_channel_label",
path = "/channel-labels",
+ params(ChannelLabelScopeQuery),
request_body = CreateChannelLabelRequest,
responses(
(status = 200, body = ChannelLabel),
@@ -224,6 +237,7 @@ 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>,
+ Query(scope): Query<ChannelLabelScopeQuery>,
Json(req): Json<CreateChannelLabelRequest>,
) -> Result<Json<ChannelLabel>, ChannelLabelsError>
where
@@ -234,6 +248,7 @@ where
let receipt = ChannelLabelsReceipt::from_access(
user.authorization.macro_user_id,
access.entity_access_receipt,
+ scope.scope,
)?;
let label = state
.service
@@ -255,7 +270,7 @@ where
tag = "channel_labels",
operation_id = "rename_channel_label",
path = "/channel-labels/{label_id}",
- params(ChannelLabelPathParams),
+ params(ChannelLabelPathParams, ChannelLabelScopeQuery),
request_body = RenameChannelLabelRequest,
responses(
(status = 200, body = ChannelLabel),
@@ -272,6 +287,7 @@ 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>,
+ Query(scope): Query<ChannelLabelScopeQuery>,
Path(params): Path<ChannelLabelPathParams>,
Json(req): Json<RenameChannelLabelRequest>,
) -> Result<Json<ChannelLabel>, ChannelLabelsError>
@@ -283,6 +299,7 @@ where
let receipt = ChannelLabelsReceipt::from_access(
user.authorization.macro_user_id,
access.entity_access_receipt,
+ scope.scope,
)?;
let label = state
.service
@@ -297,7 +314,7 @@ where
tag = "channel_labels",
operation_id = "delete_channel_label",
path = "/channel-labels/{label_id}",
- params(ChannelLabelPathParams),
+ params(ChannelLabelPathParams, ChannelLabelScopeQuery),
responses(
(status = 204),
(status = 401, body = ErrorResponse),
@@ -311,6 +328,7 @@ 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>,
+ Query(scope): Query<ChannelLabelScopeQuery>,
Path(params): Path<ChannelLabelPathParams>,
) -> Result<StatusCode, ChannelLabelsError>
where
@@ -321,6 +339,7 @@ where
let receipt = ChannelLabelsReceipt::from_access(
user.authorization.macro_user_id,
access.entity_access_receipt,
+ scope.scope,
)?;
state
.service
@@ -335,7 +354,7 @@ where
tag = "channel_labels",
operation_id = "set_channel_label",
path = "/channel-labels/channels/{channel_id}",
- params(ChannelLabelChannelPathParams),
+ params(ChannelLabelChannelPathParams, ChannelLabelScopeQuery),
request_body = SetChannelLabelRequest,
responses(
(status = 204),
@@ -351,6 +370,7 @@ 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>,
+ Query(scope): Query<ChannelLabelScopeQuery>,
Path(params): Path<ChannelLabelChannelPathParams>,
Json(req): Json<SetChannelLabelRequest>,
) -> Result<StatusCode, ChannelLabelsError>
@@ -362,6 +382,7 @@ where
let receipt = ChannelLabelsReceipt::from_access(
user.authorization.macro_user_id,
access.entity_access_receipt,
+ scope.scope,
)?;
state
.service
@@ -376,6 +397,7 @@ where
tag = "channel_labels",
operation_id = "preview_smart_tag",
path = "/channel-labels/preview",
+ params(ChannelLabelScopeQuery),
request_body = ChannelLabelRule,
responses(
(status = 200, body = SmartTagPreview),
@@ -390,6 +412,7 @@ 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>,
+ Query(scope): Query<ChannelLabelScopeQuery>,
Json(rule): Json<ChannelLabelRule>,
) -> Result<Json<SmartTagPreview>, ChannelLabelsError>
where
@@ -400,6 +423,7 @@ where
let receipt = ChannelLabelsReceipt::from_access(
user.authorization.macro_user_id,
access.entity_access_receipt,
+ scope.scope,
)?;
Ok(Json(state.service.preview_smart_tag(&receipt, rule).await?))
}
diff --git a/crates/channel_labels/src/lib.rs b/crates/channel_labels/src/lib.rs
index 1d38fe9244..334cff7586 100644
--- a/crates/channel_labels/src/lib.rs
+++ b/crates/channel_labels/src/lib.rs
@@ -2,10 +2,13 @@
//! 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
+//! Team labels are shared among members; personal labels are private to the
+//! authenticated account. Without explicit scope, team members use team labels.
+//! Every member of a team sees team 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.
+//! visible. Personal labels accept joined team, public, and private channels,
+//! but never direct messages.
//! Smart tags match current channel attributes automatically. Their memberships
//! may overlap other tags and manual labels, and only include visible channels.
//!
diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs
index ac2b8ef50d..1840d1508b 100644
--- a/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs
+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo.rs
@@ -97,8 +97,8 @@ impl PgChannelLabelsRepo {
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 c.channel_type = 'team'
- AND (l.team_id IS NULL OR c.team_id = l.team_id)
+ WHERE ((l.team_id IS NULL AND c.channel_type IN ('team', 'public', 'private'))
+ OR (l.team_id IS NOT NULL AND c.channel_type = 'team' AND c.team_id = l.team_id))
AND ((
l.name_contains IS NULL AND EXISTS (
SELECT 1 FROM channel_label_channel lc
@@ -125,8 +125,8 @@ impl PgChannelLabelsRepo {
CASE WHEN l.name_contains IS NULL THEN
(SELECT COUNT(*) FROM channel_label_channel lc
JOIN comms_channels c ON c.id = lc.channel_id
- WHERE lc.label_id = l.id AND c.channel_type = 'team'
- AND (l.team_id IS NULL OR c.team_id = l.team_id))
+ WHERE lc.label_id = l.id AND ((l.team_id IS NULL AND c.channel_type IN ('team', 'public', 'private'))
+ OR (l.team_id IS NOT NULL AND c.channel_type = 'team' AND c.team_id = l.team_id)))
ELSE cardinality(l.visible_ids)::bigint END as "channel_count!"
FROM labels l
ORDER BY l.sort_order, l.created_at, l.id
@@ -144,7 +144,7 @@ impl PgChannelLabelsRepo {
impl ChannelLabelsRepo for PgChannelLabelsRepo {
type Err = ChannelLabelsRepoErr;
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn list_labels(
&self,
scope: &ChannelLabelsScope,
@@ -153,7 +153,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
self.load_labels(scope, None, viewer).await
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn get_label(
&self,
scope: &ChannelLabelsScope,
@@ -163,7 +163,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
Ok(self.load_labels(scope, Some(label_id), viewer).await?.pop())
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn create_label(
&self,
scope: &ChannelLabelsScope,
@@ -219,7 +219,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
}
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn rename_label(
&self,
scope: &ChannelLabelsScope,
@@ -257,7 +257,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
}
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn delete_label(
&self,
scope: &ChannelLabelsScope,
@@ -275,7 +275,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
Ok(done.rows_affected() > 0)
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn set_channel_label(
&self,
scope: &ChannelLabelsScope,
@@ -329,7 +329,7 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
Ok(SetChannelLabelOutcome::Updated)
}
- #[tracing::instrument(err, skip(self))]
+ #[tracing::instrument(skip_all, err)]
async fn preview_smart_tag(
&self,
scope: &ChannelLabelsScope,
@@ -344,8 +344,8 @@ impl ChannelLabelsRepo for PgChannelLabelsRepo {
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 = 'team'
- AND ($4::uuid IS NULL OR c.team_id = $4)
+ AND (($4::uuid IS NULL AND c.channel_type IN ('team', 'public', 'private'))
+ OR (c.channel_type = 'team' AND c.team_id = $4))
AND strpos(lower(c.name), lower($2)) > 0
ORDER BY lower(c.name), c.id
LIMIT $3"#,
@@ -378,10 +378,9 @@ async fn validate_channels(
actor: &MacroUserIdStr<'_>,
assignment_scope: Option<&ChannelLabelsScope>,
) -> Result<SetChannelLabelOutcome, ChannelLabelsRepoErr> {
- // The valid_team_channel constraint makes team_id present exactly when the
- // channel type is 'team', so it supplies the domain's eligibility fact.
+ // Lock the channel type and team along with active participation.
let channels = sqlx::query!(
- r#"SELECT c.id, c.team_id
+ r#"SELECT c.id, c.team_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
@@ -394,9 +393,11 @@ async fn validate_channels(
if channels.len() != channel_ids.len() {
return Ok(SetChannelLabelOutcome::ChannelNotFound);
}
- if assignment_scope
- .is_some_and(|scope| channels.iter().any(|c| !scope.can_label_channel(c.team_id)))
- {
+ if assignment_scope.is_some_and(|scope| {
+ channels
+ .iter()
+ .any(|c| !scope.can_label_channel(&c.channel_type, c.team_id))
+ }) {
return Ok(SetChannelLabelOutcome::ChannelNotLabelable);
}
Ok(SetChannelLabelOutcome::Updated)
diff --git a/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rs b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rs
index eae5930ae9..de49e16139 100644
--- a/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rs
+++ b/crates/channel_labels/src/outbound/pg_channel_labels_repo/test/team_channels.rs
@@ -56,19 +56,35 @@ async fn only_eligible_team_channels_can_be_assigned_or_moved_during_creation(po
.unwrap(),
);
assert_eq!(private_label.channel_count, 2);
- for invalid in [public, private, dm] {
+ for eligible in [public, private] {
assert_eq!(
repo.set_channel_label(
&private_scope,
- invalid,
+ eligible,
Some(private_label.id),
&user(USER_A)
)
.await
.unwrap(),
- SetChannelLabelOutcome::ChannelNotLabelable
+ SetChannelLabelOutcome::Updated
);
}
+ assert_eq!(
+ repo.set_channel_label(&private_scope, dm, Some(private_label.id), &user(USER_A))
+ .await
+ .unwrap(),
+ SetChannelLabelOutcome::ChannelNotLabelable
+ );
+ let listed = repo
+ .list_labels(&private_scope, &user(USER_A))
+ .await
+ .unwrap();
+ assert_eq!(listed[0].channel_count, 4);
+ assert_eq!(listed[0].channel_ids.len(), 4);
+ assert_eq!(
+ repo.list_labels(&scope, &user(USER_A)).await.unwrap()[0],
+ original
+ );
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -165,8 +181,9 @@ async fn smart_preview_and_membership_include_only_eligible_team_channels(pool:
let channel = insert_team_channel(&pool, "Support", team_id, USER_A, &[USER_A]).await;
let other_team =
insert_team_channel(&pool, "Other support", other_team_id, USER_B, &[USER_A]).await;
- insert_channel(&pool, Some("Public support"), "public", USER_A, &[USER_A]).await;
- insert_channel(&pool, Some("Private support"), "private", USER_A, &[USER_A]).await;
+ let public = insert_channel(&pool, Some("Public support"), "public", USER_A, &[USER_A]).await;
+ let private =
+ insert_channel(&pool, Some("Private support"), "private", USER_A, &[USER_A]).await;
insert_channel(&pool, None, "direct_message", USER_A, &[USER_A]).await;
let repo = PgChannelLabelsRepo::new(pool.clone());
let rule = ChannelLabelRule::Name {
@@ -177,7 +194,7 @@ async fn smart_preview_and_membership_include_only_eligible_team_channels(pool:
(scope.clone(), vec![channel]),
(
ChannelLabelsScope::User(user(USER_A).into_owned()),
- vec![other_team, channel],
+ vec![other_team, private, public, channel],
),
] {
let preview = repo
diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.toml
index 6a6abcb623..1c36443118 100644
--- a/crates/workspace-hack/Cargo.toml
+++ b/crates/workspace-hack/Cargo.toml
@@ -172,6 +172,7 @@ uuid = { version = "1", features = ["fast-rng", "serde", "v4", "v5", "v7"] }
xxhash-rust = { version = "0.8", default-features = false, features = ["xxh3", "xxh32"] }
zerocopy = { version = "0.8", default-features = false, features = ["derive", "simd"] }
zeroize = { version = "1", features = ["derive"] }
+zip = { version = "9", default-features = false, features = ["aes-crypto", "bzip2", "deflate", "deflate64", "lzma", "time", "xz", "zstd"] }
[build-dependencies]
aes = { version = "0.9", default-features = false, features = ["zeroize"] }
@@ -340,6 +341,7 @@ uuid = { version = "1", features = ["fast-rng", "serde", "v4", "v5", "v7"] }
xxhash-rust = { version = "0.8", default-features = false, features = ["xxh3", "xxh32"] }
zerocopy = { version = "0.8", default-features = false, features = ["derive", "simd"] }
zeroize = { version = "1", features = ["derive"] }
+zip = { version = "9", default-features = false, features = ["aes-crypto", "bzip2", "deflate", "deflate64", "lzma", "time", "xz", "zstd"] }
[target.x86_64-unknown-linux-gnu.dependencies]
bitflags = { version = "2", default-features = false, features = ["std"] }
diff --git a/deny.toml b/deny.toml
index 0d7f85ede0..f782db290a 100644
--- a/deny.toml
+++ b/deny.toml
@@ -91,11 +91,6 @@ ignore = [
{ id = "RUSTSEC-2026-0258", reason = "h2 0.3 (via Stripe 0.41's hyper-0.14 client) has no patched release; the hyper 1.x line is bumped to the patched 0.4.16" },
{ id = "RUSTSEC-2026-0346", reason = "Temporarily accepted for rustls 0.21 pinned by Stripe 0.41; other consumers use patched rustls 0.23.46" },
{ id = "RUSTSEC-2026-0349", reason = "Temporarily accepted for rustls 0.21 pinned by Stripe 0.41; other consumers use patched rustls 0.23.46" },
- # zip 3.0.0 remains only as a utoipa-swagger-ui 9 build-dependency; workspace crates use patched zip 9.
- # Revisit: drop these when a released utoipa-swagger-ui depends on zip >= 9 (juhaku/utoipa#1645).
- { id = "RUSTSEC-2026-0367", reason = "zip 3.0.0 is a utoipa-swagger-ui build-dependency that reads its vendored Swagger UI archive entry by entry and never calls extract(); no release uses patched zip >= 9" },
- { id = "RUSTSEC-2026-0368", reason = "zip 3.0.0 is a utoipa-swagger-ui build-dependency that reads its vendored Swagger UI archive entry by entry and never calls extract(); no release uses patched zip >= 9" },
- { id = "RUSTSEC-2026-0369", reason = "zip 3.0.0 is a utoipa-swagger-ui build-dependency that reads its vendored Swagger UI archive entry by entry and never calls extract(); no release uses patched zip >= 9" },
# 0.26.11 only re-exports webpki-roots 1.x; the bans below require patched roots.
# Remove this exception when SQLx and the remaining callers stop using the wrapper.
{ id = "RUSTSEC-2026-0381", reason = "webpki-roots 0.26.11 contains no certificates and re-exports patched 1.0.10; bans reject every other version below 1.0.10" },
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index d9ad5a8a55..8e490ee4f3 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -74,6 +74,10 @@ vanishes when the first timeline entry appears. Agent DMs keep their own UI.
## Create a channel
+Chat offers separate **New channel** and **New direct message** actions with
+either sidebar layout. **New channel** and the global Create menu use this
+three-step flow:
+
1. `Create` → `Channel G`. Dialog `Create a channel` opens on step 1 of 3 with the `Name` textbox focused.
2. Fill the name and click `Next`. Step 2 of 3 shows `Visibility`, with `Team — anyone on your team` selected by default. Team channels are always discoverable to teammates.
3. For a team channel, click `Create`. For a private channel, select `Private — only specific people` and click `Create`. Creation navigates to the channel (as a split pane: `.../channel/<uuid>`); a system row `Channel <name> created` appears.
@@ -910,178 +914,190 @@ with the same full sidebar contents. With no conversation selected, the
slide-over opens on its own and closes once a conversation is picked; the
backdrop or `Escape` still dismisses it. There is no separate skinny sidebar mode.
-On desktop, the Chat rail has `All` and `Recent` tabs in a flat, shared track
-aligned with New. Choices use equal widths, a transparent outlined track with
-1px padding, and fully rounded pill shapes. The 32px selected state matches
-New's fill and border without an extra shadow. All contains an optional
-`Favorites` section and the
-independently paginated `Team channels`, `Channels`, and `DMs` sections, in
-that order. `Team channels` lists team channels; `Channels` lists every other
-non-DM channel (public and private). Each section collapses on its own and
-keeps its own sort; open sections split the column evenly, and the bottom-most
-open one takes any remaining height. Favorites appears when
-the user has channel favorites and only lists channels. Favorites show a custom
-channel picture when set; otherwise all non-DM channels use a hashtag, including
-team channels. Favorites, regular rows, and headers share the same channel/DM
-icon renderer, including participant avatars, self-DMs, and bot personas. Channel favorites open
-in the shared channel detail. Shift-clicking a favorite, channel, or DM opens that
-conversation in a new split instead. Shift-click refreshes the notification
-selection and opens at latest. Split opens mark top-level notifications seen,
-including mentions and reactions, only after the split is opened or reused.
-Deferred navigation waits until the destination is applied; an unavailable split
-must leave unread state unchanged. Join-only channels remain
-blocked after hydration, including on mobile.
-
-With GraphQL caching enabled, a current-query cached Team channels, Channels, or DMs page
-(including an empty page) remains quiet on a response-free refresh failure.
-Hold or fail the refresh before local filtering finishes: cached rows must not
-flash **Couldn’t load conversations** while awaiting reconciliation. Changing
-filters or resetting the cache must not use older rows to hide a new-query error.
-Cache misses, HTTP/GraphQL failures, and failures to load an uncached continuation
-still show errors and retry controls; background refresh retries continue.
-
-Right-clicking a favorite opens the same menu as its channel's row in the
-sections below — `Mark Read`, `Open in new split`, `Unfavorite`,
-`Mute notifications`, `Copy Link`,
-and the label actions when channel labels are enabled — and focuses the
-favorite row rather than the channel's own row.
-`Open in new split` is available for favorites, channels, and DMs on desktop.
-It follows the shared navigation behavior: a conversation already shown inline
-is focused with a `Content already open` toast. The action is hidden on phones
-and disabled when there is no room for another split.
-
-### Threads tab
-
-The `enable-channel-threads-preview` feature flag adds a third `Threads` tab.
-It is on in development; `VITE_ENABLE_CHANNEL_THREADS_PREVIEW` overrides it
-locally. The rail shows an `All threads` row above a `Conversations` section
-with the same sort and `+` controls as the All tab's sections. Conversations
-lists only channels and DMs that hold threads the user takes part in; it pages
-through the user's threads and loads their channels, so scrolling the section
-reveals more. Selecting a row filters the main pane instead of opening the
-conversation. `All threads` clears the filter. At desktop width the rail stays
-docked on Threads with no **Hide navigation** control. In narrow splits the tab
-neither opens nor closes the slide-over, so switching between `Threads`, `All`,
-and `Recent` inside it keeps it open.
-
-The main pane is a virtualized list of channel threads the user takes part in,
-newest reply first. It loads more as it nears the end and returns to the top
-when the selected conversation changes. Messages the user sent that have no
-replies are hidden. Each card shows the root message with its replies collapsed
-the same way as a channel timeline: the first reply groups, then a
-`N more replies` control that expands the rest in place. In `All threads`, each
-card is labelled with its conversation. An icon button (`View in channel`)
-appears at a card's top right on hover or focus, and always on touch; it
-switches back to `All` and opens the channel at that thread. Shift-clicking a
-conversation row opens it in a new split. The filter lives in the view's state,
-not the URL: it survives back/forward within the split and reloads, but a
-copied link opens the Threads tab on `All threads`.
-
-### 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, Team 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.
-
-Even with the flag enabled, the heading keeps the direct `Create channel`
-action while labels are loading or unavailable. It shows the label creation
-menu only after the label list loads successfully; it never advertises disabled
-`New label` or `New smart label` actions. Changing the rollout flag to off also
-removes open label menus and dismisses label dialogs without reloading Chat.
-
-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 `Team channels` section; the `Channels`
-section's `+` only creates a channel. 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 team channels the
-viewer actively participates in are shown inside it. Shared labels accept only
-channels belonging to the label's team. Private account labels also accept only
-team channels. Public channels, private channels, and direct messages cannot be
-labelled. They keep their normal navigation, have no label menu actions, and
-cannot be dragged into labels. Existing ineligible assignments no longer group
-channels, including non-team channels and other teams' channels in shared labels.
-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. 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 `Team 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 team 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
-team channel, the Team channels heading, or empty space below the list to ungroup it.
-Dragging one ungrouped team 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 team channels you
-participate in are matched; shared labels match channels from their own team.
-Public channels, private channels, and direct messages are excluded from both
-the preview and saved results.
-
-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. Existing matches update with live name
-changes; new shared-label matches and unloaded channels 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).
-Check public and private channels with matching names: they stay in the normal
-list, have no label actions, and cannot be dragged into labels or used as a
-second channel when grouping by drop. Team channels still support these actions.
-Open the same matched channel from two labels and verify keyboard focus remains
-on the chosen row. Check rule edits and persistence after reload.
+### Sidebar redesign rollout
+
+`enable-chat-sidebar-sections` gates the desktop layout, not channel or
+direct-message creation. It defaults on in development; deployed builds defer to
+PostHog. Set `VITE_ENABLE_CHAT_SIDEBAR_SECTIONS=true` or `false` to override it locally.
+Wait for the flag to resolve before mounting a desktop layout or loading its
+lists. An unavailable or disabled remote flag restores **All**, **Recent**, and
+**Threads** (the latter still requires `enable-channel-threads-preview`), the
+original independently scrolling groups, and separate creation actions. A saved
+Recent or Threads tab survives switching the redesign on and off. Personal-section
+queries and new section preferences do not affect the flag-off layout. Existing
+labels remain governed by `enable-channel-tags`. Mobile retains its recent feed
+regardless of the redesign flag, including while it is loading.
+
+### Original sidebar (flag off)
+
+The desktop rail keeps **All** and **Recent** tabs in a shared pill track beside
+New. All contains optional Favorites and independently paginated Team channels,
+Channels, and DMs. Channels lists joined public and private channels. Each group
+collapses and sorts independently; open groups split the available height.
+
+`enable-channel-threads-preview` adds a **Threads** tab. It is on in development;
+`VITE_ENABLE_CHANNEL_THREADS_PREVIEW` overrides it locally. **All threads** clears
+the channel filter, while the Conversations section lists channels and DMs with
+threads the user participates in. Scrolling loads more. Selecting a conversation
+filters the thread view instead of opening that conversation. On desktop, Threads
+pins navigation open with no Hide navigation control. In narrow splits, changing
+between Threads, All, and Recent preserves an already-open navigation overlay.
+
+### Sectioned sidebar (flag on)
+
+With the flag on, desktop Chat has one conversation sidebar, without All, Recent,
+or Threads view tabs. Favorites appears first, followed by Direct messages, the
+team's channels, and custom sections. The team heading is **[Team name] channels**,
+with **Team channels** as the fallback while the name is unavailable.
+Other joined public and private channels remain in Channels until assigned to a
+personal section. Each custom section is a top-level heading, independent of the
+Team channels disclosure. Empty sections remain visible with a short hint; empty
+Favorites explains how to add a favorite. Private conversations use a lock icon in
+the sidebar and mobile feed, including favorited private conversations.
+All section headers use the shared collapsible-section styling without leading
+icons or top padding; the section stack supplies an 8px flex gap. Custom-section
+drop zones and highlights cover both the header and its content, including the
+empty state.
+Section, DM, and search containers use the 8px outer sidebar gutter; headings
+and rows add their own item padding so headings align with the Chat title.
+Content is indented by 8px under every section, including Favorites, custom
+sections, DMs, and empty states. Search results remain unindented. The
+caret stays hidden in expanded sections until hover and remains visible when
+collapsed. Team-shared sections show a neutral Shared
+badge next to the name, before the caret. Personal sections have no scope icon or
+badge. Header focus backgrounds fill the entire header row, including its
+trailing controls, with no extra right padding.
+
+The sidebar scrolls through all sections. Each expanded section has its own
+virtualized, scrollable list. Lists with more than two items have a resize grip;
+drag it to choose a height between two rows (68px) and the end of the list,
+capped by the available pane space. Shorter lists fit their content and have no
+resize grip. Favorites and Direct messages default to four visible rows;
+other sections default to their maximum height. Focus the grip and use Up/Down
+to resize by 20px (100px with Shift), or double-click to restore the default.
+Section heights persist as personal preferences alongside sorting and sidebar
+width. Heights adapt to filtered content and smaller panes without discarding
+the saved preference. Search covers channels and DMs regardless of section
+placement and restores the selected row in its section when closed. Mobile
+retains the recent-conversation feed below.
+
+Section membership comes from the server's complete visible channel-ID lists.
+The sidebar shows available channel rows immediately. One shared by-ID query
+per batch supplies cached channel data and fetches only missing records using
+Soup's generic explicit-entity hydration. Channel batching and unread refreshes
+stay in the channel query layer; the sidebar does not coordinate separate cache
+and network queries.
+Each expanded section appends skeleton rows while its remaining channels load.
+A failed fetch keeps available rows and replaces that section's loading feedback
+with Retry. Loading sections must not briefly show an empty-state hint.
+Collapsing a section hides its loading feedback without changing membership or
+stopping shared channel hydration.
+
+Favorites open the same channel detail as ordinary rows. Shift-clicking a
+favorite, channel, or DM opens it in a new split. Rejected navigation and failed
+hydration must not mark notifications read. Context menus retain Mark Read,
+Open in new split, Unfavorite, notification controls, and Copy Link.
+
+Favorites defaults to **Custom order**. Drag a favorite onto another favorite to
+move it to that position; an accent insertion line shows the exact destination
+above or below the target row. The order saves through the shared favorites API
+and survives reloads. Hidden favorites and favorites of other entity types keep
+their positions. **Sort → Custom order** restores dragging after choosing an
+automatic sort. Dropping a favorite does not open its conversation or move it
+into a custom section. Failed saves roll back and show an error toast.
+
+### Sections
+
+Sections reuse channel labels. The existing `enable-channel-tags` flag controls
+section management; `VITE_ENABLE_CHANNEL_TAGS=true` enables it locally.
+Turning the flag off hides section controls and stops label reads without
+deleting saved labels. Channel and direct-message creation remain independent of
+the label service and its feature flag.
+
+Use **New → New section** to create a section. The wider dialog has a name field
+and a **Smart section** switch in its body. **Shared with team** sits on the left
+of the footer, with the action buttons on the right. With both switches off, the
+section is personal and manual; smart grouping reveals its name rule and preview.
+Edit and delete through each section's sliders menu. Personal sections are
+private to the account, including for team members, and accept joined team,
+public, or private channels. Shared sections
+retain the team's existing label permissions and accept only channels from that
+team. Neither kind accepts DMs. A personal assignment never changes a shared
+assignment. Names are unique within each scope, case-insensitively.
+
+Each heading has one sliders-icon menu, also available by right-clicking the header.
+**Sort** opens its independent single-select options with a checkmark on the right.
+**Filter** contains **Unread only**. The unread label sits on the left and its
+switch on the right; toggling it keeps the submenu open.
+Custom sections include editing, Mark all as read, notification actions, and a
+destructive Delete action in the same menu. Click and right-click menus use the
+same standard context-menu rows, spacing, and selection indicators. Use the heading's caret
+to expand/collapse it; this is not repeated
+in the menu. There is no separate all-sections management menu.
+Sorting and unread filters are personal, even for a team-shared section. Date ordering
+follows each paginated source; Favorites and custom sections also offer A–Z.
+Filtered-out channels retain their membership and do not reappear ungrouped.
+Shared name and rule edits apply to the team; personal edits affect only the account.
+Deleting a section does not delete its conversations or change channel access.
+
+Every desktop section menu, including **Favorites**, **Channels**,
+**[team name] channels**, and **Direct messages**, offers **Mute all channels**,
+**Unmute all channels**, and **Snooze all channels…**. These update only your
+notifications, including for shared sections. Each action uses the section's
+complete current membership, including filtered-out and unloaded channels;
+channels added later do not inherit the change. Built-in lists resolve all pages
+before applying an action, exclude channels assigned to custom sections just as
+the sidebar does, and never include unjoined channels. Favorites targets only
+channel favorites, not documents or other favorite types. Snooze uses the usual
+duration/date picker and resumes notifications at the chosen time. A partial
+failure keeps successful updates and reports the failures; snooze retries only
+failed channels. Empty or unavailable custom sections and empty Favorites disable
+these actions. Mobile remains unchanged.
+
+Use a channel's Add to section menu to change the personal or shared assignment.
+Each section uses a checkbox: checking moves the channel into that section,
+and unchecking removes it. Only one section per scope is assigned; the personal
+and shared assignments remain independent.
+
+Choose smart grouping in the section dialog for automatic name matching.
+Smart sections match channel names literally and without regard to capitalization. They preserve ordinary section permissions and are not manual
+drop targets. Channels can appear in multiple matching smart sections.
+
+Support is organized manually through a personal section. The app does not
+classify support channels by their names or silently create a Support section.
+
+Verify personal and shared creation, same-name sections in different scopes,
+private-channel assignment, and rejecting private-channel assignment to a shared
+section. Check collapse and reload, stale requests after an account change,
+empty sections, assignment failures, and one channel in both scopes. Check the
+New menu, both dialog switches, keyboard access, edit-dialog focus, destructive
+deletion, and per-section unread and sort preferences after reload. Confirm
+unread filtering does not change section
+membership or another section's rows. Scroll a long sidebar with many sections
+and confirm that Direct messages remains immediately below Favorites. Keyboard
+navigation and section shortcuts must follow
+the same order as the rendered rows.
+Drag a channel between sections and confirm the sidebar stays visible while
+lookups refetch, including with a slow or paused connection.
+When a channel belongs to both a personal and a shared section, drag its
+personal-section row into the ungrouped list. Only the personal assignment is
+removed; the shared assignment remains. Repeat from the shared-section row to
+verify the opposite scope.
+
+### Creation actions
+
+**New** offers separate **New channel** and **New direct message** actions in
+both sidebar layouts. **New channel** opens the existing
+[name, visibility, and optional invitations flow](#create-a-channel).
+**New direct message** opens the existing recipient picker, including people,
+external email addresses, private groups, and available agent personas.
+The sectioned sidebar also offers **New section** in the same menu.
+
+Check each creation action with the sidebar flag on and off; changing the layout
+must not change the creation flow.
When calls are enabled, `Live` appears below the rail's toolbar while an active
-quick call is available. It stays visible in both tabs and during conversation
+quick call is available. It stays visible while browsing sections and during conversation
search, and disappears when no active quick calls remain. Entries are titled
`Call with <creator's name>`. Clicking a call opens
its camera/microphone setup at `/app/meet/join/<token>`; it does not join immediately.
@@ -1103,51 +1119,26 @@ While reading older history or composing in the preview, incoming notifications
messages, or revoke composer focus. To check this, leave an unsent draft in a
preview scrolled into older history and deliver a notification. Selecting another
conversation or explicitly navigating to a message must still work.
-The search action beside the tabs opens a search field below them and replaces
-the active tab contents with matching channels and direct messages from one
-activity-ordered source. Search results use compact rows on `All` and
-conversation cards on `Recent`. Switching tabs preserves the active search and
-query, then scrolls the results to the selected channel when present or to the
-start. Closing search restores the active tab and applies the same scroll
-behavior to its lists. An empty result uses the standard search empty state
-artwork and wraps long queries. Desktop channel name search combines local fuzzy
-matches and service results, deduplicated by channel ID, across channels and
-DMs. The local matches cover every conversation the viewer is in (the complete
-channel list, not only the loaded page), so a channel outside the newest hundred
-appears from the first keystroke; a loaded row keeps its unread and preview
-metadata when it matches. An empty query shows the ordinary list. Scrolling
-search results loads the next search page; clearing the query restores ordinary
-list pagination. Check a matching query, a query for a conversation absent from
-the ordinary list, a query with no matches, and a clear/reopen cycle. Mobile dock
-search uses the independent Search route described below.
-Recent search includes both channels and DMs, including service hits without
-message previews. It does not require message metadata or an importance filter.
-Loaded conversation metadata is preserved when a service hit has the same ID.
-Pending and placeholder service results never appear as current hits. Ordinary
-list errors do not affect an active search.
-Collapsing a section does not discard its loaded pages. Recent has its own
-pagination cursor. Each list is virtualized, so offscreen conversations may not
-exist in the DOM.
-Verify Recent in a visible browser with a latest-message preview containing an
-agent-session mention. Let its title resolve, scroll the preview out of view and
-back, then switch to All. The title should update without repeatedly remounting
-the mention, and scrolling and navigation must remain responsive; a headless
-browser alone can miss this regression.
-Channels and DMs each have a sort action before their create action. They can be
-sorted by last viewed, last updated, or date created, and each choice persists
-independently as a user preference.
-Compact channel and DM rows in All have the same height. Section headings place
-their caret immediately after the title and reveal it on hover or while the
-section is collapsed; hovering only undims the heading text, while
-keyboard-focusing the heading with Arrow keys or `j` / `k` gives it a background.
-Clicking a section heading toggles it without moving the keyboard highlight;
-keyboard activation still toggles the highlighted section.
-
-Arrow Down / `j` at the last loaded conversation holds focus while that
-section loads its next page. Once loading finishes, the next press advances
-into 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.
+The sidebar search action expands a field under the title. Search results replace
+the section list with compact conversation rows and preserve the selected
+channel. Closing search restores the section list and scrolls to that selection
+when available. Search merges the complete joined-channel list with authorized
+service results, deduplicates by channel ID, and retains loaded unread metadata.
+Clearing the query restores ordinary pagination.
+
+Each primary channel list and the DM panel keeps its own persisted sort:
+last viewed, last updated, or date created. Custom section channels follow that
+section's selected sort, defaulting to alphabetical order. Loading failures show
+Retry without hiding already loaded rows.
+Loading another page must preserve keyboard focus and scroll position.
+
+Arrow Down / `j` follows visible rows, including section headings. `h` / `l`
+collapse or expand the focused section. `[` / `]` jump between primary and custom
+section headings, including the DM heading. Paging at the last loaded channel
+retains focus until the next page arrives.
+From a custom-section heading in the middle of the list, use both `[` and `]`;
+each shortcut must move to the adjacent heading rather than the Team channels
+heading.
On touch layouts, Channels shows only the Recent conversation feed, with channel
and DM message previews. Rows use Home's touch row: the unread dot in the left
@@ -1231,7 +1222,7 @@ The dot and DM unread count must clear without reloading, even when the complete
unread response is empty and no mark-read mutation runs. Another unread DM must
keep its dot.
-Check cached Home → Chat navigation, All/Recent/search, and unread state after a
+Check cached Home → Chat navigation, section browsing/search, and unread state after a
read, a new notification, deletion, and reconnect, without reloading the page.
With the mark-read response delayed, channel/DM dots, section counts, and new-activity
targets should clear as soon as the local read is applied. A failed read restores
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
index ba0e1c2718..c3529a7df7 100644
--- a/docs/agent-guide/email.md
+++ b/docs/agent-guide/email.md
@@ -38,10 +38,9 @@ Unlike Calls, it lists only personal tags; team-shared tags are hidden,
and its `New tag` action creates a personal tag with no Team sharing option.
Full email client. Desktop groups `Signal` and `Noise` under one `Inbox` sidebar
-item, with pill tabs beside the Inbox title in the content header, matching the
-Chat sidebar tabs; with the Focus flags on, a `Focus` tab leads them. Selecting
-Inbox from another mailbox opens Signal; selecting it while in Focus or Noise
-keeps that tab.
+item, with pill tabs beside the Inbox title in the content header; with the Focus
+flags on, a `Focus` tab leads them. Selecting Inbox from another mailbox opens
+Signal; selecting it while in Focus or Noise keeps that tab.
The desktop sidebar continues with `Favorites`, `Drafts`, `Sent`, `Scheduled`,
and `Reminders` (when reminders are enabled), followed by a **Library** section containing `All mail`,
`Archived`, and `Shared`, then **Tags**. Sidebar number shortcuts follow that
diff --git a/docs/agent-guide/files.md b/docs/agent-guide/files.md
index 6180074ebf..d99b3bc501 100644
--- a/docs/agent-guide/files.md
+++ b/docs/agent-guide/files.md
@@ -26,7 +26,9 @@ retain successful siblings. A plan-refused chat duplicate still opens the paywal
with either transport; it must not create a copy or retry through REST. Restore immediately after trash and confirm the row
returns without waiting for retained deletion markers to expire, even if the
trash's background refresh failed. A delete started after the restore request
-must still hide its row. With the flag off, the existing REST paths remain.
+must still hide its row. Deletion and restore overlays distinguish entity type as
+well as ID, so an unrelated conversation with the same ID remains visible.
+With the flag off, the existing REST paths remain.
Deleting a non-owned item still only removes it from history. Forking a markdown
history version still uses REST because GraphQL duplication copies current content.
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 4adac6d3d1..b70254aabd 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -606,8 +606,11 @@ controls use the rounded, bordered button groups from the email thread toolbar;
New and Search have their own rounded, bordered backgrounds. Search starts as an
icon and expands into a compact field when clicked or opened with Cmd/Ctrl+F.
Closing it clears the query and returns to the icon. The action stays specific to
-the view: Home returns to its starting pane, Email composes mail, Chat offers a
-channel or direct message, and Calendar offers an event or call. Tasks offers
+the view: Home returns to its starting pane and Email composes mail. With
+`enable-chat-sidebar-sections` enabled, Chat opens one picker for existing
+conversations, new channels, and direct messages; when disabled, Chat offers
+separate channel and direct-message creation actions.
+Calendar offers an event or call. Tasks offers
**Task**, **Project** (when enabled), and **Tag** in both the Tasks and Projects
lists. Customers offers Company, Contact, and enabled Pipeline creation. Reviews
uses the general creation menu. Agents keeps New above its Chat/Code mode tabs.
diff --git a/docs/agent-guide/view-tours.md b/docs/agent-guide/view-tours.md
index f90e7548fa..843434a93a 100644
--- a/docs/agent-guide/view-tours.md
+++ b/docs/agent-guide/view-tours.md
@@ -38,8 +38,10 @@ and highlights.
agent and model picker (both use a Create → Agent entry when the composer is hidden), then the
Your agents list and the Cursor / Bring your own agent strips (beacon on
Agents), then Create for automations.
-- **Channels:** channels and DMs, creation, then threads, @mentions, and calls,
- which wait on the channel list until a conversation is open. No Slack action.
+- **Channels:** the channel and DM sidebar, then New, threads, @mentions, and
+ calls. The same tour works with the tabbed sidebar or the sectioned redesign
+ (`enable-chat-sidebar-sections`). Conversation features wait on the channel
+ list until a conversation is open. No Slack action.
- **Email:** Signal/Noise tabs beside the Inbox title (beacon on Inbox when
another mailbox is open), tags, then keyboard shortcuts.
- **Customers:** Companies and People records, relationship details, then the
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/README.md b/packages/sdk-docs/reference/generated/storage/types.gen/README.md
index 7035717a17..3a6ec38b25 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/README.md
@@ -188,6 +188,7 @@
- [ChannelJoinCodeResponse](type-aliases/ChannelJoinCodeResponse.md)
- [ChannelLabel](type-aliases/ChannelLabel.md)
- [ChannelLabelRule](type-aliases/ChannelLabelRule.md)
+- [ChannelLabelScopeSelection](type-aliases/ChannelLabelScopeSelection.md)
- [ChannelLabelsList](type-aliases/ChannelLabelsList.md)
- [ChannelMessage](type-aliases/ChannelMessage.md)
- [ChannelParticipant](type-aliases/ChannelParticipant.md)
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelScopeSelection.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelScopeSelection.md
new file mode 100644
index 0000000000..236a87cf99
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelScopeSelection.md
@@ -0,0 +1,5 @@
+# Type Alias: ChannelLabelScopeSelection
+
+> **ChannelLabelScopeSelection** = `"personal"` \| `"team"`
+
+Requested label namespace. Omission retains the deployed automatic selection.
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelsList.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelsList.md
index b202b72354..34d2fe27e3 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelsList.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ChannelLabelsList.md
@@ -1,6 +1,6 @@
# Type Alias: ChannelLabelsList
-> **ChannelLabelsList** = \{ `labels`: [`ChannelLabel`](ChannelLabel.md)[]; `teamId?`: `string` \| `null`; \}
+> **ChannelLabelsList** = \{ `labels`: [`ChannelLabel`](ChannelLabel.md)[]; `scope`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); `teamId?`: `string` \| `null`; \}
The authorized scope's labels in manual order.
@@ -9,4 +9,5 @@ The authorized scope's labels in manual order.
| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-labels"></a> `labels` | [`ChannelLabel`](ChannelLabel.md)[] | Every label of the scope, whether or not the caller sees channels in it. |
+| <a id="property-scope"></a> `scope` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | Resolved label namespace. |
| <a id="property-teamid"></a> `teamId?` | `string` \| `null` | Team scope, or `None` for private labels. |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateChannelLabelData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateChannelLabelData.md
index 645a48ac67..7f58673415 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateChannelLabelData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CreateChannelLabelData.md
@@ -1,12 +1,13 @@
# Type Alias: CreateChannelLabelData
-> **CreateChannelLabelData** = \{ `body`: [`CreateChannelLabelRequest`](CreateChannelLabelRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/channel-labels"`; \}
+> **CreateChannelLabelData** = \{ `body`: [`CreateChannelLabelRequest`](CreateChannelLabelRequest.md); `path?`: `never`; `query?`: \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \}; `url`: `"/channel-labels"`; \}
## Properties
-| Property | Type |
-| ------ | ------ |
-| <a id="property-body"></a> `body` | [`CreateChannelLabelRequest`](CreateChannelLabelRequest.md) |
-| <a id="property-path"></a> `path?` | `never` |
-| <a id="property-query"></a> `query?` | `never` |
-| <a id="property-url"></a> `url` | `"/channel-labels"` |
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body` | [`CreateChannelLabelRequest`](CreateChannelLabelRequest.md) | - |
+| <a id="property-path"></a> `path?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \} | - |
+| `query.scope?` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | `personal` selects private labels; `team` requires team membership. |
+| <a id="property-url"></a> `url` | `"/channel-labels"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/DeleteChannelLabelData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/DeleteChannelLabelData.md
index 1f8285e7cb..98a6d1b223 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/DeleteChannelLabelData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/DeleteChannelLabelData.md
@@ -1,6 +1,6 @@
# Type Alias: DeleteChannelLabelData
-> **DeleteChannelLabelData** = \{ `body?`: `never`; `path`: \{ `label_id`: `string`; \}; `query?`: `never`; `url`: `"/channel-labels/{label_id}"`; \}
+> **DeleteChannelLabelData** = \{ `body?`: `never`; `path`: \{ `label_id`: `string`; \}; `query?`: \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \}; `url`: `"/channel-labels/{label_id}"`; \}
## Properties
@@ -9,5 +9,6 @@
| <a id="property-body"></a> `body?` | `never` | - |
| <a id="property-path"></a> `path` | \{ `label_id`: `string`; \} | - |
| `path.label_id` | `string` | The label id. |
-| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \} | - |
+| `query.scope?` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | `personal` selects private labels; `team` requires team membership. |
| <a id="property-url"></a> `url` | `"/channel-labels/{label_id}"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ListChannelLabelsData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ListChannelLabelsData.md
index d79086de7a..fbdabc7b26 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ListChannelLabelsData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/ListChannelLabelsData.md
@@ -1,12 +1,13 @@
# Type Alias: ListChannelLabelsData
-> **ListChannelLabelsData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/channel-labels"`; \}
+> **ListChannelLabelsData** = \{ `body?`: `never`; `path?`: `never`; `query?`: \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \}; `url`: `"/channel-labels"`; \}
## Properties
-| Property | Type |
-| ------ | ------ |
-| <a id="property-body"></a> `body?` | `never` |
-| <a id="property-path"></a> `path?` | `never` |
-| <a id="property-query"></a> `query?` | `never` |
-| <a id="property-url"></a> `url` | `"/channel-labels"` |
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \} | - |
+| `query.scope?` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | `personal` selects private labels; `team` requires team membership. |
+| <a id="property-url"></a> `url` | `"/channel-labels"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/PreviewSmartTagData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/PreviewSmartTagData.md
index a9d9768c8b..22396df4e1 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/PreviewSmartTagData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/PreviewSmartTagData.md
@@ -1,12 +1,13 @@
# Type Alias: PreviewSmartTagData
-> **PreviewSmartTagData** = \{ `body`: [`ChannelLabelRule`](ChannelLabelRule.md); `path?`: `never`; `query?`: `never`; `url`: `"/channel-labels/preview"`; \}
+> **PreviewSmartTagData** = \{ `body`: [`ChannelLabelRule`](ChannelLabelRule.md); `path?`: `never`; `query?`: \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \}; `url`: `"/channel-labels/preview"`; \}
## Properties
-| Property | Type |
-| ------ | ------ |
-| <a id="property-body"></a> `body` | [`ChannelLabelRule`](ChannelLabelRule.md) |
-| <a id="property-path"></a> `path?` | `never` |
-| <a id="property-query"></a> `query?` | `never` |
-| <a id="property-url"></a> `url` | `"/channel-labels/preview"` |
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body` | [`ChannelLabelRule`](ChannelLabelRule.md) | - |
+| <a id="property-path"></a> `path?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \} | - |
+| `query.scope?` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | `personal` selects private labels; `team` requires team membership. |
+| <a id="property-url"></a> `url` | `"/channel-labels/preview"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/RenameChannelLabelData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/RenameChannelLabelData.md
index a7b60e0ed0..8c8f8917f8 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/RenameChannelLabelData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/RenameChannelLabelData.md
@@ -1,6 +1,6 @@
# Type Alias: RenameChannelLabelData
-> **RenameChannelLabelData** = \{ `body`: [`RenameChannelLabelRequest`](RenameChannelLabelRequest.md); `path`: \{ `label_id`: `string`; \}; `query?`: `never`; `url`: `"/channel-labels/{label_id}"`; \}
+> **RenameChannelLabelData** = \{ `body`: [`RenameChannelLabelRequest`](RenameChannelLabelRequest.md); `path`: \{ `label_id`: `string`; \}; `query?`: \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \}; `url`: `"/channel-labels/{label_id}"`; \}
## Properties
@@ -9,5 +9,6 @@
| <a id="property-body"></a> `body` | [`RenameChannelLabelRequest`](RenameChannelLabelRequest.md) | - |
| <a id="property-path"></a> `path` | \{ `label_id`: `string`; \} | - |
| `path.label_id` | `string` | The label id. |
-| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \} | - |
+| `query.scope?` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | `personal` selects private labels; `team` requires team membership. |
| <a id="property-url"></a> `url` | `"/channel-labels/{label_id}"` | - |
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/SetChannelLabelData.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/SetChannelLabelData.md
index 36a1b20e73..0031fe826b 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/SetChannelLabelData.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/SetChannelLabelData.md
@@ -1,6 +1,6 @@
# Type Alias: SetChannelLabelData
-> **SetChannelLabelData** = \{ `body`: [`SetChannelLabelRequest`](SetChannelLabelRequest.md); `path`: \{ `channel_id`: `string`; \}; `query?`: `never`; `url`: `"/channel-labels/channels/{channel_id}"`; \}
+> **SetChannelLabelData** = \{ `body`: [`SetChannelLabelRequest`](SetChannelLabelRequest.md); `path`: \{ `channel_id`: `string`; \}; `query?`: \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \}; `url`: `"/channel-labels/channels/{channel_id}"`; \}
## Properties
@@ -9,5 +9,6 @@
| <a id="property-body"></a> `body` | [`SetChannelLabelRequest`](SetChannelLabelRequest.md) | - |
| <a id="property-path"></a> `path` | \{ `channel_id`: `string`; \} | - |
| `path.channel_id` | `string` | The channel id. |
-| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-query"></a> `query?` | \{ `scope?`: [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md); \} | - |
+| `query.scope?` | [`ChannelLabelScopeSelection`](ChannelLabelScopeSelection.md) | `personal` selects private labels; `team` requires team membership. |
| <a id="property-url"></a> `url` | `"/channel-labels/channels/{channel_id}"` | - |
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index beeedceaaf..37f21f0554 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-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, 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, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, 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, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DateRange, DateRangeOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, 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, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, 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, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, 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, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, ExternalChatAdd, ExternalChatAddData, ExternalChatAdded, ExternalChatAddResponse, ExternalChatAddResponses, ExternalChatAttachment, ExternalChatAttachmentState, ExternalChatBackfill, ExternalChatBackfillState, ExternalChatCall, ExternalChatCallOutcome, ExternalChatCapabilities, ExternalChatCommunity, ExternalChatContactCard, ExternalChatContacts, ExternalChatData, ExternalChatDeliveryData, ExternalChatDeliveryResponse, ExternalChatDeliveryResponses, ExternalChatDeliveryState, ExternalChatDetail, ExternalChatEvent, ExternalChatKind, ExternalChatLocation, ExternalChatMediaKind, ExternalChatMediaPresentation, ExternalChatMembers, ExternalChatMention, ExternalChatMessage, ExternalChatMessageAttachments, ExternalChatMessageAttachmentsData, ExternalChatMessageAttachmentsResponse, ExternalChatMessageAttachmentsResponses, ExternalChatMessageData, ExternalChatMessageKind, ExternalChatMessageResponse, ExternalChatMessageResponses, ExternalChatMessages, ExternalChatMessagesData, ExternalChatMessagesResponse, ExternalChatMessagesResponses, ExternalChatMutation, ExternalChatParticipant, ExternalChatPermissionsData, ExternalChatPermissionsResponse, ExternalChatPermissionsResponses, ExternalChatPersonRef, ExternalChatPoll, ExternalChatPollOption, ExternalChatProvider, ExternalChatReaction, ExternalChatReadData, ExternalChatReadResponse, ExternalChatReadResponses, ExternalChatReference, ExternalChatRemoveData, ExternalChatRemoveResponse, ExternalChatRemoveResponses, ExternalChatReplyBlock, ExternalChatReplyContent, ExternalChatResponse, ExternalChatResponses, ExternalChatRichContent, ExternalChatsData, ExternalChatSendData, ExternalChatSender, ExternalChatSendErrors, ExternalChatSendProgress, ExternalChatSendReply, ExternalChatSendResponse, ExternalChatSendResponses, ExternalChatSendsData, ExternalChatSendsResponse, ExternalChatSendsResponses, ExternalChatsResponse, ExternalChatsResponses, ExternalChatSummary, ExternalChatSystemAction, ExternalChatSystemLine, ExternalChatUpdatePermissionsData, ExternalChatUpdatePermissionsResponse, ExternalChatUpdatePermissionsResponses, ExternalChatUploadData, ExternalChatUploadedAttachment, ExternalChatUploadRequest, ExternalChatUploadResponse, ExternalChatUploadResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, 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, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, 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, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, 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, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, 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, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, 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, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyBucketing, PropertyDateFilterRange, PropertyDateRange, PropertyDateRanges, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, 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, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, 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, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharedExternalChatReference, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TaskSimilarityResult, TaskSimilaritySearchHandlerData, TaskSimilaritySearchHandlerError, TaskSimilaritySearchHandlerErrors, TaskSimilaritySearchHandlerResponse, TaskSimilaritySearchHandlerResponses, TaskSimilaritySearchRequest, TaskSimilaritySearchResponse, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, 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, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppAccount, WhatsappAccountData, WhatsappAccountResponse, WhatsappAccountResponses, WhatsAppAccountState, WhatsAppAccountView, WhatsappCancelPairingData, WhatsappCancelPairingResponse, WhatsappCancelPairingResponses, WhatsAppCannotAdd, WhatsAppChat, WhatsAppChats, WhatsappChatsData, WhatsappChatsResponse, WhatsappChatsResponses, WhatsAppConnect, WhatsappConnectData, WhatsappConnectResponse, WhatsappConnectResponses, WhatsAppDisconnect, WhatsappDisconnectData, WhatsAppDisconnectRequest, WhatsappDisconnectResponse, WhatsappDisconnectResponses, WhatsAppHistoryImport, WhatsappImportHistoryData, WhatsappImportHistoryResponse, WhatsappImportHistoryResponses, WhatsAppLookup, WhatsappLookupData, WhatsAppLookupRequest, WhatsappLookupResponse, WhatsappLookupResponses, WhatsAppLookupState, WhatsAppPairing, WhatsappPairingData, WhatsappPairingResponse, WhatsappPairingResponses, WhatsAppPairingState, WhatsAppPairState, WhatsappPasskeyData, WhatsappPasskeyResponse, WhatsappPasskeyResponses, WhatsappStartLookupData, WhatsappStartLookupResponse, WhatsappStartLookupResponses, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessiblePipeline, AccessLevel, AccessRequest, AccessRequestsCancelData, AccessRequestsCancelErrors, AccessRequestsCancelResponses, AccessRequestsDirectData, AccessRequestsDirectErrors, AccessRequestsDirectResponse, AccessRequestsDirectResponses, AccessRequestsRemoveDirectData, AccessRequestsRemoveDirectErrors, AccessRequestsRemoveDirectResponses, AccessRequestsResolveData, AccessRequestsResolveErrors, AccessRequestsResolveResponse, AccessRequestsResolveResponses, AccessRequestsSetDirectData, AccessRequestsSetDirectErrors, AccessRequestsSetDirectResponses, AccessRequestsStateData, AccessRequestsStateErrors, AccessRequestsStateResponse, AccessRequestsStateResponses, AccessRequestsSubmitData, AccessRequestsSubmitErrors, AccessRequestsSubmitResponse, AccessRequestsSubmitResponses, AccessRequestState, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentDmProfile, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, AgentSessionSource, AgentSessionVisibility, AgentTyping, AgentTypingPhase, Anchor, AnchorId, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentCommentReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarJoinRequest, CalendarJoinRequestApiError, CalendarJoinRequestErrorCode, CalendarJoinRequestsResponse, CalendarJoinRequestStatus, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarMentionViewerCopy, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallProvider, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordSource, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelScopeSelection, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, 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, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnId, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateCanvasDocumentRequest, CreateCanvasDocumentResponse, CreateCanvasHandlerData, CreateCanvasHandlerError, CreateCanvasHandlerErrors, CreateCanvasHandlerResponse, CreateCanvasHandlerResponses, 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, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseId, DatabaseOp, DatabaseQueryRequest, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DateRange, DateRangeOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, 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, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, DirectAccess, 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, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTextContent, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, 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, EntityRef, EntityReference, EntityType, ErrorResponse, EventIcsData, EventIcsErrors, EventIcsResponse, EventIcsResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, ExternalChatAdd, ExternalChatAddData, ExternalChatAdded, ExternalChatAddResponse, ExternalChatAddResponses, ExternalChatAttachment, ExternalChatAttachmentState, ExternalChatBackfill, ExternalChatBackfillState, ExternalChatCall, ExternalChatCallOutcome, ExternalChatCapabilities, ExternalChatCommunity, ExternalChatContactCard, ExternalChatContacts, ExternalChatData, ExternalChatDeliveryData, ExternalChatDeliveryResponse, ExternalChatDeliveryResponses, ExternalChatDeliveryState, ExternalChatDetail, ExternalChatEvent, ExternalChatKind, ExternalChatLocation, ExternalChatMediaKind, ExternalChatMediaPresentation, ExternalChatMembers, ExternalChatMention, ExternalChatMessage, ExternalChatMessageAttachments, ExternalChatMessageAttachmentsData, ExternalChatMessageAttachmentsResponse, ExternalChatMessageAttachmentsResponses, ExternalChatMessageData, ExternalChatMessageKind, ExternalChatMessageResponse, ExternalChatMessageResponses, ExternalChatMessages, ExternalChatMessagesData, ExternalChatMessagesResponse, ExternalChatMessagesResponses, ExternalChatMutation, ExternalChatParticipant, ExternalChatPermissionsData, ExternalChatPermissionsResponse, ExternalChatPermissionsResponses, ExternalChatPersonRef, ExternalChatPoll, ExternalChatPollOption, ExternalChatProvider, ExternalChatReaction, ExternalChatReadData, ExternalChatReadResponse, ExternalChatReadResponses, ExternalChatReference, ExternalChatRemoveData, ExternalChatRemoveResponse, ExternalChatRemoveResponses, ExternalChatReplyBlock, ExternalChatReplyContent, ExternalChatResponse, ExternalChatResponses, ExternalChatRichContent, ExternalChatsData, ExternalChatSendData, ExternalChatSender, ExternalChatSendErrors, ExternalChatSendProgress, ExternalChatSendReply, ExternalChatSendResponse, ExternalChatSendResponses, ExternalChatSendsData, ExternalChatSendsResponse, ExternalChatSendsResponses, ExternalChatsResponse, ExternalChatsResponses, ExternalChatSummary, ExternalChatSystemAction, ExternalChatSystemLine, ExternalChatUpdatePermissionsData, ExternalChatUpdatePermissionsResponse, ExternalChatUpdatePermissionsResponses, ExternalChatUploadData, ExternalChatUploadedAttachment, ExternalChatUploadRequest, ExternalChatUploadResponse, ExternalChatUploadResponses, Favorite, FavoriteEntityRef, FavoritesList, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, 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, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, 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, GetCrmPipelineData, GetCrmPipelinePermissionsData, GetCrmPipelinePermissionsResponse, GetCrmPipelinePermissionsResponses, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, 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, GetDocumentTextContentData, GetDocumentTextContentErrors, GetDocumentTextContentResponse, GetDocumentTextContentResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, 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, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, 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, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestCallChatPostData, GuestCallChatPostErrors, GuestCallChatPostResponse, GuestCallChatPostResponses, GuestCallChatReadData, GuestCallChatReadErrors, GuestCallChatReadResponse, GuestCallChatReadResponses, GuestChatMessage, GuestChatPage, GuestChatPost, GuestId, GuestJoinRequest, GuestPolicy, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListJoinRequestsData, ListJoinRequestsError, ListJoinRequestsErrors, ListJoinRequestsResponse, ListJoinRequestsResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MarkRead, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionId, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyBucketing, PropertyDateFilterRange, PropertyDateRange, PropertyDateRanges, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDatabasesData, QueryDatabasesError, QueryDatabasesErrors, QueryDatabasesResponse, QueryDatabasesResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, 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, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestAccess, RequestedHarnessScope, RequestedLayout, RequestStatus, RequestToJoinData, RequestToJoinError, RequestToJoinErrors, RequestToJoinResponse, RequestToJoinResponses, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveRequest, ResponseStatus, ResponseSummary, ResultColumn, ResultSet, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionSource, 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, SetDirectAccess, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharedExternalChatReference, ShareEntity, ShareEntityType, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, SqlCell, SqlEntityKind, SqlOutcome, SqlOutcomeKind, SqlSelectOption, SqlStatement, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableId, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TaskSimilarityResult, TaskSimilaritySearchHandlerData, TaskSimilaritySearchHandlerError, TaskSimilaritySearchHandlerErrors, TaskSimilaritySearchHandlerResponse, TaskSimilaritySearchHandlerResponses, TaskSimilaritySearchRequest, TaskSimilaritySearchResponse, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmPipelinePermissionsData, UpdateCrmPipelinePermissionsResponse, UpdateCrmPipelinePermissionsResponses, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, 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, VersionedTable, View, ViewChange, ViewColumn, ViewerCapabilities, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WhatsAppAccount, WhatsappAccountData, WhatsappAccountResponse, WhatsappAccountResponses, WhatsAppAccountState, WhatsAppAccountView, WhatsappCancelPairingData, WhatsappCancelPairingResponse, WhatsappCancelPairingResponses, WhatsAppCannotAdd, WhatsAppChat, WhatsAppChats, WhatsappChatsData, WhatsappChatsResponse, WhatsappChatsResponses, WhatsAppConnect, WhatsappConnectData, WhatsappConnectResponse, WhatsappConnectResponses, WhatsAppDisconnect, WhatsappDisconnectData, WhatsAppDisconnectRequest, WhatsappDisconnectResponse, WhatsappDisconnectResponses, WhatsAppHistoryImport, WhatsappImportHistoryData, WhatsappImportHistoryResponse, WhatsappImportHistoryResponses, WhatsAppLookup, WhatsappLookupData, WhatsAppLookupRequest, WhatsappLookupResponse, WhatsappLookupResponses, WhatsAppLookupState, WhatsAppPairing, WhatsappPairingData, WhatsappPairingResponse, WhatsappPairingResponses, WhatsAppPairingState, WhatsAppPairState, WhatsappPasskeyData, WhatsappPasskeyResponse, WhatsappPasskeyResponses, WhatsappStartLookupData, WhatsappStartLookupResponse, WhatsappStartLookupResponses, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 02b2e548f5..98e8c8665d 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -2779,6 +2779,11 @@ export type ChannelLabelRule = {
contains: string;
};
+/**
+ * Requested label namespace. Omission retains the deployed automatic selection.
+ */
+export type ChannelLabelScopeSelection = 'personal' | 'team';
+
/**
* The authorized scope's labels in manual order.
*/
@@ -2787,6 +2792,10 @@ export type ChannelLabelsList = {
* Every label of the scope, whether or not the caller sees channels in it.
*/
labels: Array<ChannelLabel>;
+ /**
+ * Resolved label namespace.
+ */
+ scope: ChannelLabelScopeSelection;
/**
* Team scope, or `None` for private labels.
*/
@@ -18240,7 +18249,12 @@ export type IngestTranscriptResponses = {
export type ListChannelLabelsData = {
body?: never;
path?: never;
- query?: never;
+ query?: {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+ };
url: '/channel-labels';
};
@@ -18261,7 +18275,12 @@ export type ListChannelLabelsResponse = ListChannelLabelsResponses[keyof ListCha
export type CreateChannelLabelData = {
body: CreateChannelLabelRequest;
path?: never;
- query?: never;
+ query?: {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+ };
url: '/channel-labels';
};
@@ -18290,7 +18309,12 @@ export type SetChannelLabelData = {
*/
channel_id: string;
};
- query?: never;
+ query?: {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+ };
url: '/channel-labels/channels/{channel_id}';
};
@@ -18313,7 +18337,12 @@ export type SetChannelLabelResponse = SetChannelLabelResponses[keyof SetChannelL
export type PreviewSmartTagData = {
body: ChannelLabelRule;
path?: never;
- query?: never;
+ query?: {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+ };
url: '/channel-labels/preview';
};
@@ -18340,7 +18369,12 @@ export type DeleteChannelLabelData = {
*/
label_id: string;
};
- query?: never;
+ query?: {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+ };
url: '/channel-labels/{label_id}';
};
@@ -18367,7 +18401,12 @@ export type RenameChannelLabelData = {
*/
label_id: string;
};
- query?: never;
+ query?: {
+ /**
+ * `personal` selects private labels; `team` requires team membership.
+ */
+ scope?: ChannelLabelScopeSelection;
+ };
url: '/channel-labels/{label_id}';
};
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index b377f726eb..46d9b03c14 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -3019,6 +3019,17 @@
"tags": ["channel_labels"],
"summary": "List the caller's shared or private labels.",
"operationId": "list_channel_labels",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
+ }
+ ],
"responses": {
"200": {
"description": "",
@@ -3066,6 +3077,17 @@
"tags": ["channel_labels"],
"summary": "Create a label for the caller's authorized scope.",
"operationId": "create_channel_label",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -3165,6 +3187,15 @@
"type": "string",
"format": "uuid"
}
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
}
],
"requestBody": {
@@ -3239,6 +3270,17 @@
"tags": ["channel_labels"],
"summary": "Preview visible channels matched by a smart tag, without creating it.",
"operationId": "preview_smart_tag",
+ "parameters": [
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
+ }
+ ],
"requestBody": {
"content": {
"application/json": {
@@ -3318,6 +3360,15 @@
"type": "string",
"format": "uuid"
}
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
}
],
"responses": {
@@ -3380,6 +3431,15 @@
"type": "string",
"format": "uuid"
}
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "`personal` selects private labels; `team` requires team membership.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection"
+ }
}
],
"requestBody": {
@@ -23669,10 +23729,15 @@
],
"description": "An attribute rule that automatically groups matching channels."
},
+ "ChannelLabelScopeSelection": {
+ "type": "string",
+ "description": "Requested label namespace. Omission retains the deployed automatic selection.",
+ "enum": ["personal", "team"]
+ },
"ChannelLabelsList": {
"type": "object",
"description": "The authorized scope's labels in manual order.",
- "required": ["labels"],
+ "required": ["scope", "labels"],
"properties": {
"labels": {
"type": "array",
@@ -23681,6 +23746,10 @@
},
"description": "Every label of the scope, whether or not the caller sees channels in it."
},
+ "scope": {
+ "$ref": "#/components/schemas/ChannelLabelScopeSelection",
+ "description": "Resolved label namespace."
+ },
"teamId": {
"type": ["string", "null"],
"format": "uuid",
diff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.md
index b87e036165..dc2c37e5cf 100644
--- a/services/document_storage_service/AGENTS.md
+++ b/services/document_storage_service/AGENTS.md
@@ -68,7 +68,7 @@ threads, pins, recents, notifications, folders, activity.
- Add a Soup GraphQL field: resolver/loader in `crates/graphql_soup` →
`src/api/graphql_soup.rs` if wiring changes.
- Add a REST route: `src/api/<area>.rs` → `src/api.rs` (router) →
- `src/api/swagger.rs`.
+ `src/api/swagger.rs`; register query-only schemas explicitly in its components list.
- Add a config value or feature-gated behavior: `src/config.rs` → the
`[features]` table in `Cargo.toml` if it should be independently toggleable.
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index 01e389ecce..659062ed21 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -58,7 +58,8 @@ use crate::{
},
};
use channel_labels::domain::models::{
- ChannelLabel, ChannelLabelRule, ChannelLabelsList, SmartTagChannelMatch, SmartTagPreview,
+ ChannelLabel, ChannelLabelRule, ChannelLabelScopeSelection, ChannelLabelsList,
+ SmartTagChannelMatch, SmartTagPreview,
};
use channel_labels::inbound::axum_router::{
CreateChannelLabelRequest, RenameChannelLabelRequest, SetChannelLabelRequest,
@@ -715,6 +716,7 @@ use utoipa::OpenApi;
ChannelLabel,
ChannelLabelsList,
ChannelLabelRule,
+ ChannelLabelScopeSelection,
SmartTagChannelMatch,
SmartTagPreview,
CreateChannelLabelRequest,
diff --git a/vendor/utoipa-swagger-ui/Cargo.toml b/vendor/utoipa-swagger-ui/Cargo.toml
index dd67481492..57246cddcf 100644
--- a/vendor/utoipa-swagger-ui/Cargo.toml
+++ b/vendor/utoipa-swagger-ui/Cargo.toml
@@ -147,7 +147,7 @@ version = "0.1"
optional = true
[build-dependencies.zip]
-version = "3.0"
+version = "9.0.5"
features = ["deflate"]
default-features = false
diff --git a/vendor/utoipa-swagger-ui/README-MACRO.md b/vendor/utoipa-swagger-ui/README-MACRO.md
index a5b4ac2922..e115bf14ce 100644
--- a/vendor/utoipa-swagger-ui/README-MACRO.md
+++ b/vendor/utoipa-swagger-ui/README-MACRO.md
@@ -6,9 +6,12 @@ and `--remap-path-prefix` does not rewrite string literals, so the compiled
crate differed in every checkout. Every service above it, and their test
binaries, then had a different kache key on each machine and in CI.
-The functional change: the build script writes `$OUT_DIR/…` and rust-embed's
-`interpolate-folder-path` expands it at compile time. Drop this copy once
-upstream emits a relative or interpolated folder.
+The build script writes `$OUT_DIR/…` and rust-embed's
+`interpolate-folder-path` expands it at compile time.
+
+The ZIP build dependency is updated to `9.0.5`, matching the workspace, to
+remove the vulnerable `zip 3` dependency. Keep both patches when refreshing
+this copy; drop it once upstream covers both changes.
`Cargo.toml` also drops the author's email from `authors`, which the
repository's PII scan rejects.
diff --git a/vendor/utoipa-swagger-ui/build.rs b/vendor/utoipa-swagger-ui/build.rs
index 09d5799ca4..feaac60dac 100644
--- a/vendor/utoipa-swagger-ui/build.rs
+++ b/vendor/utoipa-swagger-ui/build.rs
@@ -114,7 +114,7 @@ impl SwaggerZip {
let directory = [&target_dir].iter().collect::<PathBuf>();
let out_path = directory.join(filepath);
- if file.name().ends_with('/') {
+ if file.name()?.ends_with('/') {
fs::create_dir_all(&out_path)?;
} else {
if let Some(p) = out_path.parent() {