Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(sharing): team sharing for chats (#6450)
Will Hutchinson81f0d9bb085e
diff --git a/.sqlx/query-49088955bcab31835d8fc01c61693aae1ffa798b3621e97aa5a2eb328a11c303.json b/.sqlx/query-49088955bcab31835d8fc01c61693aae1ffa798b3621e97aa5a2eb328a11c303.jsonnew file mode 100644index 0000000000..2e3f847e90--- /dev/null+++ b/.sqlx/query-49088955bcab31835d8fc01c61693aae1ffa798b3621e97aa5a2eb328a11c303.json@@ -0,0 +1,76 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n sp.team_share_access_level as \"team_share_access_level?: AccessLevel\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "link_share?",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "link_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "team_share_access_level?: AccessLevel",+ "type_info": {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "comment",+ "edit",+ "owner"+ ]+ }+ }+ }+ },+ {+ "ordinal": 4,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ true,+ false,+ null+ ]+ },+ "hash": "49088955bcab31835d8fc01c61693aae1ffa798b3621e97aa5a2eb328a11c303"+}diff --git a/.sqlx/query-a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c.json b/.sqlx/query-a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c.jsondeleted file mode 100644index 7f73edd639..0000000000--- a/.sqlx/query-a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c.json+++ /dev/null@@ -1,58 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n sp.id as id,\n sp.\"linkShare\" as \"link_share?\",\n sp.\"linkShareAccessLevel\" as \"link_share_access_level?: AccessLevel\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- },- {- "ordinal": 1,- "name": "link_share?",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "link_share_access_level?: AccessLevel",- "type_info": {- "Custom": {- "name": "\"AccessLevel\"",- "kind": {- "Enum": [- "view",- "comment",- "edit",- "owner"- ]- }- }- }- },- {- "ordinal": 3,- "name": "owner",- "type_info": "Text"- },- {- "ordinal": 4,- "name": "channel_share_permissions?",- "type_info": "Json"- }- ],- "parameters": {- "Left": [- "Text"- ]- },- "nullable": [- false,- true,- true,- false,- null- ]- },- "hash": "a451041dec8da33ffa7a375c13d3a6115c8241b019f09f72eb487c926700a98c"-}diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsxindex 33887ff358..bb86c16501 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.test.tsx@@ -1,6 +1,6 @@import { ForwardToChannel } from '@core/component/ForwardToChannel';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { createSignal, type JSX } from 'solid-js';+import { createSignal, For, type JSX } from 'solid-js';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { Permissions } from '../SharePermissions';import { ShareDialogContext, ShareModal, ShareTrigger } from './ShareButton';@@ -9,8 +9,10 @@ const mocks = vi.hoisted(() => ({sendToChannel: vi.fn(),sendToUsers: vi.fn(),mobile: false,+ hasTeam: false,getDocumentPermissions: vi.fn(),getChatPermissions: vi.fn(),+ updateChatPermissions: vi.fn(),getProjectPermissions: vi.fn(),copyLink: vi.fn(),blockPermissionsRead: vi.fn(),@@ -37,6 +39,7 @@ vi.mock('@core/block', () => ({},{ refetch: vi.fn() },],+ useBlockName: () => 'md',useMaybeBlockName: () => 'md',useMaybeBlockAliasedName: () => 'md',useMaybeBlockId: () => 'launcher-placeholder',@@ -117,10 +120,16 @@ vi.mock('@core/util/url', () => ({`https://macro.com/app/${type}/${id}`,}));vi.mock('@service-cognition/client', () => ({- cognitionApiServiceClient: { getChatPermissions: mocks.getChatPermissions },+ cognitionApiServiceClient: {+ getChatPermissions: mocks.getChatPermissions,+ updateChatPermissions: mocks.updateChatPermissions,+ },}));vi.mock('@queries/team/teams', () => ({- useCurrentTeamQuery: () => ({ isSuccess: false, data: undefined }),+ useCurrentTeamQuery: () => ({+ isSuccess: mocks.hasTeam,+ data: mocks.hasTeam ? { id: 'team-1' } : undefined,+ }),}));vi.mock('@solidjs/router', () => ({ useNavigate: () => vi.fn() }));vi.mock('./LoginButton', () => ({ openLoginModal: vi.fn() }));@@ -168,8 +177,35 @@ vi.mock('@ui', () => {Trigger: Container,Content: Container,Item: Container,+ // Each radio group exposes one button per option, labelled by the group's+ // accessible name, so tests can pick a value on a specific group.+ RadioGroup: (props: {+ children?: JSX.Element;+ value?: string;+ 'aria-label'?: string;+ onChange?: (value: string) => void;+ }) => {+ const label = props['aria-label'] ?? 'option';+ return (+ <div role="group" aria-label={label} data-value={props.value}>+ {props.children}+ <For each={['NONE', 'view', 'comment', 'edit']}>+ {(value) => (+ <button+ aria-label={`Set ${label} ${value}`}+ onClick={() => props.onChange?.(value)}+ />+ )}+ </For>+ </div>+ );+ },+ RadioItem: Container,+ ItemIndicator: Container,+ Group: Container,}),ButtonGroup: Object.assign(Container, { Divider: () => null }),+ SegmentedControl: () => null,cn: (...values: unknown[]) => values.filter(Boolean).join(' '),Hotkey: () => null,};@@ -177,6 +213,8 @@ vi.mock('@ui', () => {beforeEach(() => {vi.clearAllMocks();mocks.mobile = false;+ mocks.hasTeam = false;+ mocks.updateChatPermissions.mockResolvedValue({ isErr: () => false });Object.defineProperty(navigator, 'clipboard', {configurable: true,value: { writeText: mocks.copyLink },@@ -312,3 +350,85 @@ describe('agent session sharing', () => {);});});++function mountChatShare() {+ mocks.blockPermissionsRead.mockReturnValue({+ isErr: () => false,+ value: {+ id: 'perm-1',+ owner: 'owner',+ linkShare: null,+ linkShareAccessLevel: null,+ teamShareAccessLevel: 'view',+ channelSharePermissions: [],+ },+ });+ render(() => (+ <ShareModal+ id="chat-1"+ name="Planning chat"+ owner="owner"+ itemType="chat"+ blockAlias="chat"+ userPermissions={Permissions.OWNER}+ isSharePermOpen+ setIsSharePermOpen={vi.fn()}+ />+ ));+}++describe('chat team sharing', () => {+ it('lets the owner share the chat with their team through the chat permissions endpoint', async () => {+ mocks.hasTeam = true;+ mountChatShare();++ expect(screen.getByText('Team access')).toBeTruthy();+ expect(+ screen.getByText("Share this chat directly with the owner's team.")+ ).toBeTruthy();+ expect(+ screen+ .getByRole('group', { name: 'Team access level' })+ .getAttribute('data-value')+ ).toBe('view');++ fireEvent.click(+ screen.getByRole('button', { name: 'Set Team access level edit' })+ );++ await vi.waitFor(() =>+ expect(mocks.updateChatPermissions).toHaveBeenCalledWith({+ chat_id: 'chat-1',+ sharePermission: { teamShareAccessLevel: 'edit' },+ })+ );+ expect(mocks.getDocumentPermissions).not.toHaveBeenCalled();+ });++ it('clears team access with an explicit null', async () => {+ mocks.hasTeam = true;+ mountChatShare();++ fireEvent.click(+ screen.getByRole('button', { name: 'Set Team access level NONE' })+ );++ await vi.waitFor(() =>+ expect(mocks.updateChatPermissions).toHaveBeenCalledWith({+ chat_id: 'chat-1',+ sharePermission: { teamShareAccessLevel: null },+ })+ );+ });++ it('hides team access when the owner has no team', () => {+ mocks.hasTeam = false;+ mountChatShare();++ expect(screen.queryByText('Team access')).toBeNull();+ expect(+ screen.queryByRole('group', { name: 'Team access level' })+ ).toBeNull();+ expect(mocks.updateChatPermissions).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx b/apps/web/src/lib/core/component/TopBar/ShareButton.tsxindex d7db3bd5b6..b3ad25caeb 100644--- a/apps/web/src/lib/core/component/TopBar/ShareButton.tsx+++ b/apps/web/src/lib/core/component/TopBar/ShareButton.tsx@@ -96,9 +96,11 @@ import {buildTeamSharePayload,getLinkShareScope,getLinkShareScopeCopy,+ getShareItemNoun,getShareStatus,getTeamShareScope,getTeamShareScopeCopy,+ isTeamShareSupportedForItem,LINK_SHARE_SCOPE_OPTIONS,type LinkSharePayload,type LinkShareScope,@@ -288,10 +290,15 @@ interface LinkSharingControlsProps {setLinkShareScope: (scope: LinkShareScope) => void;setLinkShareAccessLevel: (accessLevel: AccessLevel | null) => void;copyLink: () => void;- teamShare?: {- accessLevel: AccessLevel | null | undefined;- setAccessLevel: (scope: TeamShareScope) => void;- };+ teamShare?: TeamShareControls;+}++/** Owner-only explicit team sharing, present only for entity types that support it. */+interface TeamShareControls {+ accessLevel: AccessLevel | null | undefined;+ setAccessLevel: (scope: TeamShareScope) => void;+ /** Noun for the copy, e.g. "document" or "chat". */+ itemNoun: string;}function LinkSharingControls(props: LinkSharingControlsProps) {@@ -300,6 +307,7 @@ function LinkSharingControls(props: LinkSharingControlsProps) {const shareStatus = () =>getShareStatus(props.linkShare, props.hasExplicitShares);const teamShareScope = () => getTeamShareScope(props.teamShare?.accessLevel);+ const teamShareNoun = () => props.teamShare?.itemNoun ?? 'item';return (<div class="flex flex-col gap-3 p-4 text-sm text-ink">@@ -351,7 +359,7 @@ function LinkSharingControls(props: LinkSharingControlsProps) {<div class="flex flex-col gap-1"><span class="font-medium">Team access</span><p class="text-sm text-ink-muted">- Share this document directly with the owner's team.+ Share this {teamShareNoun()} directly with the owner's team.</p></div><Dropdown>@@ -365,6 +373,7 @@ function LinkSharingControls(props: LinkSharingControlsProps) {</Dropdown.Trigger><Dropdown.Content portalScope="local"><Dropdown.RadioGroup+ aria-label="Team access level"value={teamShareScope()}onChange={(value) =>props.teamShare?.setAccessLevel(value as TeamShareScope)@@ -639,6 +648,7 @@ function MobileShareDrawer(props: MobileShareDrawerProps) {? {accessLevel: props.teamShareAccessLevel,setAccessLevel: props.setTeamShareAccessLevel,+ itemNoun: getShareItemNoun(props.itemType),}: undefined}@@ -959,14 +969,23 @@ export function ShareModal(props: ShareModalProps) {const updateTeamSharePermissions = createCallback(async (sharePermission: TeamSharePayload) => {- if (props.itemType !== 'document') {+ if (!isTeamShareSupportedForItem(props.itemType)) {return;}-- const result = await storageServiceClient.editDocument({- sharePermission,- documentId: props.id,- });+ const itemNoun = getShareItemNoun(props.itemType);++ // Both endpoints accept the same `sharePermission.teamShareAccessLevel`+ // patch; the backend authorizes it against the persisted owner.+ const result =+ props.itemType === 'chat'+ ? await cognitionApiServiceClient.updateChatPermissions({+ sharePermission,+ chat_id: props.id,+ })+ : await storageServiceClient.editDocument({+ sharePermission,+ documentId: props.id,+ });if (result.isErr()) {toast.alert('Failed to change team access', {subtext: 'Please try again',@@ -978,12 +997,12 @@ export function ShareModal(props: ShareModalProps) {refetch();const scope = getTeamShareScope(sharePermission.teamShareAccessLevel);if (scope === 'NONE') {- toast.success('Removed team access for this document');+ toast.success(`Removed team access for this ${itemNoun}`);return;}toast.success('Updated team access', {- subtext: `The owner's team can ${getTeamShareScopeCopy(scope).toLowerCase()} this document`,+ subtext: `The owner's team can ${getTeamShareScopeCopy(scope).toLowerCase()} this ${itemNoun}`,});analytics.track('share_entity', {entityType: props.itemType,@@ -998,14 +1017,15 @@ export function ShareModal(props: ShareModalProps) {return updateTeamSharePermissions(buildTeamSharePayload(scope));});- const teamShareControls = () =>- props.itemType === 'document' &&+ const teamShareControls = (): TeamShareControls | undefined =>+ isTeamShareSupportedForItem(props.itemType) &&props.userPermissions === Permissions.OWNER &¤tTeamQuery.isSuccess &¤tTeamQuery.data? {accessLevel: teamShareAccessLevel(),setAccessLevel: setTeamShareAccessLevel,+ itemNoun: getShareItemNoun(props.itemType),}: undefined;diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts b/apps/web/src/lib/core/component/TopBar/linkShare.test.tsindex 4d62697b96..068f2088f5 100644--- a/apps/web/src/lib/core/component/TopBar/linkShare.test.ts+++ b/apps/web/src/lib/core/component/TopBar/linkShare.test.ts@@ -5,12 +5,38 @@ import {buildTeamSharePayload,getLinkShareScope,getLinkShareScopeCopy,+ getShareItemNoun,getShareStatus,getTeamShareScope,+ isTeamShareSupportedForItem,LINK_SHARE_SCOPE_OPTIONS,TEAM_SHARE_SCOPE_OPTIONS,} from './linkShare';+describe('isTeamShareSupportedForItem', () => {+ it.each(['document', 'chat'] as const)('supports %s', (itemType) => {+ expect(isTeamShareSupportedForItem(itemType)).toBe(true);+ });++ it.each(['project', 'email', 'agent_session', 'call'] as const)(+ 'does not offer team access for %s',+ (itemType) => {+ expect(isTeamShareSupportedForItem(itemType)).toBe(false);+ }+ );+});++describe('getShareItemNoun', () => {+ it.each([+ ['document', 'document'],+ ['chat', 'chat'],+ ['email', 'email thread'],+ ['agent_session', 'agent session'],+ ] as const)('names %s as "%s"', (itemType, noun) => {+ expect(getShareItemNoun(itemType)).toBe(noun);+ });+});+describe('getLinkShareScope', () => {it.each([null, undefined])('maps %s to NONE', (linkShare) => {expect(getLinkShareScope(linkShare)).toBe('NONE');diff --git a/apps/web/src/lib/core/component/TopBar/linkShare.ts b/apps/web/src/lib/core/component/TopBar/linkShare.tsindex a975403d71..8aa467f810 100644--- a/apps/web/src/lib/core/component/TopBar/linkShare.ts+++ b/apps/web/src/lib/core/component/TopBar/linkShare.ts@@ -1,9 +1,35 @@+import type { ItemType } from '@service-storage/client';import type { AccessLevel } from '@service-storage/generated/schemas/accessLevel';import type { LinkShare } from '@service-storage/generated/schemas/linkShare';import type { UpdateSharePermissionRequestV2 } from '@service-storage/generated/schemas/updateSharePermissionRequestV2';export const NO_LINK_SHARE = 'NONE' as const;+/**+ * Entity types whose backend honors `sharePermission.teamShareAccessLevel`+ * (documents via `PATCH /documents/{id}`, AI chats via `PATCH /chats/{id}`).+ */+const TEAM_SHAREABLE_ITEM_TYPES: ReadonlySet<ItemType> = new Set<ItemType>([+ 'document',+ 'chat',+]);++export function isTeamShareSupportedForItem(itemType: ItemType): boolean {+ return TEAM_SHAREABLE_ITEM_TYPES.has(itemType);+}++/** Human noun for share-modal copy such as "Share this chat with the owner's team." */+export function getShareItemNoun(itemType: ItemType): string {+ switch (itemType) {+ case 'email':+ return 'email thread';+ case 'agent_session':+ return 'agent session';+ default:+ return itemType;+ }+}+export type LinkShareScope = LinkShare | typeof NO_LINK_SHARE;export type LinkSharePayload = Required<diff --git a/crates/chat/README.md b/crates/chat/README.mdindex 25e78c2080..f680494a64 100644--- a/crates/chat/README.md+++ b/crates/chat/README.md@@ -29,7 +29,11 @@ Optional metadata is serialized as `null`. On `chat.updated`, `name` and`project_id` describe the requested PATCH: `null` means the field was omitted,and `project_id: ""` means the chat was removed from its project (mirroringthe `PatchChatArgs` semantics). `previous_project_id` is the project in the-pre-PATCH chat snapshot when known. On the deleted, permanently-deleted, and+pre-PATCH chat snapshot when known. `share_permission_updated` is `true` for+any `sharePermission` patch, including an explicit `teamShareAccessLevel`,+which only the chat's persisted owner may set (shared with the owner's team+through the canonical `SharePermission.team_share_*` state and an+`entity_access` team grant). On the deleted, permanently-deleted, andrestored events, `actor_user_id` is `null` for unauthenticated or internalcallers.diff --git a/crates/chat/src/domain/models/chat.rs b/crates/chat/src/domain/models/chat.rsindex a132ffe62f..f9a3f6fe76 100644--- a/crates/chat/src/domain/models/chat.rs+++ b/crates/chat/src/domain/models/chat.rs@@ -1,5 +1,6 @@use model::chat::ChatMessageWithAttachments;use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::team_share::AuthorizedTeamShareCommand;use serde::{Deserialize, Serialize};use utoipa::ToSchema;@@ -21,7 +22,7 @@ pub struct CopyChatArgs {pub project_id: Option<String>,}-/// Arguments for patching a chat.+/// Arguments for patching a chat, as supplied by inbound callers.#[derive(Debug)]pub struct PatchChatArgs {/// New name for the chat, if changing.@@ -33,6 +34,24 @@ pub struct PatchChatArgs {Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,}+/// Arguments the domain service hands to the repository when patching a chat.+///+/// Only the service can produce the authorized team-share command, so inbound+/// callers cannot request a team grant the owner policy has not approved.+#[derive(Debug)]+pub struct PatchChatRepoArgs {+ /// New name for the chat, if changing.+ pub name: Option<String>,+ /// New project ID for the chat, if moving. Empty string clears the project.+ pub project_id: Option<String>,+ /// Share permission updates, if changing.+ pub share_permission:+ Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,+ /// Owner-authorized team-share write, present only when the request+ /// carried an explicit `teamShareAccessLevel`.+ pub team_share: Option<AuthorizedTeamShareCommand>,+}+/// Wrapper response for get_chat, matching the DCS API response shape.#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]#[serde(rename_all = "camelCase")]diff --git a/crates/chat/src/domain/models/error.rs b/crates/chat/src/domain/models/error.rsindex c5dce8147c..06ad9da177 100644--- a/crates/chat/src/domain/models/error.rs+++ b/crates/chat/src/domain/models/error.rs@@ -16,6 +16,10 @@ pub enum ChatErr {/// Bad request#[error("bad request: {0}")]BadRequest(String),+ /// The requested change conflicts with the persisted state (for example a+ /// stale team-share revision); the caller should reload and retry.+ #[error("conflict: {0}")]+ Conflict(String),/// Access denied.#[error(transparent)]Access(#[from] AccessError),diff --git a/crates/chat/src/domain/models/mod.rs b/crates/chat/src/domain/models/mod.rsindex a9dc652fcb..e179aec9ae 100644--- a/crates/chat/src/domain/models/mod.rs+++ b/crates/chat/src/domain/models/mod.rs@@ -5,7 +5,9 @@ mod error;mod message;pub mod model_access;-pub use chat::{ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs};+pub use chat::{+ ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs, PatchChatRepoArgs,+};pub use error::{ChatErr, Result};pub use message::{PatchChatMessageArgs, ResolvedMessageContent, WebCitation};pub use model_access::{CHAT_MODELS, FREE_MODEL, PAID_DEFAULT_MODEL};diff --git a/crates/chat/src/domain/ports/chat.rs b/crates/chat/src/domain/ports/chat.rsindex d5971802a4..32f3a84777 100644--- a/crates/chat/src/domain/ports/chat.rs+++ b/crates/chat/src/domain/ports/chat.rs@@ -1,6 +1,6 @@use crate::domain::models::{ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs,- PatchChatMessageArgs, Result,+ PatchChatMessageArgs, PatchChatRepoArgs, Result,};use agent::types::ChatMessageContent;use ai_toolset::tool_object::UserToolResponse;@@ -11,6 +11,7 @@ use entity_access::domain::models::{use macro_user_id::user_id::MacroUserIdStr;use model::chat::Chat;use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::team_share::TeamShareFacts;use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};/// Repository trait for low-level chat data access.@@ -75,6 +76,13 @@ pub trait ChatRepo: Send + Sync + 'static {chat_id: &str,) -> impl std::future::Future<Output = Result<SharePermissionV2>> + Send;+ /// Load the canonical team-share facts (persisted owner, owner's team,+ /// current explicit grant, revision) the owner policy authorizes against.+ fn get_team_share_facts(+ &self,+ chat_id: &str,+ ) -> impl std::future::Future<Output = Result<TeamShareFacts>> + Send;+/// Soft-delete a chat (sets `deleted_at`, removes pins and history).fn delete(&self, chat_id: &str) -> impl std::future::Future<Output = Result<()>> + Send;@@ -85,11 +93,15 @@ pub trait ChatRepo: Send + Sync + 'static {) -> impl std::future::Future<Output = Result<()>> + Send;/// Patch a chat's metadata (name, project, share permissions).+ ///+ /// `args.team_share` is the owner-authorized command for an explicit+ /// `teamShareAccessLevel`; the repository applies it atomically with the+ /// rest of the patch and rejects a team level that arrives without one.fn patch(&self,user_id: MacroUserIdStr<'static>,chat_id: &str,- args: PatchChatArgs,+ args: PatchChatRepoArgs,) -> impl std::future::Future<Output = Result<()>> + Send;/// Update a project's `updatedAt` timestamp.diff --git a/crates/chat/src/domain/service/chat.rs b/crates/chat/src/domain/service/chat.rsindex ab7a37162e..451513d23e 100644--- a/crates/chat/src/domain/service/chat.rs+++ b/crates/chat/src/domain/service/chat.rs@@ -8,20 +8,27 @@ use crate::domain::{ChatCopiedMetadata, ChatCreatedMetadata, ChatDeletedMetadata, ChatMacroEvent,ChatPermanentlyDeletedMetadata, ChatRestoredMetadata, ChatUpdatedMetadata,},- models::{ChatErr, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs, Result},+ models::{+ ChatErr, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs, PatchChatRepoArgs,+ Result,+ },ports::{ChatRepo, ChatService},};use agent::types::{AssistantMessagePart, ChatMessageContent};use ai_toolset::{AsyncToolCollection, RequestContext, tool_object::UserToolResponse};use entity_access::domain::models::{- AccessLevel, EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityPermission,- OwnerAccessLevel, ViewAccessLevel,+ AccessError, AccessLevel, EditAccessLevel, EntityAccessAuth, EntityAccessReceipt,+ EntityPermission, OwnerAccessLevel, ViewAccessLevel,};use entity_access_management::domain::ports::EntityAccessManagementService;use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};use macro_user_id::user_id::MacroUserIdStr;use model_entity::EntityType;use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::team_share::{+ AuthorizedTeamShareCommand, TeamShareLevel, TeamSharePolicyError, TeamShareRequest,+ authorize_team_share,+};use std::sync::Arc;use unicode_segmentation::UnicodeSegmentation;@@ -110,6 +117,41 @@ wheretracing::error!(error = ?error, "failed to schedule chat event");}));}++ /// Authorize an explicit team-share change against the persisted owner.+ ///+ /// Returns `Ok(None)` without loading anything when the request omits the+ /// team level, so ordinary renames and moves never take the team-share+ /// guard. Effective Owner access (for example via a project) is not enough:+ /// only the chat's actual owner may share it with their team.+ async fn authorize_chat_team_share(+ &self,+ receipt: &EntityAccessReceipt<OwnerAccessLevel>,+ request: TeamShareRequest,+ ) -> Result<Option<AuthorizedTeamShareCommand>> {+ if request == TeamShareRequest::default() {+ return Ok(None);+ }+ let facts = self+ .repo+ .get_team_share_facts(&receipt.entity().entity_id)+ .await?;+ authorize_team_share(+ receipt.acting_user_id(),+ &facts,+ request,+ TeamShareLevel::Edit,+ )+ .map_err(|error| match error {+ TeamSharePolicyError::MissingActor | TeamSharePolicyError::NotOwner => {+ ChatErr::Access(AccessError::Unauthorized)+ }+ TeamSharePolicyError::InvalidRevision => ChatErr::Conflict(error.to_string()),+ TeamSharePolicyError::MissingTeam+ | TeamSharePolicyError::InvalidLevel+ | TeamSharePolicyError::ContradictoryInputs => ChatErr::BadRequest(error.to_string()),+ })+ }}impl<R: ChatRepo, ToolSetContext, Eam: EntityAccessManagementService, B: MacroEventBroker>@@ -352,6 +394,21 @@ wherelet user_id = entity_access_receipt.get_authenticated_user()?;let chat_id = &entity_access_receipt.entity().entity_id;+ // Team sharing is authorized against the persisted owner before any+ // write; a rejected request returns here and publishes nothing.+ let team_share = self+ .authorize_chat_team_share(+ &entity_access_receipt,+ TeamShareRequest {+ access_level: args+ .share_permission+ .as_ref()+ .and_then(|p| p.team_share_access_level),+ legacy_enabled: None,+ },+ )+ .await?;+let old_project_id = self.repo.get_metadata(chat_id)@@ -364,7 +421,18 @@ wherelet name = args.name.clone();let share_permission_updated = args.share_permission.is_some();- self.repo.patch(user_id.to_owned(), chat_id, args).await?;+ self.repo+ .patch(+ user_id.to_owned(),+ chat_id,+ PatchChatRepoArgs {+ name: args.name,+ project_id: args.project_id,+ share_permission: args.share_permission,+ team_share,+ },+ )+ .await?;// Remove from old project (only if the project is actually changing)if project_changingdiff --git a/crates/chat/src/domain/service/chat/test.rs b/crates/chat/src/domain/service/chat/test.rsindex 9a9a8a50f8..ec5fc6990d 100644--- a/crates/chat/src/domain/service/chat/test.rs+++ b/crates/chat/src/domain/service/chat/test.rs@@ -16,6 +16,8 @@ const CHAT_ID: &str = "3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90";const NEW_CHAT_ID: &str = "0197f776-6e7b-7c69-a251-780ae754d3e4";const PROJECT_ID: &str = "c1a2b3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d";const OWNER: &str = "macro|[email protected]";+const OTHER_USER: &str = "macro|[email protected]";+const TEAM_ID: uuid::Uuid = uuid::Uuid::from_u128(0x7ea3_0000_0000_0000_0000_0000_0000_0001);const MESSAGE_ID: &str = "message-id";const TOOL_CALL_ID: &str = "tool-call-id";const TOOL_NAME: &str = "test_tool";@@ -40,11 +42,16 @@ struct StubChatRepo {message_persistence: Arc<Mutex<MessagePersistence>>,team_default: Option<models_permissions::share_permission::TeamLinkShareDefault>,received_share_permission: Arc<Mutex<Option<SharePermissionV2>>>,+ /// Facts returned by `get_team_share_facts`; `None` uses the owner-with-team default.+ team_share_facts: Option<TeamShareFacts>,+ team_share_facts_loads: Arc<Mutex<usize>>,+ received_patch: Arc<Mutex<Option<PatchChatRepoArgs>>>,fail_create: bool,fail_copy_chat: bool,fail_delete: bool,fail_permanently_delete: bool,fail_patch: bool,+ fail_patch_with_conflict: bool,fail_revert_delete: bool,}@@ -56,6 +63,25 @@ impl StubChatRepo {}}+ fn with_team_share_facts(facts: TeamShareFacts) -> Self {+ Self {+ team_share_facts: Some(facts),+ ..Self::default()+ }+ }++ fn team_share_facts_loads(&self) -> usize {+ *self.team_share_facts_loads.lock().unwrap()+ }++ fn received_team_share(&self) -> Option<Option<AuthorizedTeamShareCommand>> {+ self.received_patch+ .lock()+ .unwrap()+ .as_ref()+ .map(|args| args.team_share.clone())+ }+fn with_tool_message() -> Self {Self {message_persistence: Arc::new(Mutex::new(MessagePersistence {@@ -154,6 +180,14 @@ impl ChatRepo for StubChatRepo {unimplemented!("not exercised")}+ async fn get_team_share_facts(&self, _chat_id: &str) -> Result<TeamShareFacts> {+ *self.team_share_facts_loads.lock().unwrap() += 1;+ Ok(self+ .team_share_facts+ .clone()+ .unwrap_or_else(|| team_share_facts(owner(), Some(TEAM_ID), 0)))+ }+async fn delete(&self, _chat_id: &str) -> Result<()> {if self.fail_delete {return Err(Self::repo_err());@@ -172,11 +206,15 @@ impl ChatRepo for StubChatRepo {&self,_user_id: MacroUserIdStr<'static>,_chat_id: &str,- _args: PatchChatArgs,+ args: PatchChatRepoArgs,) -> Result<()> {if self.fail_patch {return Err(Self::repo_err());}+ if self.fail_patch_with_conflict {+ return Err(ChatErr::Conflict("stale team-share facts".to_string()));+ }+ *self.received_patch.lock().unwrap() = Some(args);Ok(())}@@ -848,3 +886,201 @@ async fn broker_scheduling_failure_does_not_fail_the_call() {);assert!(service.revert_delete(owner_receipt(CHAT_ID)).await.is_ok());}++// -- Team sharing --++use models_permissions::share_permission::access_level::AccessLevel as ShareAccessLevel;+use models_permissions::share_permission::team_share::{+ AuthorizedTeamShareCommand, TeamShareFacts, TeamShareLevel,+};++fn user(id: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(id.to_string()).expect("valid user id")+}++fn team_share_facts(+ owner: MacroUserIdStr<'static>,+ owner_team_id: Option<uuid::Uuid>,+ revision: i64,+) -> TeamShareFacts {+ TeamShareFacts {+ entity: EntityType::Chat.with_entity_str(CHAT_ID),+ owner,+ owner_team_id,+ current: None,+ revision,+ }+}++fn team_share_args(level: Option<ShareAccessLevel>) -> PatchChatArgs {+ PatchChatArgs {+ name: None,+ project_id: None,+ share_permission: Some(+ models_permissions::share_permission::UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ team_share_access_level: Some(level),+ channel_share_permissions: None,+ },+ ),+ }+}++#[tokio::test]+async fn patch_without_team_share_field_does_not_load_facts_or_send_command() {+ let repo = StubChatRepo::default();+ let service = build_service(repo.clone(), RecordingEventBroker::default());++ service+ .patch(owner_receipt(CHAT_ID), patch_args(true))+ .await+ .unwrap();++ assert_eq!(repo.team_share_facts_loads(), 0);+ assert_eq!(repo.received_team_share(), Some(None));+}++#[tokio::test]+async fn patch_with_team_share_level_forwards_authorized_command() {+ let repo = StubChatRepo::default();+ let broker = RecordingEventBroker::default();+ let service = build_service(repo.clone(), broker.clone());++ service+ .patch(+ owner_receipt(CHAT_ID),+ team_share_args(Some(ShareAccessLevel::Edit)),+ )+ .await+ .unwrap();++ let command = repo+ .received_team_share()+ .flatten()+ .expect("repo receives an authorized command");+ assert_eq!(+ command.expected(),+ &team_share_facts(owner(), Some(TEAM_ID), 0)+ );+ let grant = command.target().expect("explicit level sets a grant");+ assert_eq!(grant.team_id, TEAM_ID);+ assert_eq!(grant.level, TeamShareLevel::Edit);+ assert_eq!(command.next_revision(), 1);+ let events = broker.events();+ assert_eq!(events.len(), 1);+ assert_eq!(+ events[0].envelope["metadata"]["share_permission_updated"],+ true+ );+}++#[tokio::test]+async fn patch_with_team_share_null_forwards_clear_command() {+ let repo = StubChatRepo::default();+ let service = build_service(repo.clone(), RecordingEventBroker::default());++ service+ .patch(owner_receipt(CHAT_ID), team_share_args(None))+ .await+ .unwrap();++ let command = repo+ .received_team_share()+ .flatten()+ .expect("clearing still produces a command");+ assert!(command.target().is_none());+ assert_eq!(command.next_revision(), 1);+}++#[tokio::test]+async fn patch_team_share_by_non_owner_returns_unauthorized_and_publishes_nothing() {+ // The receipt carries effective Owner access, but the persisted owner is someone else.+ let repo =+ StubChatRepo::with_team_share_facts(team_share_facts(user(OTHER_USER), Some(TEAM_ID), 0));+ let broker = RecordingEventBroker::default();+ let service = build_service(repo.clone(), broker.clone());++ let result = service+ .patch(+ owner_receipt(CHAT_ID),+ team_share_args(Some(ShareAccessLevel::View)),+ )+ .await;++ assert!(matches!(+ result,+ Err(ChatErr::Access(AccessError::Unauthorized))+ ));+ assert_eq!(repo.received_team_share(), None, "repo patch must not run");+ assert!(broker.events().is_empty());+}++#[tokio::test]+async fn patch_team_share_owner_level_returns_bad_request() {+ let repo = StubChatRepo::default();+ let service = build_service(repo.clone(), RecordingEventBroker::default());++ let result = service+ .patch(+ owner_receipt(CHAT_ID),+ team_share_args(Some(ShareAccessLevel::Owner)),+ )+ .await;++ assert!(matches!(result, Err(ChatErr::BadRequest(_))));+ assert_eq!(repo.received_team_share(), None);+}++#[tokio::test]+async fn patch_team_share_without_owner_team_returns_bad_request() {+ let repo = StubChatRepo::with_team_share_facts(team_share_facts(owner(), None, 0));+ let service = build_service(repo.clone(), RecordingEventBroker::default());++ let result = service+ .patch(+ owner_receipt(CHAT_ID),+ team_share_args(Some(ShareAccessLevel::Edit)),+ )+ .await;++ assert!(matches!(result, Err(ChatErr::BadRequest(_))));+ assert_eq!(repo.received_team_share(), None);+}++#[tokio::test]+async fn patch_team_share_exhausted_revision_returns_conflict() {+ let repo =+ StubChatRepo::with_team_share_facts(team_share_facts(owner(), Some(TEAM_ID), i64::MAX));+ let service = build_service(repo.clone(), RecordingEventBroker::default());++ let result = service+ .patch(+ owner_receipt(CHAT_ID),+ team_share_args(Some(ShareAccessLevel::Edit)),+ )+ .await;++ assert!(matches!(result, Err(ChatErr::Conflict(_))));+ assert_eq!(repo.received_team_share(), None);+}++#[tokio::test]+async fn patch_repo_conflict_does_not_publish_event() {+ let repo = StubChatRepo {+ fail_patch_with_conflict: true,+ ..StubChatRepo::default()+ };+ let broker = RecordingEventBroker::default();+ let service = build_service(repo, broker.clone());++ let result = service+ .patch(+ owner_receipt(CHAT_ID),+ team_share_args(Some(ShareAccessLevel::Edit)),+ )+ .await;++ assert!(matches!(result, Err(ChatErr::Conflict(_))));+ assert!(broker.events().is_empty());+}diff --git a/crates/chat/src/domain/service/entity_mutation.rs b/crates/chat/src/domain/service/entity_mutation.rsindex 11142c5cc6..6b55995e81 100644--- a/crates/chat/src/domain/service/entity_mutation.rs+++ b/crates/chat/src/domain/service/entity_mutation.rs@@ -26,6 +26,7 @@ impl From<ChatErr> for EntityMutationErrorCode {match error {error @ ChatErr::NotFound => Self::not_found(rootcause::report!(error)),error @ ChatErr::BadRequest(_) => Self::invalid(rootcause::report!(error)),+ error @ ChatErr::Conflict(_) => Self::conflict(rootcause::report!(error)),ChatErr::Access(error) => access_error(error),error @ ChatErr::Unknown(_) => Self::internal(rootcause::report!(error)),}diff --git a/crates/chat/src/inbound/error_response.rs b/crates/chat/src/inbound/error_response.rsindex 52dc047244..ae0b2b49fb 100644--- a/crates/chat/src/inbound/error_response.rs+++ b/crates/chat/src/inbound/error_response.rs@@ -2,6 +2,9 @@//!//! Lives in inbound so the domain error type stays transport-free.+#[cfg(test)]+mod test;+use axum::http::StatusCode;use axum::response::{IntoResponse, Response};use entity_access::domain::models::AccessError;@@ -13,6 +16,7 @@ impl IntoResponse for ChatErr {let (status, msg) = match &self {ChatErr::NotFound => (StatusCode::NOT_FOUND, "Not found"),ChatErr::BadRequest(_) => (StatusCode::BAD_REQUEST, "Bad request"),+ ChatErr::Conflict(_) => (StatusCode::CONFLICT, "Conflict"),ChatErr::Access(AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),) => (StatusCode::FORBIDDEN, "Forbidden"),diff --git a/crates/chat/src/inbound/error_response/test.rs b/crates/chat/src/inbound/error_response/test.rsnew file mode 100644index 0000000000..11a9c9940f--- /dev/null+++ b/crates/chat/src/inbound/error_response/test.rs@@ -0,0 +1,25 @@+use super::*;++#[test]+fn maps_domain_errors_to_status_codes() {+ let cases = [+ (ChatErr::NotFound, StatusCode::NOT_FOUND),+ (+ ChatErr::BadRequest("bad".to_string()),+ StatusCode::BAD_REQUEST,+ ),+ (ChatErr::Conflict("stale".to_string()), StatusCode::CONFLICT),+ (+ ChatErr::Access(AccessError::Unauthorized),+ StatusCode::FORBIDDEN,+ ),+ (+ ChatErr::Unknown(anyhow::anyhow!("boom")),+ StatusCode::INTERNAL_SERVER_ERROR,+ ),+ ];++ for (error, status) in cases {+ assert_eq!(error.into_response().status(), status);+ }+}diff --git a/crates/chat/src/outbound/postgres.rs b/crates/chat/src/outbound/postgres.rsindex 613c76a344..a8ba3ed2ea 100644--- a/crates/chat/src/outbound/postgres.rs+++ b/crates/chat/src/outbound/postgres.rs@@ -1,11 +1,12 @@//! Postgres-backed [`ChatRepo`] implementation.mod queries;+mod team_share;#[cfg(test)]mod test;use crate::domain::models::{- ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, PatchChatArgs, PatchChatMessageArgs,+ ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, PatchChatMessageArgs, PatchChatRepoArgs,Result, WebCitation,};use crate::domain::ports::{ChatRepo, MessageRepo};@@ -16,6 +17,7 @@ use macro_user_id::user_id::MacroUserIdStr;use model::chat::ChatMessageWithAttachments;use model::chat::NewChatMessage;use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::team_share::TeamShareFacts;use models_permissions::share_permission::{SharePermissionV2, TeamLinkShareDefault};use sqlx::PgPool;@@ -285,6 +287,11 @@ impl ChatRepo for PgChatRepo {.map_err(to_chat_err)}+ #[tracing::instrument(err, skip(self))]+ async fn get_team_share_facts(&self, chat_id: &str) -> Result<TeamShareFacts> {+ team_share::get_team_share_facts(&self.pool, chat_id).await+ }+#[tracing::instrument(err, skip(self))]async fn delete(&self, chat_id: &str) -> Result<()> {let mut tx = self@@ -313,12 +320,12 @@ impl ChatRepo for PgChatRepo {Ok(())}- #[tracing::instrument(err, skip(self))]+ #[tracing::instrument(err, skip(self, args))]async fn patch(&self,user_id: MacroUserIdStr<'static>,chat_id: &str,- args: PatchChatArgs,+ args: PatchChatRepoArgs,) -> Result<()> {let mut tx = self.pool@@ -326,6 +333,16 @@ impl ChatRepo for PgChatRepo {.await.map_err(|e| ChatErr::Unknown(e.into()))?;+ // Canonical team sharing first: it takes the shared guard before any+ // `SharePermission` row lock and refuses an unauthorized team level.+ team_share::apply_team_share(+ &mut tx,+ chat_id,+ args.share_permission.as_ref(),+ args.team_share.as_ref(),+ )+ .await?;+queries::patch_chat::patch_chat(&mut tx,chat_id,diff --git a/crates/chat/src/outbound/postgres/fixtures/team.sql b/crates/chat/src/outbound/postgres/fixtures/team.sqlnew file mode 100644index 0000000000..188557ce9e--- /dev/null+++ b/crates/chat/src/outbound/postgres/fixtures/team.sql@@ -0,0 +1,5 @@+INSERT INTO public.team ("id", "name", "owner_id", "seat_count")+VALUES ('b2222222-2222-2222-2222-222222222222', 'Test Team', 'macro|[email protected]', 2);++INSERT INTO public.team_user ("team_id", "user_id", "team_role")+VALUES ('b2222222-2222-2222-2222-222222222222', 'macro|[email protected]', 'owner');diff --git a/crates/chat/src/outbound/postgres/queries/get_permissions.rs b/crates/chat/src/outbound/postgres/queries/get_permissions.rsindex c21c4b80ac..3a05af092d 100644--- a/crates/chat/src/outbound/postgres/queries/get_permissions.rs+++ b/crates/chat/src/outbound/postgres/queries/get_permissions.rs@@ -17,6 +17,7 @@ pub(crate) async fn get_chat_share_permission(sp.id as id,sp."linkShare" as "link_share?",sp."linkShareAccessLevel" as "link_share_access_level?: AccessLevel",+ sp.team_share_access_level as "team_share_access_level?: AccessLevel",c."userId" as owner,COALESCE(json_agg(json_build_object(@@ -61,7 +62,7 @@ pub(crate) async fn get_chat_share_permission(id: result.id,link_share,link_share_access_level: result.link_share_access_level,- team_share_access_level: None,+ team_share_access_level: result.team_share_access_level,owner: result.owner,channel_share_permissions,})diff --git a/crates/chat/src/outbound/postgres/team_share.rs b/crates/chat/src/outbound/postgres/team_share.rsnew file mode 100644index 0000000000..7d383fb35e--- /dev/null+++ b/crates/chat/src/outbound/postgres/team_share.rs@@ -0,0 +1,95 @@+//! Canonical team-share persistence for chats.+//!+//! Chats reuse the shared `SharePermission.team_share_*` state and the+//! `entity_access` team grant managed by `share_permission_db_utils`; this+//! module only adapts those helpers to the chat repository's error type.++#[cfg(test)]+mod test;++use entity_access::domain::models::AccessError;+use model_entity::{Entity, EntityType};+use models_permissions::share_permission::UpdateSharePermissionRequestV2;+use models_permissions::share_permission::team_share::{+ AuthorizedTeamShareCommand, TeamShareFacts,+};+use share_permission_db_utils::team_share::{self, TeamShareError};+use sqlx::{PgPool, Postgres, Transaction};++use crate::domain::models::ChatErr;++/// Map a canonical team-share failure onto the chat domain error.+///+/// Stale or unexplained state surfaces as a conflict so the owner can reload+/// and retry instead of receiving a 500.+pub(super) fn map_team_share_error(error: rootcause::Report<TeamShareError>) -> ChatErr {+ match error.current_context() {+ TeamShareError::NotFound => ChatErr::NotFound,+ TeamShareError::ChangedFacts | TeamShareError::UntrackedGrant => {+ ChatErr::Conflict(error.to_string())+ }+ TeamShareError::InvalidAdoption+ | TeamShareError::InvalidEntity+ | TeamShareError::InvalidState+ | TeamShareError::Infrastructure => ChatErr::Unknown(error.into()),+ }+}++fn chat_entity(chat_id: &str) -> Entity<'_> {+ EntityType::Chat.with_entity_str(chat_id)+}++/// Read the authoritative facts in one guarded snapshot without writing anything.+///+/// Chats never had a pre-canonical team grant, so unlike documents there is no+/// legacy adoption step here.+#[tracing::instrument(err, skip(pool))]+pub(super) async fn get_team_share_facts(+ pool: &PgPool,+ chat_id: &str,+) -> Result<TeamShareFacts, ChatErr> {+ let mut transaction = pool.begin().await.map_err(|e| ChatErr::Unknown(e.into()))?;+ let facts = team_share::load_facts(&mut transaction, &chat_entity(chat_id))+ .await+ .map_err(map_team_share_error)?;+ transaction+ .commit()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+ Ok(facts)+}++/// Apply the owner-authorized team-share command inside the patch transaction,+/// or refuse a requested team level that arrived without one.+///+/// The command must target this chat and request exactly the level carried by+/// the share-permission patch; anything else is a malformed edit. Callers run+/// this before other `SharePermission` writes so the shared guard is acquired+/// before any row locks, matching the document repository.+#[tracing::instrument(err, skip(transaction, share_permission, team_share))]+pub(super) async fn apply_team_share(+ transaction: &mut Transaction<'_, Postgres>,+ chat_id: &str,+ share_permission: Option<&UpdateSharePermissionRequestV2>,+ team_share: Option<&AuthorizedTeamShareCommand>,+) -> Result<(), ChatErr> {+ let requested_level = share_permission.and_then(|p| p.team_share_access_level);+ match team_share {+ Some(command) => {+ let expected = &command.expected().entity;+ if expected.entity_type != EntityType::Chat+ || expected.entity_id != chat_id+ || requested_level != Some(command.target().map(|grant| grant.level.into()))+ {+ return Err(ChatErr::BadRequest(+ "team-share command does not match patch".to_string(),+ ));+ }+ team_share::apply(transaction, command)+ .await+ .map_err(map_team_share_error)+ }+ None if requested_level.is_some() => Err(ChatErr::Access(AccessError::Unauthorized)),+ None => Ok(()),+ }+}diff --git a/crates/chat/src/outbound/postgres/team_share/test.rs b/crates/chat/src/outbound/postgres/team_share/test.rsnew file mode 100644index 0000000000..3a6e2fd622--- /dev/null+++ b/crates/chat/src/outbound/postgres/team_share/test.rs@@ -0,0 +1,404 @@+use entity_access::domain::models::AccessError;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::team_share::{+ AuthorizedTeamShareCommand, TeamShareFacts, TeamShareLevel, TeamShareRequest,+ authorize_team_share,+};+use models_permissions::share_permission::{+ LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,+};+use sqlx::{PgPool, Pool, Postgres};+use uuid::Uuid;++use crate::domain::models::{ChatErr, CreateChatArgs, PatchChatRepoArgs};+use crate::domain::ports::ChatRepo;+use crate::outbound::postgres::PgChatRepo;++const OWNER: &str = "macro|[email protected]";+const TEAM_ID: Uuid = Uuid::from_u128(0xb2222222_2222_2222_2222_222222222222);++fn owner() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(OWNER).unwrap().into_owned()+}++async fn create_chat(repo: &PgChatRepo, name: &str) -> String {+ repo.create(+ owner(),+ CreateChatArgs {+ name: name.to_string(),+ project_id: None,+ },+ SharePermissionV2::new_chat_share_permission(None),+ )+ .await+ .unwrap()+}++fn team_share_request(level: Option<AccessLevel>) -> UpdateSharePermissionRequestV2 {+ UpdateSharePermissionRequestV2 {+ link_share: None,+ link_share_access_level: None,+ team_share_access_level: Some(level),+ channel_share_permissions: None,+ }+}++/// Authorize `level` exactly as the domain service would for the persisted owner.+fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeamShareCommand {+ authorize_team_share(+ Some(&facts.owner),+ facts,+ TeamShareRequest {+ access_level: Some(level),+ legacy_enabled: None,+ },+ TeamShareLevel::Edit,+ )+ .unwrap()+ .unwrap()+}++async fn patch_team_share(+ repo: &PgChatRepo,+ chat_id: &str,+ level: Option<AccessLevel>,+) -> Result<(), ChatErr> {+ let facts = repo.get_team_share_facts(chat_id).await?;+ repo.patch(+ owner(),+ chat_id,+ PatchChatRepoArgs {+ name: None,+ project_id: None,+ share_permission: Some(team_share_request(level)),+ team_share: Some(command(&facts, level)),+ },+ )+ .await+}++#[derive(Debug, PartialEq, Eq)]+struct StoredTeamShare {+ level: Option<String>,+ team_id: Option<Uuid>,+ revision: i64,+}++async fn stored_team_share(pool: &Pool<Postgres>, chat_id: &str) -> StoredTeamShare {+ let row = sqlx::query!(+ r#"+ SELECT+ sp.team_share_access_level::text AS "level?",+ sp.team_share_team_id AS "team_id?",+ sp.team_share_revision AS revision+ FROM "ChatPermission" cp+ JOIN "SharePermission" sp ON cp."sharePermissionId" = sp.id+ WHERE cp."chatId" = $1+ "#,+ chat_id,+ )+ .fetch_one(pool)+ .await+ .unwrap();+ StoredTeamShare {+ level: row.level,+ team_id: row.team_id,+ revision: row.revision,+ }+}++async fn direct_team_rows(pool: &Pool<Postgres>, chat_id: &str) -> Vec<AccessLevel> {+ sqlx::query_scalar!(+ r#"+ SELECT access_level AS "access_level: AccessLevel"+ FROM entity_access+ WHERE entity_id = $1 AND entity_type = 'chat' AND source_type = 'team'+ AND granted_from_project_id IS NULL+ ORDER BY access_level+ "#,+ Uuid::parse_str(chat_id).unwrap(),+ )+ .fetch_all(pool)+ .await+ .unwrap()+}++fn unshared() -> StoredTeamShare {+ StoredTeamShare {+ level: None,+ team_id: None,+ revision: 0,+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn get_team_share_facts_reads_owner_team_and_null_state(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Facts").await;++ let facts = repo.get_team_share_facts(&chat_id).await.unwrap();++ assert_eq!(facts.entity.entity_type, EntityType::Chat);+ assert_eq!(facts.entity.entity_id, chat_id);+ assert_eq!(facts.owner, owner());+ assert_eq!(facts.owner_team_id, Some(TEAM_ID));+ assert_eq!(facts.current, None);+ assert_eq!(facts.revision, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users"))+)]+async fn get_team_share_facts_without_team_has_no_owner_team(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "No team").await;++ let facts = repo.get_team_share_facts(&chat_id).await.unwrap();++ assert_eq!(facts.owner_team_id, None);+ assert_eq!(facts.current, None);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn patch_applies_team_share_command_and_inserts_direct_team_entity_access(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Shared").await;++ patch_team_share(&repo, &chat_id, Some(AccessLevel::Edit))+ .await+ .unwrap();+ assert_eq!(+ stored_team_share(&pool, &chat_id).await,+ StoredTeamShare {+ level: Some("edit".to_string()),+ team_id: Some(TEAM_ID),+ revision: 1,+ }+ );+ assert_eq!(direct_team_rows(&pool, &chat_id).await, [AccessLevel::Edit]);++ // A downgrade replaces the managed grant instead of adding a second row.+ patch_team_share(&repo, &chat_id, Some(AccessLevel::View))+ .await+ .unwrap();+ assert_eq!(+ stored_team_share(&pool, &chat_id).await,+ StoredTeamShare {+ level: Some("view".to_string()),+ team_id: Some(TEAM_ID),+ revision: 2,+ }+ );+ assert_eq!(direct_team_rows(&pool, &chat_id).await, [AccessLevel::View]);++ let facts = repo.get_team_share_facts(&chat_id).await.unwrap();+ assert_eq!(+ facts.current.map(|grant| (grant.team_id, grant.level)),+ Some((TEAM_ID, TeamShareLevel::View))+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn patch_clear_command_removes_managed_team_entity_access_and_bumps_revision(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Cleared").await;+ patch_team_share(&repo, &chat_id, Some(AccessLevel::Comment))+ .await+ .unwrap();++ patch_team_share(&repo, &chat_id, None).await.unwrap();++ assert_eq!(+ stored_team_share(&pool, &chat_id).await,+ StoredTeamShare {+ level: None,+ team_id: None,+ revision: 2,+ }+ );+ assert!(direct_team_rows(&pool, &chat_id).await.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn patch_with_team_level_but_no_command_returns_unauthorized(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Original").await;++ let result = repo+ .patch(+ owner(),+ &chat_id,+ PatchChatRepoArgs {+ name: Some("Renamed".to_string()),+ project_id: None,+ share_permission: Some(team_share_request(Some(AccessLevel::Edit))),+ team_share: None,+ },+ )+ .await;++ assert!(matches!(+ result,+ Err(ChatErr::Access(AccessError::Unauthorized))+ ));+ assert_eq!(stored_team_share(&pool, &chat_id).await, unshared());+ assert!(direct_team_rows(&pool, &chat_id).await.is_empty());+ // The whole patch is rolled back, not just the team share.+ assert_eq!(repo.get_metadata(&chat_id).await.unwrap().name, "Original");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn patch_rejects_command_for_other_chat_or_mismatched_level(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Target").await;+ let other_chat_id = create_chat(&repo, "Other").await;+ let facts = repo.get_team_share_facts(&chat_id).await.unwrap();+ let other_facts = repo.get_team_share_facts(&other_chat_id).await.unwrap();++ let wrong_chat = repo+ .patch(+ owner(),+ &chat_id,+ PatchChatRepoArgs {+ name: None,+ project_id: None,+ share_permission: Some(team_share_request(Some(AccessLevel::Edit))),+ team_share: Some(command(&other_facts, Some(AccessLevel::Edit))),+ },+ )+ .await;+ assert!(matches!(wrong_chat, Err(ChatErr::BadRequest(_))));++ let wrong_level = repo+ .patch(+ owner(),+ &chat_id,+ PatchChatRepoArgs {+ name: None,+ project_id: None,+ share_permission: Some(team_share_request(Some(AccessLevel::View))),+ team_share: Some(command(&facts, Some(AccessLevel::Edit))),+ },+ )+ .await;+ assert!(matches!(wrong_level, Err(ChatErr::BadRequest(_))));++ assert_eq!(stored_team_share(&pool, &chat_id).await, unshared());+ assert_eq!(stored_team_share(&pool, &other_chat_id).await, unshared());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn patch_stale_command_returns_conflict(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Stale").await;+ let facts = repo.get_team_share_facts(&chat_id).await.unwrap();+ let stale = command(&facts, Some(AccessLevel::Edit));++ patch_team_share(&repo, &chat_id, Some(AccessLevel::Edit))+ .await+ .unwrap();++ let replay = repo+ .patch(+ owner(),+ &chat_id,+ PatchChatRepoArgs {+ name: None,+ project_id: None,+ share_permission: Some(team_share_request(Some(AccessLevel::Edit))),+ team_share: Some(stale),+ },+ )+ .await;++ assert!(matches!(replay, Err(ChatErr::Conflict(_))));+ assert_eq!(stored_team_share(&pool, &chat_id).await.revision, 1);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn patch_team_share_and_link_share_in_one_call_persists_both(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Both").await;+ let facts = repo.get_team_share_facts(&chat_id).await.unwrap();++ repo.patch(+ owner(),+ &chat_id,+ PatchChatRepoArgs {+ name: Some("Renamed".to_string()),+ project_id: None,+ share_permission: Some(UpdateSharePermissionRequestV2 {+ link_share: Some(Some(LinkShare::Team)),+ link_share_access_level: Some(Some(AccessLevel::Comment)),+ team_share_access_level: Some(Some(AccessLevel::Edit)),+ channel_share_permissions: None,+ }),+ team_share: Some(command(&facts, Some(AccessLevel::Edit))),+ },+ )+ .await+ .unwrap();++ let permission = repo.get_permissions(&chat_id).await.unwrap();+ assert_eq!(permission.link_share, Some(LinkShare::Team));+ assert_eq!(+ permission.link_share_access_level,+ Some(AccessLevel::Comment)+ );+ assert_eq!(permission.team_share_access_level, Some(AccessLevel::Edit));+ assert_eq!(repo.get_metadata(&chat_id).await.unwrap().name, "Renamed");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../fixtures", scripts("users", "team"))+)]+async fn get_permissions_reads_team_share_access_level(pool: PgPool) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_chat(&repo, "Read").await;+ assert_eq!(+ repo.get_permissions(&chat_id)+ .await+ .unwrap()+ .team_share_access_level,+ None+ );++ patch_team_share(&repo, &chat_id, Some(AccessLevel::Comment))+ .await+ .unwrap();++ assert_eq!(+ repo.get_permissions(&chat_id)+ .await+ .unwrap()+ .team_share_access_level,+ Some(AccessLevel::Comment)+ );+}diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rsindex 1ffb3cbe2b..0b7aa88431 100644--- a/crates/chat/src/outbound/postgres/test.rs+++ b/crates/chat/src/outbound/postgres/test.rs@@ -14,7 +14,7 @@ use sqlx::postgres::PgRow;use sqlx::{Pool, Postgres, Row};use super::PgChatRepo;-use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatArgs};+use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatRepoArgs};use crate::domain::ports::ChatRepo;/// The no-team default permission for a chat — the repo persists whatever the@@ -84,10 +84,11 @@ async fn patch_share_permission(repo.patch(user_id,chat_id,- PatchChatArgs {+ PatchChatRepoArgs {name: None,project_id: None,share_permission: Some(share_permission),+ team_share: None,},).await@@ -922,10 +923,11 @@ async fn patch_chat_updates_name(pool: Pool<Postgres>) {repo.patch(patch_user_id,&chat_id,- PatchChatArgs {+ PatchChatRepoArgs {name: Some("Renamed".to_string()),project_id: None,share_permission: None,+ team_share: None,},).await@@ -963,10 +965,11 @@ async fn patch_chat_updates_project(pool: Pool<Postgres>) {repo.patch(patch_user_id,&chat_id,- PatchChatArgs {+ PatchChatRepoArgs {name: None,project_id: Some("project-123".to_string()),share_permission: None,+ team_share: None,},).await@@ -1012,10 +1015,11 @@ async fn patch_chat_clears_project(pool: Pool<Postgres>) {repo.patch(patch_user_id,&chat_id,- PatchChatArgs {+ PatchChatRepoArgs {name: None,project_id: Some("".to_string()),share_permission: None,+ team_share: None,},).awaitdiff --git a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rs b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rsindex 566e0dcc91..7b5be0bd4b 100644--- a/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rs+++ b/crates/entity_access/src/outbound/pg_access_repo/queries/chat_access/test.rs@@ -160,6 +160,34 @@ async fn insert_explicit_access(Ok(())}+/// A canonical team share: the grant `share_permission_db_utils::team_share`+/// writes for the owner's team.+async fn insert_team_access(+ pool: &PgPool,+ chat_id: Uuid,+ team_id: Uuid,+ access_level: AccessLevel,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO entity_access (+ entity_id,+ entity_type,+ source_id,+ source_type,+ access_level+ )+ VALUES ($1, 'chat', $2, 'team', $3)+ "#,+ chat_id,+ team_id.to_string(),+ access_level as AccessLevel,+ )+ .execute(pool)+ .await?;+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn enforces_complete_link_access_matrix(pool: PgPool) -> anyhow::Result<()> {insert_user(&pool, OWNER_WITH_TEAM).await?;@@ -236,3 +264,46 @@ async fn takes_maximum_of_link_and_explicit_access(pool: PgPool) -> anyhow::Resu);Ok(())}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn explicit_team_grant_allows_team_members_only(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;+ let chat_id = insert_chat(&pool, OWNER_WITH_TEAM, None, None).await?;+ insert_team_access(&pool, chat_id, OWNER_TEAM, AccessLevel::Comment).await?;++ let anonymous = SourceIds(vec![]);+ let other_team = SourceIds(vec![REQUESTER.to_string(), OTHER_TEAM.to_string()]);+ let same_team = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ assert_eq!(get_chat_access(&pool, &chat_id, &anonymous).await?, None);+ assert_eq!(get_chat_access(&pool, &chat_id, &other_team).await?, None);+ assert_eq!(+ get_chat_access(&pool, &chat_id, &same_team).await?,+ Some(AccessLevel::Comment)+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn takes_maximum_of_explicit_team_grant_and_link(pool: PgPool) -> anyhow::Result<()> {+ insert_user(&pool, OWNER_WITH_TEAM).await?;+ add_owner_to_team(&pool, OWNER_WITH_TEAM, OWNER_TEAM).await?;+ let same_team = SourceIds(vec![REQUESTER.to_string(), OWNER_TEAM.to_string()]);++ let team_grant_wins = insert_chat(&pool, OWNER_WITH_TEAM, Some("PUBLIC"), Some("view")).await?;+ insert_team_access(&pool, team_grant_wins, OWNER_TEAM, AccessLevel::Edit).await?;++ let link_wins = insert_chat(&pool, OWNER_WITH_TEAM, Some("TEAM"), Some("edit")).await?;+ insert_team_access(&pool, link_wins, OWNER_TEAM, AccessLevel::View).await?;++ assert_eq!(+ get_chat_access(&pool, &team_grant_wins, &same_team).await?,+ Some(AccessLevel::Edit)+ );+ assert_eq!(+ get_chat_access(&pool, &link_wins, &same_team).await?,+ Some(AccessLevel::Edit)+ );+ Ok(())+}diff --git a/crates/share_permission_db_utils/src/team_share/test.rs b/crates/share_permission_db_utils/src/team_share/test.rsindex 7f266a40c8..1d7f3d51f7 100644--- a/crates/share_permission_db_utils/src/team_share/test.rs+++ b/crates/share_permission_db_utils/src/team_share/test.rs@@ -11,6 +11,10 @@ fn initiative() -> Entity<'static> {EntityType::Initiative.with_entity_string("20000000-0000-0000-0000-000000000007".to_string())}+fn chat() -> Entity<'static> {+ EntityType::Chat.with_entity_string("20000000-0000-0000-0000-000000000003".to_string())+}+fn command(facts: &TeamShareFacts, level: Option<AccessLevel>) -> AuthorizedTeamShareCommand {authorize_team_share(Some(&facts.owner),@@ -123,6 +127,17 @@ async fn apply_inserts_updates_and_deletes_direct_team_entity_access_for_initiatapply_comment_view_and_clear(&mut tx, &initiative()).await}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("team_share"))+)]+async fn apply_inserts_updates_and_deletes_direct_team_entity_access_for_chat(+ pool: PgPool,+) -> rootcause::Result<()> {+ let mut tx = pool.begin().await?;+ apply_comment_view_and_clear(&mut tx, &chat()).await+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("team_share"))diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex aa88ab6b11..72638f58a0 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -113,6 +113,24 @@ Leaving Macro selected uses the backend's in-memory default in everyenvironment, including production; it does not provision a Daytona container.Explicit coding-agent selections still use their configured runtimes.+## Sharing a chat++A standalone chat (`/app/chat/<uuid>`) has **Share** and **Copy Share Link** in+the desktop header; the same **Share** action is on entity list menus and the+entity sharing shortcut. It opens the same Share dialog (mobile: drawer) as+documents:++- People/channels: pick recipients and an access level and send the chat with+ an optional message.+- Link sharing: None / Public / Team link plus an access level.+- **Team access** (owner only, and only when the owner belongs to a team): a+ dropdown with None / View / Comment / Edit that shares the chat directly with+ the owner's whole team. Teammates then open the chat with that level and see+ it under Shared; setting it back to None revokes that access. This is+ independent of the team-scoped link control. Only the chat's actual owner can+ change it; someone with inherited owner access gets a "Failed to change team+ access" toast.+## Start a doc-scoped chatOpen a doc → side panel `Actions` → `Ask Macro`. Opens a chat pane with the document alreadydiff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex d96faa7a36..cbbc6539c0 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -157,9 +157,9 @@ Right side of a doc (toggle with `Hide/Show Side Panel`):oldest fetched entry (usually `created this`) pinned last; the toggle flips to `Show less`once expanded.- Header: `Share`, `Copy Share Link`, overflow menu — use `Share` to inspect or change the- doc's visibility/permissions. Documents also have a `Team access` dropdown (None / View /- Comment / Edit) for sharing directly with the owner's team. That is independent of the- team-scoped link control.+ doc's visibility/permissions. Documents and AI chats also have a `Team access` dropdown+ (None / View / Comment / Edit) for sharing directly with the owner's team. That is+ independent of the team-scoped link control.## Known failure: "expected instance of LoroDoc"diff --git a/services/document_cognition_service/src/service/chat_renamer.rs b/services/document_cognition_service/src/service/chat_renamer.rsindex 21f8d5d4ec..caffa87bf4 100644--- a/services/document_cognition_service/src/service/chat_renamer.rs+++ b/services/document_cognition_service/src/service/chat_renamer.rs@@ -1,6 +1,6 @@use crate::api::context::ApiContext;use agent::PredefinedModel;-use chat::domain::models::PatchChatArgs;+use chat::domain::models::PatchChatRepoArgs;use chat::domain::ports::ChatRepo;use chat::outbound::postgres::PgChatRepo;use macro_user_id::user_id::MacroUserIdStr;@@ -71,10 +71,11 @@ async fn rename_initial_chat(.patch(user_id,&chat_id,- PatchChatArgs {+ PatchChatRepoArgs {name: Some(name.clone()),project_id: None,share_permission: None,+ team_share: None,},).await