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(web): make item menus consistent across entity types (#8944)
Jacob Beckerman8bafc99299a9
diff --git a/.sqlx/query-732a799c309c5112b4684aaa7f9424f78cd13b425b36ce02335269f3c6cddda9.json b/.sqlx/query-732a799c309c5112b4684aaa7f9424f78cd13b425b36ce02335269f3c6cddda9.jsonnew file mode 100644index 0000000000..d7affd7e24--- /dev/null+++ b/.sqlx/query-732a799c309c5112b4684aaa7f9424f78cd13b425b36ce02335269f3c6cddda9.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, name, \"projectId\" AS \"project_id!\"\n FROM \"Document\"\n WHERE \"projectId\" = ANY($1) AND \"deletedAt\" IS NULL\n LIMIT $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "project_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "732a799c309c5112b4684aaa7f9424f78cd13b425b36ce02335269f3c6cddda9"+}diff --git a/.sqlx/query-82cde1a52131de67f885a23bd1205c84d240e94a1308347c61f1f17fd053f149.json b/.sqlx/query-82cde1a52131de67f885a23bd1205c84d240e94a1308347c61f1f17fd053f149.jsonnew file mode 100644index 0000000000..cc0239c41d--- /dev/null+++ b/.sqlx/query-82cde1a52131de67f885a23bd1205c84d240e94a1308347c61f1f17fd053f149.json@@ -0,0 +1,35 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, name, \"projectId\" AS \"project_id!\"\n FROM \"Chat\"\n WHERE \"projectId\" = ANY($1) AND \"deletedAt\" IS NULL\n LIMIT $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "project_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "82cde1a52131de67f885a23bd1205c84d240e94a1308347c61f1f17fd053f149"+}diff --git a/.sqlx/query-aa1a119e12755e3a4f1c97699e1df7316ba8dc6f8f602a100d1f49f4aabc18d8.json b/.sqlx/query-aa1a119e12755e3a4f1c97699e1df7316ba8dc6f8f602a100d1f49f4aabc18d8.jsonnew file mode 100644index 0000000000..ce7af8d3b0--- /dev/null+++ b/.sqlx/query-aa1a119e12755e3a4f1c97699e1df7316ba8dc6f8f602a100d1f49f4aabc18d8.json@@ -0,0 +1,41 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE folders AS (\n SELECT child.id, child.\"parentId\" AS parent_id, child.name, 1 AS depth\n FROM \"Project\" child\n WHERE child.\"parentId\" = $1 AND child.\"deletedAt\" IS NULL\n UNION ALL\n SELECT child.id, child.\"parentId\", child.name, folders.depth + 1\n FROM \"Project\" child\n JOIN folders ON child.\"parentId\" = folders.id\n WHERE child.\"deletedAt\" IS NULL\n )\n SELECT\n id AS \"id!\",\n parent_id AS \"parent_id!\",\n name AS \"name!\",\n depth AS \"depth!\"\n FROM folders\n LIMIT $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "parent_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "depth!",+ "type_info": "Int4"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null+ ]+ },+ "hash": "aa1a119e12755e3a4f1c97699e1df7316ba8dc6f8f602a100d1f49f4aabc18d8"+}diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 448e2226c5..ed53bd518e 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -587,7 +587,10 @@ instance proxy retains `/cognition`, `/scheduled-action`, and `/preview`.Channel videos, linked video previews, and Drive video/image/code/canvas/unknown previews share`createFileDownload` and `FileDownloadButton`. Keep menu and visible controls-bound to the same controller. Download hands off directly to browser downloads+bound to the same controller. Call recording menus and the list-row Download+(`makeDownloadAction`) use the same controller; the list action runs it under+its own root, because choosing a context-menu item disposes the menu's owner.+Download hands off directly to browser downloadsor the native save picker. Show channel Download on hover or keyboard focus,always on touch, without a footer. Keep system Share inside the touch Downloadmenu; desktop Share belongs to Macro permissions. Do not add a customdiff --git a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsxindex b2cd8db8cf..fb9076edf2 100644--- a/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx+++ b/apps/web/src/components/app/split-layout/components/SplitFileMenu.tsx@@ -18,6 +18,7 @@ import {type BlockName,useBlockAliasedName,} from '@core/block';+import { canDuplicateItemType } from '@core/component/FileList/itemOperations';import { useItemOperations } from '@core/component/FileList/useItemOperations';import { Permissions } from '@core/component/SharePermissions';import { toast } from '@core/component/Toast/Toast';@@ -37,6 +38,7 @@ import BellSlash from '@icon/system/regular/bell-slash.svg';import CaretDown from '@icon/system/regular/caret-down.svg';import CaretRight from '@icon/system/regular/caret-right.svg';import Check from '@icon/system/regular/check.svg';+import Clock from '@icon/system/regular/clock.svg';import Copy from '@icon/system/regular/copy.svg';import DotsThree from '@icon/system/regular/dots-three.svg';import Link from '@icon/system/regular/link.svg';@@ -429,6 +431,20 @@ export function SplitFileMenu(props: SplitFileMenuProps) {};};+ const snoozeOp = (): SplitFileMenuAction | undefined => {+ const entity = menuEntity();+ if (!entity || !muteAction.canExecute(entity)) return undefined;+ return {+ label: t('entityActions.snoozeNotifications'),+ icon: Clock,+ action: () => {+ setOpen(false);+ muteAction.snooze([entity]);+ },+ group: 'macro' as const,+ };+ };+// Read reactively as well as through the action's imperative gate: `ops` below// is a memo, so without a reactive dependency the item would stay missing for// the life of this menu if PostHog answered after it was first computed. The@@ -477,10 +493,6 @@ export function SplitFileMenu(props: SplitFileMenuProps) {// Some entities have no shareable link (a reminder resolves to no block, so// its URL is dead); skip the item rather than copy one that won't open.if (entity && !copyLinkAction.canExecute(entity)) return undefined;- // Foreign PRs link out via their entity URL (GitHub); the block-derived- // fallback would mint an internal /pr URL that doesn't resolve, so omit- // the item when the entity is unavailable.- if (!entity && blockName === 'pr') return undefined;return {label: t('entityActions.copyLink'),icon: Link,@@ -579,15 +591,10 @@ export function SplitFileMenu(props: SplitFileMenuProps) {};}).with('copy', () => {+ if (!canDuplicateItemType(props.itemType)) return null;return {label: t('entityActions.duplicate'),action: async () => {- if (props.itemType === 'project') {- console.warn(- 'Attempting to copy project!. This should not happen'- );- return;- }const res = await itemOperations.copyItem({itemType: props.itemType,id: props.id,@@ -646,6 +653,7 @@ export function SplitFileMenu(props: SplitFileMenuProps) {.filter((op) => !!op);return [favoriteOp(),+ snoozeOp(),muteOp(),reminderOp(),addTagOp(),diff --git a/apps/web/src/components/kanban/kanban.tsx b/apps/web/src/components/kanban/kanban.tsxindex 0ccdafe151..fb144c3400 100644--- a/apps/web/src/components/kanban/kanban.tsx+++ b/apps/web/src/components/kanban/kanban.tsx@@ -502,7 +502,12 @@ export function KanbanCard(props: {props.pending && 'ring-1 ring-ink/20')}onMouseDown={(event) => {- if (!event.currentTarget.contains(event.target)) {+ // A secondary press opens the card's menu; it must not restart an+ // active drag's origin.+ if (+ event.button !== 0 ||+ !event.currentTarget.contains(event.target)+ ) {return;}diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsxindex 91f7b46a23..35e2d9881a 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.test.tsx@@ -393,17 +393,8 @@ describe('mixed Agents sidebar', () => {expect(sessionMenu.getByRole('menuitem', { name: 'Copy Link' })).toBeTruthy();- expect(sessionMenu.getByRole('menuitem', { name: 'Archive' })).toBeTruthy();-+ // Archive and Unarchive come from the shared entity menu, like Search's.expect(screen.getByText('Archived')).toBeTruthy();- const archived = screen.getByRole('button', { name: /Old session/ });- fireEvent.contextMenu(archived);- const archivedMenu = within(- archived.closest('[data-entity-context-menu]') as HTMLElement- );- expect(- archivedMenu.getByRole('menuitem', { name: 'Unarchive' })- ).toBeTruthy();const chat = screen.getByRole('button', { name: /Plan launch/ });fireEvent.contextMenu(chat);diff --git a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx b/apps/web/src/features/agents-view/components/AgentsSidebar.tsxindex b116f5310a..68ba5300e9 100644--- a/apps/web/src/features/agents-view/components/AgentsSidebar.tsx+++ b/apps/web/src/features/agents-view/components/AgentsSidebar.tsx@@ -7,7 +7,6 @@ import {} from '@app/components/view-shell';import { CreateMenuItem } from '@app/components/view-shell/CreateMenuItem';import { ViewCreateButton } from '@app/components/view-shell/ViewCreateButton';-import { changeSessionArchiveState } from '@app/features/block-agent/queries/change-session-archive-state';import {type EntityActionListState,type EntityActionViewContext,@@ -19,8 +18,6 @@ import {} from '@app/features/soup';import { t } from '@app/lib/i18n';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';-import { MenuItem } from '@core/component/ContextMenu';-import { useUserId } from '@core/context/user';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { unreadFilterFn } from '@entity/utils/filter';import RoutineIcon from '@icon/system/regular/clock-clockwise.svg';@@ -28,7 +25,6 @@ import CodeIcon from '@icon/system/regular/code.svg';import MagnifyingGlassIcon from '@icon/system/regular/magnifying-glass.svg';import PlugIcon from '@icon/system/regular/plugs-connected.svg';import AgentIcon from '@icon/system/regular/sparkle.svg';-import TrayIcon from '@icon/system/regular/tray.svg';import { Key } from '@solid-primitives/keyed';import { cn, Dropdown } from '@ui';import { tourTarget } from '@ui/components/Tour';@@ -103,15 +99,6 @@ function ConversationContextMenu(props: {list: EntityActionListState;children: JSX.Element;}) {- const userId = useUserId();- const setArchived = async () => {- if (props.conversation.type !== 'agent_session') return;- await changeSessionArchiveState(- props.conversation.id,- !props.conversation.isArchived- );- };-return (<SoupEntityContextMenuentity={props.conversation}@@ -122,20 +109,6 @@ function ConversationContextMenu(props: {// The nav is a fixed-height flex column, so the trigger's default// `h-full` would split that height between the rows; keep rows content-sized.class="block h-auto w-full shrink-0"- extraItems={- props.conversation.type === 'agent_session' &&- props.conversation.ownerId === userId() ? (- <MenuItem- icon={TrayIcon}- text={- props.conversation.isArchived- ? t('entityActions.unarchive')- : t('entityActions.archive')- }- onClick={setArchived}- />- ) : undefined- }onOpenChange={(open) => {if (!open) return;props.list.focus.set(props.conversation.id);diff --git a/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsx b/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsxindex 67cfcf5d2d..fd5b924d90 100644--- a/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsx+++ b/apps/web/src/features/block-call/component/CallRecording/CallRecordingSplitHeader.tsx@@ -10,6 +10,7 @@ import {ResponsivePermissionsBadge,} from '@components/app/ResponsiveBlockToolbar';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';+import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';import {SplitHeaderLeft,SplitHeaderRight,@@ -26,12 +27,16 @@ import { isMobile } from '@core/mobile/isMobile';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { blockMetadataSignal } from '@core/signal/load';import { useGetPermissions } from '@core/signal/permissions';+import { createFileDownload } from '@core/util/createFileDownload';+import { fireAndForget } from '@core/util/fireAndForget';import { buildEntityData } from '@entity';import IconShared from '@icon/share.svg';+import DownloadSimple from '@icon/system/regular/download-simple.svg';import PhoneCallIcon from '@icon/system/regular/phone-call.svg';import type { CallRecord } from '@service-call/client';import { Button } from '@ui';import { Show } from 'solid-js';+import { callRecordingDownloadSource } from '../../queries/recording-download';import { useCallAgain } from '../use-call-again';export function CallRecordingSplitHeaderLoading() {@@ -68,6 +73,27 @@ export function CallRecordingSplitHeader(props: { record: CallRecord }) {() => record().callId,() => record().channelId);+ const recordingDownload = createFileDownload(() =>+ callRecordingDownloadSource(record(), callName())+ );+ const ops = (): FileOperation[] => [+ { op: 'rename' },+ ...(record().recordingUrl+ ? [+ {+ group: 'file' as const,+ label: 'Download',+ icon: DownloadSimple,+ action: () =>+ fireAndForget(+ recordingDownload.start(),+ 'call-recording-download'+ ),+ },+ ]+ : []),+ { op: 'delete' },+ ];const shareTool: BlockTool = {label: 'Share',@@ -173,7 +199,7 @@ export function CallRecordingSplitHeader(props: { record: CallRecord }) {<ResponsiveBlockToolbartools={tools}menuTools={menuTools}- ops={[{ op: 'copy' }]}+ ops={ops()}id={blockId}itemType="call"name={callName()}diff --git a/apps/web/src/features/block-call/queries/recording-download.test.ts b/apps/web/src/features/block-call/queries/recording-download.test.tsnew file mode 100644index 0000000000..e09e6d10b0--- /dev/null+++ b/apps/web/src/features/block-call/queries/recording-download.test.ts@@ -0,0 +1,54 @@+import { Telemetry } from '@macro-inc/observability';+import type { CallRecord } from '@service-call/client';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({ fetch: vi.fn() }));+vi.mock('@core/util/platformFetch', () => ({ platformFetch: mocks.fetch }));++import { callRecordingDownloadSource } from './recording-download';++const record = (recordingUrl?: string): CallRecord => ({+ callId: 'call-1',+ createdBy: 'macro|[email protected]',+ guests: [],+ isActive: false,+ participants: [],+ shareWithTeam: false,+ startedAt: '2026-10-27T10:00:00Z',+ transcript: [],+ recordingUrl,+});++const loadOptions = () => ({+ signal: new AbortController().signal,+ onProgress: vi.fn(),+ span: Telemetry.span('test.call_recording_download'),+});++beforeEach(() => vi.clearAllMocks());++describe('call recording download', () => {+ it('is unavailable until the call has a recording', () => {+ expect(callRecordingDownloadSource(record(), 'Weekly sync')).toBe(+ undefined+ );+ });++ it("saves the recording under the call's name and the recording's extension", async () => {+ mocks.fetch.mockResolvedValue(+ new Response('video', { headers: { 'Content-Type': 'video/mp4' } })+ );+ const source = callRecordingDownloadSource(+ record('https://recordings.example/calls/call-1/1730000000.mp4?sig=a.b'),+ 'Weekly sync'+ );++ const result = await source?.load(loadOptions());++ expect(mocks.fetch.mock.calls[0][0]).toBe(+ 'https://recordings.example/calls/call-1/1730000000.mp4?sig=a.b'+ );+ expect(result?._unsafeUnwrap().name).toBe('Weekly sync.mp4');+ expect(result?._unsafeUnwrap().blob.size).toBe(5);+ });+});diff --git a/apps/web/src/features/block-call/queries/recording-download.ts b/apps/web/src/features/block-call/queries/recording-download.tsnew file mode 100644index 0000000000..2faf3b740f--- /dev/null+++ b/apps/web/src/features/block-call/queries/recording-download.ts@@ -0,0 +1,29 @@+import type { DownloadSource } from '@core/util/createFileDownload';+import type { CallRecord } from '@service-call/client';+import { fetchPresignedBlobWithProgress } from '@service-storage/util/fetchPresigned';+import { fileExtension } from '@service-storage/util/filename';++/**+ * A call's recording, saved under the call's name with the recording's own+ * extension, or undefined while the call has no recording.+ */+export function callRecordingDownloadSource(+ record: CallRecord,+ callName: string+): DownloadSource | undefined {+ const url = record.recordingUrl;+ if (!url) return undefined;+ return {+ // The presigned URL is re-signed on every refetch; the call is stable.+ id: record.callId,+ name: callName,+ load: async ({ signal, onProgress }) => {+ const fileName = new URL(url).pathname.split('/').at(-1);+ const name = `${callName}.${fileExtension(fileName) ?? 'mp4'}`;+ const result = await fetchPresignedBlobWithProgress(url, onProgress, {+ signal,+ });+ return result.map((blob) => ({ blob, name }));+ },+ };+}diff --git a/apps/web/src/features/block-database/component/TopBar.tsx b/apps/web/src/features/block-database/component/TopBar.tsxindex a4e3a04325..5159bab864 100644--- a/apps/web/src/features/block-database/component/TopBar.tsx+++ b/apps/web/src/features/block-database/component/TopBar.tsx@@ -1,3 +1,8 @@+import {+ makeCopyEntityIdAction,+ makeCopyLinkAction,+ makeFavoriteAction,+} from '@app/features/next-soup/actions';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { ResponsivePermissionsBadge } from '@components/app/ResponsiveBlockToolbar';@@ -13,6 +18,8 @@ import { useShareModal } from '@core/component/TopBar/shareModal';import { enableForms } from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { useGetPermissions } from '@core/signal/permissions';+import { fireAndForget } from '@core/util/fireAndForget';+import type { DatabaseEntity } from '@entity';import SparkleIcon from '@icon/system/regular/sparkle.svg';import type { DatabaseDetail } from '@service-storage/generated/schemas/databaseDetail';import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';@@ -26,7 +33,10 @@ import {databaseEntityMessage,} from '../../database/core/write-failure';import { renameDatabase } from '../queries/rename-database';-import { DatabasePageActions } from '../views/database-page-actions';+import {+ type DatabaseEntityActions,+ DatabasePageActions,+} from '../views/database-page-actions';import { TableTabs } from './TableTabs';// Forms load only when the flag is on, and only through this boundary.@@ -74,6 +84,34 @@ export function TopBar(props: {: undefined,};});+ const favoriteAction = makeFavoriteAction();+ const copyLinkAction = makeCopyLinkAction();+ const copyEntityIdAction = makeCopyEntityIdAction();+ const entity = (detail: DatabaseDetail): DatabaseEntity => ({+ type: 'database',+ id: databaseId,+ name: detail.database.name,+ ownerId: detail.database.owner_id,+ grant: detail.grant,+ });+ const entityActions = (detail: DatabaseDetail): DatabaseEntityActions => ({+ favorited: favoriteAction.isFavorited(entity(detail)),+ onToggleFavorite: () =>+ fireAndForget(+ favoriteAction.execute([entity(detail)]),+ 'database-actions'+ ),+ onCopyLink: () =>+ fireAndForget(+ copyLinkAction.execute([entity(detail)]),+ 'database-actions'+ ),+ onCopyId: () =>+ fireAndForget(+ copyEntityIdAction.executeById(databaseId),+ 'database-actions'+ ),+ });const rename = (next: string) => {renameDatabase(getEntityGraphqlClient(), databaseId, next).mapErr((failure) => toast.failure(databaseEntityMessage(failure, 'rename'))@@ -102,6 +140,7 @@ export function TopBar(props: {<DatabasePageActionsdetail={detail()}table={props.activeTable}+ entityActions={entityActions(detail())}onRename={() => editTitle?.()}onDelete={props.onDelete}onImported={props.onSelectTable}diff --git a/apps/web/src/features/block-database/views/database-page-actions.test.tsx b/apps/web/src/features/block-database/views/database-page-actions.test.tsxindex 2992321368..cdde20683c 100644--- a/apps/web/src/features/block-database/views/database-page-actions.test.tsx+++ b/apps/web/src/features/block-database/views/database-page-actions.test.tsx@@ -13,7 +13,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { toast } from '../../../lib/core/component/Toast/Toast';import { DatabaseTitle } from '../../database/components/database-title';import type { DatabaseEntityFailure } from '../../database/core/write-failure';-import { DatabasePageActions } from './database-page-actions';+import {+ type DatabaseEntityActions,+ DatabasePageActions,+} from './database-page-actions';const mocks = vi.hoisted(() => ({download: vi.fn(),@@ -49,7 +52,8 @@ function setup(grant: DatabaseDetail['grant'] = 'owner',remove = vi.fn((): ResultAsync<void, DatabaseEntityFailure> => okAsync(undefined)- )+ ),+ entityActions?: DatabaseEntityActions) {let editTitle: (() => void) | undefined;render(() => (@@ -69,6 +73,7 @@ function setup(} as unknown as DatabaseDetail}table={{ table: { id: 'table', name: 'Contacts' } } as TableDetail}+ entityActions={entityActions}onImported={vi.fn()}onRename={() => editTitle?.()}onDelete={remove}@@ -215,6 +220,25 @@ describe('database page actions', () => {})) as HTMLInputElement;expect(name.value).toBe('Contacts 2');});+ it('offers link, ID and favorite actions to every grant', async () => {+ const entityActions = {+ favorited: true,+ onToggleFavorite: vi.fn(),+ onCopyLink: vi.fn(),+ onCopyId: vi.fn(),+ };+ setup('view', undefined, entityActions);+ for (const [item, handler] of [+ ['Copy Link', entityActions.onCopyLink],+ ['Copy ID', entityActions.onCopyId],+ ['Unfavorite', entityActions.onToggleFavorite],+ ] as const) {+ await openMenu();+ selectItem(item);+ expect(handler).toHaveBeenCalledOnce();+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull());+ }+ });it('confirms deletion and retains a failed dialog for retry', async () => {const remove = vi.fn()diff --git a/apps/web/src/features/block-database/views/database-page-actions.tsx b/apps/web/src/features/block-database/views/database-page-actions.tsxindex 5b9d77158d..c3506a59ec 100644--- a/apps/web/src/features/block-database/views/database-page-actions.tsx+++ b/apps/web/src/features/block-database/views/database-page-actions.tsx@@ -1,9 +1,12 @@import { fireAndForget } from '@core/util/fireAndForget';import { downloadFile } from '@filesystem/download';import CaretRightIcon from '@icon/system/regular/caret-right.svg';+import CopyIcon from '@icon/system/regular/copy.svg';import DotsThreeIcon from '@icon/system/regular/dots-three.svg';import DownloadIcon from '@icon/system/regular/download-simple.svg';+import LinkIcon from '@icon/system/regular/link.svg';import PencilIcon from '@icon/system/regular/pencil-line.svg';+import StarIcon from '@icon/system/regular/star.svg';import TrashIcon from '@icon/system/regular/trash-simple.svg';import UploadIcon from '@icon/system/regular/upload-simple.svg';import WebhookIcon from '@phosphor/webhooks-logo.svg';@@ -37,9 +40,18 @@ import {/** A CSV that cannot become a table, or a file that could not be read at all. */type CsvImportFailure = DatabaseCsvFailure | { kind: 'unreadable' };+/** The items every entity's "…" menu offers, supplied by the host. */+export type DatabaseEntityActions = {+ favorited: boolean;+ onToggleFavorite: () => void;+ onCopyLink: () => void;+ onCopyId: () => void;+};+export function DatabasePageActions(props: {detail: DatabaseDetail;table?: TableDetail;+ entityActions?: DatabaseEntityActions;onImported: (tableId: string) => void;onRename: () => void;onDelete: () => ResultAsync<void, DatabaseEntityFailure>;@@ -166,6 +178,28 @@ export function DatabasePageActions(props: {} else if (confirmDelete()) event.preventDefault();}}>+ <Show when={props.entityActions}>+ {(actions) => (+ <>+ <Dropdown.Group>+ <Dropdown.Item onSelect={actions().onCopyLink}>+ <LinkIcon class="size-4 shrink-0" />+ Copy Link+ </Dropdown.Item>+ <Dropdown.Item onSelect={actions().onCopyId}>+ <CopyIcon class="size-4 shrink-0" />+ Copy ID+ </Dropdown.Item>+ </Dropdown.Group>+ <Dropdown.Group>+ <Dropdown.Item onSelect={actions().onToggleFavorite}>+ <StarIcon class="size-4 shrink-0" />+ {actions().favorited ? 'Unfavorite' : 'Favorite'}+ </Dropdown.Item>+ </Dropdown.Group>+ </>+ )}+ </Show><Show when={editable()}><Dropdown.Group><Dropdown.Item onSelect={() => (focusTitleAfterClose = true)}>diff --git a/apps/web/src/features/block-email/component/useEmailThreadTools.tsx b/apps/web/src/features/block-email/component/useEmailThreadTools.tsxindex 423015595a..35ec98bc79 100644--- a/apps/web/src/features/block-email/component/useEmailThreadTools.tsx+++ b/apps/web/src/features/block-email/component/useEmailThreadTools.tsx@@ -5,7 +5,10 @@ import {} from '@app/features/chat/ChatWithAgentButton';import type { EmailThreadListNavigation } from '@app/features/email-thread/context/email-thread-context';import { useEmailThreadState } from '@app/features/email-thread/context/email-thread-state-context';-import { makeMoveToProjectAction } from '@app/features/next-soup/actions';+import {+ emailSenderBucket,+ makeMoveToProjectAction,+} from '@app/features/next-soup/actions';import { useMaybeSoup } from '@app/features/next-soup/soup-context';import {openEntityInSplitFromUnifiedList,@@ -21,6 +24,7 @@ import {} from '@core/component/TopBar/ShareButton';import { useShareModal } from '@core/component/TopBar/shareModal';import { ENABLE_EMAIL_SHARING } from '@core/constant/featureFlags';+import { useUserId } from '@core/context/user';import { TOKENS } from '@core/hotkey/tokens';import { getActiveCommandByToken, runCommand } from '@core/hotkey/utils';import { fireAndForget } from '@core/util/fireAndForget';@@ -35,6 +39,7 @@ import EnvelopeSimpleOpenIcon from '@icon/system/regular/envelope-simple-open.svimport TaskIcon from '@icon/system/regular/list-checks.svg';import ProhibitIcon from '@icon/system/regular/prohibit.svg';import TrashIcon from '@icon/system/regular/trash.svg';+import SignalIcon from '@icon/system/regular/wave-sine.svg';import NoiseIcon from '@icon/system/regular/waveform.svg';import { useEmailLinksQuery } from '@queries/email/link';import { queryReadyGate } from '@queries/gate';@@ -64,7 +69,9 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {});const soup = useMaybeSoup();const linksQuery = useEmailLinksQuery();- const moveToProjectAction = makeMoveToProjectAction();+ const moveToProjectAction = makeMoveToProjectAction({+ userId: useUserId(),+ });const isInvite = () => {const row = soup?.items.get(props.id);@@ -96,9 +103,20 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {});};+ // The thread's own Signal or Noise placement, when the list row that opened+ // it said; unknown offers both sender moves, as in Search.+ const senderBucket = () => emailSenderBucket(emailEntity());++ // A thread belongs to the mailbox it came to, so being its owner is being+ // one of the user's inboxes; the row's ownerId isn't known before it loads.+ const canMoveToFolder = () => {+ const entity = emailEntity();+ return !!entity && moveToProjectAction.canMoveType(entity) && isOwnThread();+ };+const moveToFolder = () => {const entity = emailEntity();- if (!entity || !moveToProjectAction.canExecute(entity)) return;+ if (!entity || !canMoveToFolder()) return;fireAndForget(moveToProjectAction.execute([entity]), 'email-thread-tools');};@@ -196,14 +214,14 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {const emailActions: BlockTool[] = [{- label: 'Mark done',+ label: 'Mark Done',icon: CheckIcon,action: toggleMarkDone,condition: () => isOwnThread() && !isDone(),hotkeyToken: TOKENS.entity.action.markDone,},{- label: 'Mark as not done',+ label: 'Mark Not Done',icon: CheckBoldIcon,action: toggleMarkDone,condition: () =>@@ -211,14 +229,14 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {hotkeyToken: TOKENS.entity.action.markNotDone,},{- label: 'Mark unread',+ label: 'Mark Unread',icon: EnvelopeSimpleOpenIcon,action: toggleMarkUnread,condition: () => isOwnThread() && !emailCtx.isThreadMarkedUnread(),hotkeyToken: TOKENS.entity.action.markUnread,},{- label: 'Mark read',+ label: 'Mark Read',icon: EnvelopeSimpleIcon,action: toggleMarkUnread,condition: () => isOwnThread() && emailCtx.isThreadMarkedUnread(),@@ -255,7 +273,7 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {action: moveToFolder,condition: () => {const entity = emailEntity();- return !!entity && moveToProjectAction.canExecute(entity);+ return !!entity && canMoveToFolder();},},{@@ -266,12 +284,19 @@ export function useEmailThreadTools(props: EmailThreadToolsOptions) {condition: isOwnThread,hotkeyToken: TOKENS.email.trash,},+ {+ group: 'sender',+ label: 'Sender → Signal',+ icon: SignalIcon,+ action: () => emailCtx.markSenderSignal(),+ condition: () => isOwnThread() && senderBucket() !== 'signal',+ },{group: 'sender',label: 'Sender → Noise',icon: NoiseIcon,action: () => emailCtx.markSenderNoise(),- condition: isOwnThread,+ condition: () => isOwnThread() && senderBucket() !== 'noise',},{group: 'sender',diff --git a/apps/web/src/features/block-form/form-block.test.tsx b/apps/web/src/features/block-form/form-block.test.tsxindex 16a6f93d72..990562aafd 100644--- a/apps/web/src/features/block-form/form-block.test.tsx+++ b/apps/web/src/features/block-form/form-block.test.tsx@@ -33,6 +33,10 @@ vi.mock('@components/app/split-layout/components/SplitHeader', () => ({}));vi.mock('@components/app/split-layout/components/SplitLabel', () => ({BlockItemSplitLabel: () => null,+ SplitTitleFileMenu: (props: ParentProps) => props.children,+}));+vi.mock('@components/app/split-layout/components/SplitFileMenu', () => ({+ SplitFileMenu: () => null,}));vi.mock('@components/app/ResponsiveBlockToolbar', () => ({ResponsivePermissionsBadge: () => null,diff --git a/apps/web/src/features/block-form/form-block.tsx b/apps/web/src/features/block-form/form-block.tsxindex b67d2fe1db..e154d33877 100644--- a/apps/web/src/features/block-form/form-block.tsx+++ b/apps/web/src/features/block-form/form-block.tsx@@ -12,11 +12,15 @@ import { HeaderActionButton } from '@components/app/HeaderActionButton';import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { ResponsivePermissionsBadge } from '@components/app/ResponsiveBlockToolbar';import { HeaderIsland } from '@components/app/split-layout/components/HeaderIsland';+import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';import {SplitHeaderLeft,SplitHeaderRight,} from '@components/app/split-layout/components/SplitHeader';-import { BlockItemSplitLabel } from '@components/app/split-layout/components/SplitLabel';+import {+ BlockItemSplitLabel,+ SplitTitleFileMenu,+} from '@components/app/split-layout/components/SplitLabel';import { useSplitLayout } from '@components/app/split-layout/layout';import {returnSplitToRecentListView,@@ -25,10 +29,12 @@ import {import { useBlockId, useIsNestedBlock } from '@core/block';import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';import { BlockLiveIndicators } from '@core/component/LiveIndicators';+import { getPermissions } from '@core/component/SharePermissions';import { ShareTrigger } from '@core/component/TopBar/ShareButton';import { useShareModal } from '@core/component/TopBar/shareModal';import { enableForms } from '@core/constant/featureFlags';import { isMobile } from '@core/mobile/isMobile';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import { fireAndForget } from '@core/util/fireAndForget';import { openExternalUrl } from '@core/util/url';import { useCopyLink } from '@core/util/useCopyLink';@@ -155,6 +161,28 @@ function FormBlockContent(props: {<SplitHeaderLeft><BlockItemSplitLabel name={name} /></SplitHeaderLeft>+ <Show when={source.detail()}>+ {(detail) => (+ <SplitTitleFileMenu>+ <SplitFileMenu+ id={formId}+ itemType="form"+ entityKind="form"+ name={detail().form.name}+ entity={{+ type: 'form',+ id: formId,+ name: detail().form.name,+ ownerId: detail().form.ownerId,+ access: detail().access,+ }}+ permissions={getPermissions(detail().access)}+ ops={[]}+ buttonClass={isTouchDevice() ? 'order-last' : 'order-first'}+ />+ </SplitTitleFileMenu>+ )}+ </Show><SplitHeaderRight><Showwhen={diff --git a/apps/web/src/features/block-pr/component/Block.tsx b/apps/web/src/features/block-pr/component/Block.tsxindex ad20d118c6..dd9a57a09d 100644--- a/apps/web/src/features/block-pr/component/Block.tsx+++ b/apps/web/src/features/block-pr/component/Block.tsx@@ -4,8 +4,10 @@ import { SplitPanel } from '@components/app/split-panel';import { useBlockId } from '@core/block';import { fireAndForget } from '@core/util/fireAndForget';import { Show } from 'solid-js';+import { createPrActions } from '../primitives/create-pr-actions';import { prDisplayName } from '../util/prKey';import { PrDetailActions, PrDetailBody, usePrDetail } from '../views/PrDetail';+import { confirmMergePullRequest } from './MergePullRequestButton';import { PrSplitHeader } from './PrSplitHeader';import { PrStatusIcon } from './PrStatus';import { PrSidePanelSections } from './sidepanel/PrSidePanelSections';@@ -14,6 +16,7 @@ import { PrSidePanelSections } from './sidepanel/PrSidePanelSections';export default function PrBlock() {const foreignEntityId = useBlockId();const detail = usePrDetail(() => foreignEntityId);+ const actions = createPrActions(detail.data, confirmMergePullRequest);const name = () => {const data = detail.data();return (@@ -35,16 +38,10 @@ export default function PrBlock() {{(status) => <PrStatusIcon status={status()} />}</Show><span class="min-w-0 truncate text-sm font-semibold">{name()}</span>- <PrDetailActions detail={detail.data()} />+ <PrDetailActions detail={detail.data()} actions={actions} /></ViewShell.TopBar><Show when={detail.data()}>- {(data) => (- <PrSplitHeader- foreignEntityId={foreignEntityId}- prRef={data().prRef}- enrichment={data().pullRequest}- />- )}+ {(data) => <PrSplitHeader detail={data()} actions={actions} />}</Show><PrDetailBodyforeignEntityId={foreignEntityId}diff --git a/apps/web/src/features/block-pr/component/PrSplitHeader.tsx b/apps/web/src/features/block-pr/component/PrSplitHeader.tsxindex e7ae90d285..90ad5fcf52 100644--- a/apps/web/src/features/block-pr/component/PrSplitHeader.tsx+++ b/apps/web/src/features/block-pr/component/PrSplitHeader.tsx@@ -1,54 +1,30 @@-import {- type FileOperation,- SplitFileMenu,-} from '@components/app/split-layout/components/SplitFileMenu';+import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';import {SplitTitleFileMenu,StaticSplitLabel,} from '@components/app/split-layout/components/SplitLabel';import { Permissions } from '@core/component/SharePermissions';-import { toast } from '@core/component/Toast/Toast';import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { openExternalUrl } from '@core/util/url';-import GithubIcon from '@icon/mcp-github.svg';-import Link from '@icon/system/regular/link.svg';-import type { GithubPullRequest } from '@service-storage/generated/schemas';--import type { PrRef } from '../util/prKey';-import { prDisplayName, prHtmlUrl } from '../util/prKey';+import type { PrForeignEntityData } from '../data/queries';+import type { PrActions } from '../primitives/create-pr-actions';+import { usePrFileOperations } from '../primitives/pr-file-operations';+import { prDisplayName } from '../util/prKey';import { PrStatusIcon } from './PrStatus';/*** PR identity in the split header chrome and file menu, independent of the* legacy block context. Foreign PRs have the same read-only permission that- * the legacy BlockLoader supplied by default.+ * the legacy BlockLoader supplied by default; GitHub decides whether the+ * menu's changes go through.*/export function PrSplitHeader(props: {- foreignEntityId: string;- prRef: PrRef;- enrichment: GithubPullRequest | undefined;+ detail: PrForeignEntityData;+ actions: PrActions;}) {- const title = () => props.enrichment?.name ?? prDisplayName(props.prRef);- const githubUrl = () => props.enrichment?.url ?? prHtmlUrl(props.prRef);-- const copyLink = async () => {- await navigator.clipboard.writeText(githubUrl());- toast.success('Link copied to clipboard');- };-- const ops: FileOperation[] = [- {- label: 'Copy link',- icon: Link,- action: copyLink,- },- {- label: 'Open on GitHub',- icon: GithubIcon,- action: () => openExternalUrl(githubUrl()),- },- ];+ const title = () =>+ props.detail.pullRequest.name ?? prDisplayName(props.detail.prRef);+ const operations = usePrFileOperations(() => props.detail, props.actions);return (<>@@ -57,7 +33,7 @@ export function PrSplitHeader(props: {label={title()}icon={<PrStatusIcon- status={props.enrichment?.status ?? 'open'}+ status={props.detail.pullRequest.status ?? 'open'}class="size-3.5"/>}@@ -66,12 +42,12 @@ export function PrSplitHeader(props: {<SplitTitleFileMenu><SplitFileMenu- id={props.foreignEntityId}+ id={props.detail.id}itemType="foreign"entityKind="pr"permissions={Permissions.CAN_VIEW}name={title()}- ops={ops}+ ops={operations()}buttonClass={isTouchDevice() ? 'order-last' : 'order-first'}/></SplitTitleFileMenu>diff --git a/apps/web/src/features/block-pr/component/PullRequestActionsButton.test.tsx b/apps/web/src/features/block-pr/component/PullRequestActionsButton.test.tsxnew file mode 100644index 0000000000..e096d1a5cc--- /dev/null+++ b/apps/web/src/features/block-pr/component/PullRequestActionsButton.test.tsx@@ -0,0 +1,191 @@+/** @vitest-environment jsdom */+import { queryClient } from '@queries/client';+import { authServiceClient } from '@service-auth/client';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { QueryClientProvider } from '@tanstack/solid-query';+import { ok } from 'neverthrow';+import { createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { PrForeignEntityData } from '../data/queries';+import { createPrActions } from '../primitives/create-pr-actions';+import { PullRequestActionsButton } from './PullRequestActionsButton';++const mocks = vi.hoisted(() => ({+ success: vi.fn(),+ failure: vi.fn(),+}));++vi.mock('@queries/client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return {+ queryClient: new QueryClient({+ defaultOptions: { queries: { retry: false } },+ }),+ };+});+vi.mock('@service-auth/client', () => ({+ authServiceClient: {+ mergeGithubPullRequest: vi.fn(),+ setGithubPullRequestDraft: vi.fn(),+ setGithubPullRequestState: vi.fn(),+ },+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: mocks.success, failure: mocks.failure },+}));++const target = { owner: 'macro-inc', repo: 'macro', number: 6369 };++function pullRequest(+ overrides: Partial<PrForeignEntityData['pullRequest']>+): PrForeignEntityData {+ return {+ id: 'pr-1',+ prRef: target,+ pullRequest: {+ ...target,+ displayName: 'macro-inc/macro#6369',+ githubKey: 'macro-inc/macro/pull/6369',+ url: 'https://github.com/macro-inc/macro/pull/6369',+ name: 'Fix reply state',+ status: 'open',+ draft: false,+ checks: [+ {+ id: 1,+ name: 'ci',+ status: 'completed',+ conclusion: 'success',+ },+ ],+ ...overrides,+ } as PrForeignEntityData['pullRequest'],+ };+}++function setup(initial: PrForeignEntityData) {+ const [detail, setDetail] = createSignal(initial);+ const confirmMerge = vi.fn(async () => true);+ render(() => (+ <QueryClientProvider client={queryClient}>+ {(() => {+ const actions = createPrActions(detail, confirmMerge);+ return <PullRequestActionsButton actions={actions} />;+ })()}+ </QueryClientProvider>+ ));+ return { setDetail, confirmMerge };+}++async function openMenu() {+ const trigger = screen.getByRole('button', {+ name: 'More pull request actions',+ });+ trigger.focus();+ fireEvent.keyDown(trigger, { key: 'ArrowDown' });+ return screen.findByRole('menu');+}++function selectItem(name: string) {+ const item = screen.getByRole('menuitem', { name });+ item.focus();+ fireEvent.keyDown(item, { key: 'Enter' });+}++afterEach(() => {+ cleanup();+ queryClient.clear();+ vi.clearAllMocks();+});++describe('PullRequestActionsButton', () => {+ it('marks a draft ready for review, with Close behind the chevron', async () => {+ vi.mocked(authServiceClient.setGithubPullRequestDraft).mockResolvedValue(+ ok({ draft: false })+ );+ setup(pullRequest({ draft: true }));++ expect(screen.queryByRole('button', { name: 'Merge' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Ready for review' }));++ await waitFor(() =>+ expect(authServiceClient.setGithubPullRequestDraft).toHaveBeenCalledWith({+ ...target,+ draft: false,+ })+ );+ await openMenu();+ expect(+ screen.getByRole('menuitem', { name: 'Close pull request' })+ ).toBeTruthy();+ expect(+ screen.queryByRole('menuitem', { name: 'Convert to draft' })+ ).toBeNull();+ });++ it('merges a ready pull request and offers draft and close behind the chevron', async () => {+ vi.mocked(authServiceClient.setGithubPullRequestState).mockResolvedValue(+ ok({ state: 'closed' })+ );+ vi.mocked(authServiceClient.mergeGithubPullRequest).mockResolvedValue(+ ok({ sha: 'abc123', message: 'Pull Request successfully merged' })+ );+ const { confirmMerge } = setup(pullRequest({}));++ fireEvent.click(screen.getByRole('button', { name: 'Merge' }));+ await waitFor(() =>+ expect(mocks.success).toHaveBeenCalledWith('Merged macro-inc/macro#6369')+ );+ expect(confirmMerge).toHaveBeenCalledOnce();++ await openMenu();+ expect(+ screen.getByRole('menuitem', { name: 'Convert to draft' })+ ).toBeTruthy();+ selectItem('Close pull request');+ await waitFor(() =>+ expect(authServiceClient.setGithubPullRequestState).toHaveBeenCalledWith({+ ...target,+ state: 'closed',+ })+ );+ expect(mocks.success).toHaveBeenCalledWith('Closed macro-inc/macro#6369');+ });++ it('keeps Merge disabled until every check passes', () => {+ const { setDetail } = setup(+ pullRequest({+ checks: [+ { id: 2, name: 'ci', status: 'in_progress', conclusion: null },+ ],+ })+ );++ const merge = screen.getByRole('button', {+ name: 'Merge',+ }) as HTMLButtonElement;+ expect(merge.disabled).toBe(true);+ expect(+ screen.getByRole('button', { name: 'More pull request actions' })+ ).toBeTruthy();++ setDetail(pullRequest({}));+ expect(+ (screen.getByRole('button', { name: 'Merge' }) as HTMLButtonElement)+ .disabled+ ).toBe(false);+ });++ it('renders nothing for merged or closed pull requests', () => {+ const { setDetail } = setup(pullRequest({ status: 'merged' }));+ expect(screen.queryByRole('button')).toBeNull();+ setDetail(pullRequest({ status: 'closed' }));+ expect(screen.queryByRole('button')).toBeNull();+ });+});diff --git a/apps/web/src/features/block-pr/component/PullRequestActionsButton.tsx b/apps/web/src/features/block-pr/component/PullRequestActionsButton.tsxnew file mode 100644index 0000000000..6d13b52d49--- /dev/null+++ b/apps/web/src/features/block-pr/component/PullRequestActionsButton.tsx@@ -0,0 +1,64 @@+import { t } from '@app/lib/i18n';+import CaretDown from '@icon/system/regular/caret-down.svg';+import { Button, ButtonGroup, Dropdown } from '@ui';+import { For, Show } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import type { PrActions } from '../primitives/create-pr-actions';++/**+ * The pull request header's split button: Merge, or Ready for review for a+ * draft, with the other state changes (convert to draft, close) behind the+ * chevron. Merge stays visible but disabled until every check passes.+ */+export function PullRequestActionsButton(props: { actions: PrActions }) {+ return (+ <Show when={props.actions.primary()}>+ {(primary) => (+ <Dropdown placement="bottom-end">+ <ButtonGroup+ variant={primary().key === 'merge' ? 'success' : 'outline'}+ depth={2}+ label={t('entityActions.prActions')}+ >+ <Button+ disabled={props.actions.pending() || !!primary().disabledReason}+ tooltip={primary().disabledReason}+ aria-description={primary().disabledReason}+ data-pull-request-primary-action={primary().key}+ onClick={() => primary().run()}+ >+ <Dynamic component={primary().icon} class="size-3.5" />+ <span>+ {primary().key === 'merge' && props.actions.pending()+ ? t('entityActions.prMerging')+ : primary().label}+ </span>+ </Button>+ <Show when={props.actions.secondary().length > 0}>+ <ButtonGroup.Divider />+ <Dropdown.Trigger+ size="icon-md"+ label={t('entityActions.prMoreActions')}+ disabled={props.actions.pending()}+ >+ <CaretDown class="size-3.5" />+ </Dropdown.Trigger>+ </Show>+ </ButtonGroup>+ <Dropdown.Content>+ <Dropdown.Group>+ <For each={props.actions.secondary()}>+ {(action) => (+ <Dropdown.Item onSelect={action.run}>+ <Dynamic component={action.icon} class="size-4 shrink-0" />+ {action.label}+ </Dropdown.Item>+ )}+ </For>+ </Dropdown.Group>+ </Dropdown.Content>+ </Dropdown>+ )}+ </Show>+ );+}diff --git a/apps/web/src/features/block-pr/data/queries.ts b/apps/web/src/features/block-pr/data/queries.tsindex 0cf2dd6eb9..0828ce5843 100644--- a/apps/web/src/features/block-pr/data/queries.ts+++ b/apps/web/src/features/block-pr/data/queries.ts@@ -15,6 +15,8 @@ export type PrForeignEntityData = {id: string;prRef: PrRef;pullRequest: GithubPullRequestWithDetails;+ /** The branch carrying the pull request's changes, when stored. */+ headBranch?: string;};export function prForeignEntityQueryKey(id: string): string[] {@@ -38,6 +40,7 @@ function prForeignEntityDataFromStored(return {id: pullRequest.id,prRef,+ headBranch: pullRequest.head?.name ?? undefined,pullRequest: {additions: pullRequest.additions,authorLogin: pullRequest.authorLogin,diff --git a/apps/web/src/features/block-pr/hooks/usePrShare.tsx b/apps/web/src/features/block-pr/hooks/usePrShare.tsxindex e015dd6c2c..4b7c6e197e 100644--- a/apps/web/src/features/block-pr/hooks/usePrShare.tsx+++ b/apps/web/src/features/block-pr/hooks/usePrShare.tsx@@ -7,7 +7,6 @@ import { buildSimpleEntityUrl } from '@core/util/url';import { useCopyLink } from '@core/util/useCopyLink';import CopyIcon from '@icon/system/regular/copy.svg';import { Dialog } from '@kobalte/core/dialog';-import { createCallback } from '@solid-primitives/rootless';import { Button, Panel } from '@ui';import { type Accessor, createSignal, Show } from 'solid-js';@@ -16,6 +15,7 @@ interface PrShareModalProps {name: string;open: boolean;onOpenChange: (open: boolean) => void;+ copyLink: () => Promise<boolean>;}function prShareUrl(foreignEntityId: string): string {@@ -23,15 +23,6 @@ function prShareUrl(foreignEntityId: string): string {}function PrShareModal(props: PrShareModalProps) {- const copyEntityLink = useCopyLink();-- const copyLink = createCallback(() => {- fireAndForget(- copyEntityLink(prShareUrl(props.foreignEntityId)),- 'pr-share-modal'- );- });-return (<Showwhen={!isMobile()}@@ -67,7 +58,12 @@ function PrShareModal(props: PrShareModalProps) {submitPermissionInfo={undefined}/><div class="px-4 py-3 border-t border-edge-muted">- <Button variant="outline" onClick={copyLink}>+ <Button+ variant="outline"+ onClick={() =>+ fireAndForget(props.copyLink(), 'pr-share-modal')+ }+ ><CopyIcon class="size-4" /><span>Copy Link</span></Button>@@ -121,7 +117,12 @@ function PrShareModal(props: PrShareModalProps) {Anyone with access to the PR on GitHub can view it inMacro</span>- <Button variant="outline" onClick={copyLink}>+ <Button+ variant="outline"+ onClick={() =>+ fireAndForget(props.copyLink(), 'pr-share-modal')+ }+ ><CopyIcon class="size-4" /><span>Copy Link</span></Button>@@ -137,16 +138,18 @@ function PrShareModal(props: PrShareModalProps) {}/**- * Hook to manage PR share modal state. Returns the modal component and an- * opener function.+ * Hook to manage PR share modal state. Returns the modal component, an opener+ * function, and the share link copy the modal and header both offer.*/export function usePrShare(foreignEntityId: Accessor<string>,name: Accessor<string>) {const [open, setOpen] = createSignal(false);+ const copyEntityLink = useCopyLink();const openShare = () => setOpen(true);+ const copyLink = () => copyEntityLink(prShareUrl(foreignEntityId()));const ShareModal = () => (<PrShareModal@@ -154,8 +157,9 @@ export function usePrShare(name={name()}open={open()}onOpenChange={setOpen}+ copyLink={copyLink}/>);- return { openShare, ShareModal, isOpen: open };+ return { openShare, copyLink, ShareModal, isOpen: open };}diff --git a/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.ts b/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.tsindex bbba2bd19e..bf6bb46064 100644--- a/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.ts+++ b/apps/web/src/features/block-pr/primitives/create-merge-pull-request-action.ts@@ -18,12 +18,15 @@ export type MergePullRequestAction = {pending: Accessor<boolean>;};-function mergeFailureMessage(error: unknown): string {- // A declined merge carries GitHub's own reason; anything else is ours.+/** GitHub's own reason when it declined a pull request change; anything else is ours. */+export function pullRequestFailureMessage(+ error: unknown,+ fallback: string+): string {if (error instanceof ThrownResultError && error.errors.length > 0) {return error.message;}- return 'Failed to merge pull request';+ return fallback;}/**@@ -51,7 +54,9 @@ export function createMergePullRequestAction(options: {try {await mutation.mutateAsync(input);} catch (error) {- toast.failure(mergeFailureMessage(error));+ toast.failure(+ pullRequestFailureMessage(error, 'Failed to merge pull request')+ );return;}toast.success(`Merged ${name}`);diff --git a/apps/web/src/features/block-pr/primitives/create-pr-actions.ts b/apps/web/src/features/block-pr/primitives/create-pr-actions.tsnew file mode 100644index 0000000000..9df57e2e92--- /dev/null+++ b/apps/web/src/features/block-pr/primitives/create-pr-actions.ts@@ -0,0 +1,201 @@+import { t } from '@app/lib/i18n';+import { toast } from '@core/component/Toast/Toast';+import { fireAndForget } from '@core/util/fireAndForget';+import ArrowCounterClockwise from '@icon/system/regular/arrow-counter-clockwise.svg';+import Eye from '@icon/system/regular/eye.svg';+import FileDashed from '@icon/system/regular/file-dashed.svg';+import GitMerge from '@icon/system/regular/git-merge.svg';+import XCircle from '@icon/system/regular/x-circle.svg';+import { queryClient } from '@queries/client';+import { soupKeys } from '@queries/soup/keys';+import { useSetGithubPullRequestDraftMutation } from '@queries/storage/pr-draft';+import { useSetGithubPullRequestStateMutation } from '@queries/storage/pr-state';+import {+ type Accessor,+ type Component,+ getOwner,+ type JSX,+ type Owner,+} from 'solid-js';+import {+ invalidatePrForeignEntity,+ type PrForeignEntityData,+} from '../data/queries';+import { prDisplayName } from '../util/prKey';+import {+ createMergePullRequestAction,+ type MergePullRequestTarget,+ pullRequestFailureMessage,+} from './create-merge-pull-request-action';+import { pullRequestReadyToMerge } from './pull-request-ready-to-merge';++export type PrActionKey =+ | 'merge'+ | 'ready-for-review'+ | 'convert-to-draft'+ | 'close'+ | 'reopen';++export type PrAction = {+ key: PrActionKey;+ label: string;+ icon: Component<JSX.SvgSVGAttributes<SVGSVGElement>>;+ run: () => void;+ /** Why the action can't run yet; only Merge waits, on checks. */+ disabledReason?: string;+};++export type PrActions = {+ /** Every change the pull request offers now, in menu order. */+ all: Accessor<PrAction[]>;+ /** The header button's action: Merge, or Ready for review for a draft. */+ primary: Accessor<PrAction | undefined>;+ /** The rest, behind the header button's chevron. */+ secondary: Accessor<PrAction[]>;+ /** A change is in flight. */+ pending: Accessor<boolean>;+};++/**+ * A pull request's state changes, shared by its header button and "…" menu:+ * merge, draft state, and close or reopen. GitHub decides whether the+ * signed-in user may make a change and says why when it declines.+ */+export function createPrActions(+ detail: Accessor<PrForeignEntityData | undefined>,+ /** Asks before merging; the host supplies the dialog. */+ confirmMerge: (+ target: MergePullRequestTarget,+ owner: Owner | null+ ) => Promise<boolean>+): PrActions {+ const owner = getOwner();+ // The routes patch the stored pull request first, so refetches see the+ // change: the detail itself and the lists showing it.+ const refresh = () => {+ const id = detail()?.id;+ if (id) invalidatePrForeignEntity(id);+ queryClient.invalidateQueries({ queryKey: soupKeys.astItems._def });+ };+ const merge = createMergePullRequestAction({+ confirm: (target) => confirmMerge(target, owner),+ onMerged: refresh,+ });+ const setDraft = useSetGithubPullRequestDraftMutation();+ const setState = useSetGithubPullRequestStateMutation();++ const change = async (+ request: () => Promise<unknown>,+ copy: { done: string; failed: string }+ ) => {+ try {+ await request();+ } catch (error) {+ toast.failure(pullRequestFailureMessage(error, copy.failed));+ return;+ }+ toast.success(copy.done);+ refresh();+ };+ const runChange = (+ request: () => Promise<unknown>,+ copy: { done: string; failed: string }+ ) => fireAndForget(change(request, copy), 'pr-actions');++ const all = (): PrAction[] => {+ const data = detail();+ if (!data) return [];+ const { prRef, pullRequest } = data;+ const target = {+ owner: prRef.owner,+ repo: prRef.repo,+ number: prRef.number,+ };+ const name = prDisplayName(prRef);+ const actions: PrAction[] = [];++ if (pullRequest.status === 'closed') {+ actions.push({+ key: 'reopen',+ label: t('entityActions.prReopen'),+ icon: ArrowCounterClockwise,+ run: () =>+ runChange(() => setState.mutateAsync({ ...target, state: 'open' }), {+ done: t('entityActions.toastPrReopened', { name }),+ failed: t('entityActions.toastPrReopenFailed'),+ }),+ });+ }+ if (pullRequest.status !== 'open') return actions;++ if (pullRequest.draft === true) {+ actions.push({+ key: 'ready-for-review',+ label: t('entityActions.prReadyForReview'),+ icon: Eye,+ run: () =>+ runChange(() => setDraft.mutateAsync({ ...target, draft: false }), {+ done: t('entityActions.toastPrReadyForReview', { name }),+ failed: t('entityActions.toastPrReadyForReviewFailed'),+ }),+ });+ } else {+ actions.push({+ key: 'merge',+ label: t('entityActions.prMerge'),+ icon: GitMerge,+ run: () =>+ fireAndForget(+ merge.merge({ ...prRef, title: pullRequest.name }),+ 'pr-merge'+ ),+ disabledReason: pullRequestReadyToMerge({+ status: pullRequest.status,+ draft: pullRequest.draft,+ checks: pullRequest.checks,+ })+ ? undefined+ : t('entityActions.prMergeWaitsOnChecksTooltip'),+ });+ }+ // Draft state unknown: offer neither direction rather than guess.+ if (pullRequest.draft === false) {+ actions.push({+ key: 'convert-to-draft',+ label: t('entityActions.prConvertToDraft'),+ icon: FileDashed,+ run: () =>+ runChange(() => setDraft.mutateAsync({ ...target, draft: true }), {+ done: t('entityActions.toastPrConvertedToDraft', { name }),+ failed: t('entityActions.toastPrConvertToDraftFailed'),+ }),+ });+ }+ actions.push({+ key: 'close',+ label: t('entityActions.prClose'),+ icon: XCircle,+ run: () =>+ runChange(() => setState.mutateAsync({ ...target, state: 'closed' }), {+ done: t('entityActions.toastPrClosed', { name }),+ failed: t('entityActions.toastPrCloseFailed'),+ }),+ });+ return actions;+ };++ const primary = () =>+ all().find(+ (action) => action.key === 'merge' || action.key === 'ready-for-review'+ );++ return {+ all,+ primary,+ secondary: () => {+ const primaryKey = primary()?.key;+ return all().filter((action) => action.key !== primaryKey);+ },+ pending: () => merge.pending() || setDraft.isPending || setState.isPending,+ };+}diff --git a/apps/web/src/features/block-pr/primitives/pr-file-operations.ts b/apps/web/src/features/block-pr/primitives/pr-file-operations.tsnew file mode 100644index 0000000000..1cd23b746a--- /dev/null+++ b/apps/web/src/features/block-pr/primitives/pr-file-operations.ts@@ -0,0 +1,80 @@+import { t } from '@app/lib/i18n';+import type { FileOperation } from '@components/app/split-layout/components/SplitFileMenu';+import { toast } from '@core/component/Toast/Toast';+import { fireAndForget } from '@core/util/fireAndForget';+import { openExternalUrl } from '@core/util/url';+import GithubIcon from '@icon/mcp-github.svg';+import GitBranch from '@icon/system/regular/git-branch.svg';+import Link from '@icon/system/regular/link.svg';+import type { Accessor } from 'solid-js';+import type { PrForeignEntityData } from '../data/queries';+import { prHtmlUrl } from '../util/prKey';+import type { PrActions } from './create-pr-actions';++async function copyToClipboard(text: string, confirmation: string) {+ await navigator.clipboard.writeText(text);+ toast.success(confirmation);+}++/**+ * A pull request's "…" menu: the state changes it offers now (Merge only+ * once its checks pass, as on the header button), its GitHub link, and its+ * branch.+ */+export function usePrFileOperations(+ detail: Accessor<PrForeignEntityData | undefined>,+ actions: PrActions+): Accessor<FileOperation[]> {+ return () => {+ const data = detail();+ if (!data) return [];+ const githubUrl = data.pullRequest.url || prHtmlUrl(data.prRef);+ const operations: FileOperation[] = actions+ .all()+ .filter((action) => !action.disabledReason)+ .map((action) => ({+ label: action.label,+ icon: action.icon,+ action: action.run,+ }));++ operations.push(+ {+ group: 'sharing',+ label: t('entityActions.copyGithubLink'),+ icon: Link,+ action: () =>+ fireAndForget(+ copyToClipboard(+ githubUrl,+ t('entityActions.toastGithubLinkCopied')+ ),+ 'pr-file-menu'+ ),+ },+ {+ group: 'sharing',+ label: t('entityActions.openOnGitHub'),+ icon: GithubIcon,+ action: () => openExternalUrl(githubUrl),+ }+ );+ const headBranch = data.headBranch;+ if (headBranch) {+ operations.push({+ group: 'sharing',+ label: t('entityActions.copyBranchName'),+ icon: GitBranch,+ action: () =>+ fireAndForget(+ copyToClipboard(+ headBranch,+ t('entityActions.toastBranchNameCopied')+ ),+ 'pr-file-menu'+ ),+ });+ }+ return operations;+ };+}diff --git a/apps/web/src/features/block-pr/views/PrDetail.tsx b/apps/web/src/features/block-pr/views/PrDetail.tsxindex a22aa4958c..8b3af6f7d2 100644--- a/apps/web/src/features/block-pr/views/PrDetail.tsx+++ b/apps/web/src/features/block-pr/views/PrDetail.tsx@@ -5,24 +5,27 @@ import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { HeaderActionButton } from '@components/app/HeaderActionButton';import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { SidePanel } from '@components/app/side-panel';+import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';import { SplitPanel } from '@components/app/split-panel';import {StaticMarkdown,StaticMarkdownContext,} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { Permissions } from '@core/component/SharePermissions';import { fireAndForget } from '@core/util/fireAndForget';import { GithubLabelPills } from '@entity/components/GithubLabelPill';import { PrAgentSessionsChip } from '@entity/views/PrAgentSessionsChip';import IconShared from '@icon/share.svg';+import IconLink from '@icon/system/regular/link.svg';import { DebouncedNotificationReadMarker } from '@notifications';import {type GithubPullRequestWithDetails,useRefreshGithubPullRequest,} from '@queries/storage/github-pull-requests';import { githubPullRequestChangesKeys } from '@queries/storage/keys';-import { Button, cn, Layer, Scroll, Tooltip } from '@ui';+import { Button, CopyButton, cn, Layer, Scroll, Tooltip } from '@ui';import { type Accessor, createMemo, Show, Suspense } from 'solid-js';-import { MergePullRequestButton } from '../component/MergePullRequestButton';+import { confirmMergePullRequest } from '../component/MergePullRequestButton';import { PrChangesProvider } from '../component/PrChanges';import {PrDescriptionSkeleton,@@ -36,15 +39,20 @@ import {PrStatusIcon,} from '../component/PrStatus';import { PrTimeline } from '../component/PrTimeline';+import { PullRequestActionsButton } from '../component/PullRequestActionsButton';import { PrSidePanelSections } from '../component/sidepanel/PrSidePanelSections';import { createPrDiscussionSource } from '../data/prDiscussionSource';import {- invalidatePrForeignEntity,type PrForeignEntityData,prForeignEntityQueryKey,usePrForeignEntityQuery,} from '../data/queries';import { usePrShare } from '../hooks/usePrShare';+import {+ createPrActions,+ type PrActions,+} from '../primitives/create-pr-actions';+import { usePrFileOperations } from '../primitives/pr-file-operations';import {cleanGithubMarkdown,githubAvatarUrl,@@ -191,8 +199,11 @@ export function PrDetailContent(props: PrDetailBodyProps) {);}-export function PrDetailActions(props: { detail?: PrForeignEntityData }) {- const { openShare, ShareModal } = usePrShare(+export function PrDetailActions(props: {+ detail?: PrForeignEntityData;+ actions: PrActions;+}) {+ const { openShare, copyLink, ShareModal } = usePrShare(() => props.detail?.id ?? '',() => props.detail?.pullRequest.name ?? 'Pull request');@@ -200,28 +211,24 @@ export function PrDetailActions(props: { detail?: PrForeignEntityData }) {return (<div class="ml-auto flex shrink-0 items-center gap-2"><Show when={props.detail}>- {(detail) => (- <>- <HeaderActionGroup label="Sharing">- <Tooltip label="Share pull request">- <HeaderActionButton- label="Share"- icon={<IconShared />}- onClick={openShare}- />- </Tooltip>- </HeaderActionGroup>- <HeaderActionGroup label="Pull request actions">- <MergePullRequestButton- target={{ ...detail().prRef, title: detail().pullRequest.name }}- status={detail().pullRequest.status}- draft={detail().pullRequest.draft}- checks={detail().pullRequest.checks}- onMerged={() => invalidatePrForeignEntity(detail().id)}- />- </HeaderActionGroup>- </>- )}+ <HeaderActionGroup label="Sharing">+ <Tooltip label="Share pull request">+ <HeaderActionButton+ label="Share"+ icon={<IconShared />}+ onClick={openShare}+ />+ </Tooltip>+ <CopyButton+ variant="ghost"+ tooltip="Copy Share Link"+ size="icon-md"+ onClick={copyLink}+ >+ <IconLink class="size-3.5!" />+ </CopyButton>+ </HeaderActionGroup>+ <PullRequestActionsButton actions={props.actions} /></Show><ChangesToggle /><SidePanel.Toggle />@@ -232,6 +239,8 @@ export function PrDetailActions(props: { detail?: PrForeignEntityData }) {export function StandalonePrDetail(props: { foreignEntityId: string }) {const detail = usePrDetail(() => props.foreignEntityId);+ const actions = createPrActions(detail.data, confirmMergePullRequest);+ const operations = usePrFileOperations(detail.data, actions);const name = () => {const data = detail.data();return (@@ -261,7 +270,17 @@ export function StandalonePrDetail(props: { foreignEntityId: string }) {<span class="min-w-0 truncate text-sm font-semibold">{name()}</span>- <PrDetailActions detail={detail.data()} />+ <div class="shrink-0">+ <SplitFileMenu+ id={props.foreignEntityId}+ itemType="foreign"+ name={name()}+ entityKind="pr"+ permissions={Permissions.CAN_VIEW}+ ops={operations()}+ />+ </div>+ <PrDetailActions detail={detail.data()} actions={actions} /></ViewShell.TopBar><PrDetailContentforeignEntityId={props.foreignEntityId}diff --git a/apps/web/src/features/block-project/component/TopBar.tsx b/apps/web/src/features/block-project/component/TopBar.tsxindex d2ea09aeab..6910ce81fa 100644--- a/apps/web/src/features/block-project/component/TopBar.tsx+++ b/apps/web/src/features/block-project/component/TopBar.tsx@@ -76,6 +76,7 @@ export function TopBar() {...(isOwner() && !isSpecialProject? [{ op: 'rename' as const },+ { op: 'copy' as const },{ op: 'moveToProject' as const },{ op: 'delete' as const },]diff --git a/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx b/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsxindex 50b27f4c40..698ac01334 100644--- a/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx+++ b/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx@@ -37,11 +37,15 @@ import { getDisplayName, tryMacroId } from '@core/user';import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';import { downloadFile } from '@filesystem/download';import IconShared from '@icon/share.svg';+import DownloadSimple from '@icon/system/regular/download-simple.svg';+import FileCsv from '@icon/system/regular/file-csv.svg';+import FileXls from '@icon/system/regular/file-xls.svg';import { Badge } from '@ui';-import { onMount, Show } from 'solid-js';+import { onCleanup, onMount, Show } from 'solid-js';import { spreadsheetChatContext } from './core/chat-context';import { clipboardTargetInScope } from './core/clipboard-scope';import type { SpreadsheetData } from './definition';+import { createSpreadsheetDownload } from './primitives/create-spreadsheet-download';import { createSpreadsheetStore } from './primitives/create-spreadsheet-store';import { useSpreadsheetAccess } from './primitives/use-spreadsheet-access';import { createSpreadsheetSession } from './queries/spreadsheet-session';@@ -109,6 +113,7 @@ function SpreadsheetBlockContent(props: { share?: string }) {| undefined;return value?.__block === 'spreadsheet' ? value : undefined;};+ const sheetDownload = createSpreadsheetDownload();return (<DocumentBlockContainer>@@ -136,6 +141,23 @@ function SpreadsheetBlockContent(props: { share?: string }) {{ op: 'rename' },{ op: 'copy' },{ op: 'moveToProject' },+ {+ group: 'file',+ label: 'Download',+ icon: DownloadSimple,+ children: [+ {+ label: 'Download as Excel (.xlsx)',+ icon: FileXls,+ action: () => sheetDownload.download('xlsx'),+ },+ {+ label: 'Download as CSV',+ icon: FileCsv,+ action: () => sheetDownload.download('csv'),+ },+ ],+ },{ op: 'delete' },]}tools={[@@ -151,6 +173,7 @@ function SpreadsheetBlockContent(props: { share?: string }) {/><Show when={data()?.syncSource} keyed>{(syncSource) => {+ onCleanup(sheetDownload.clear);const source = createSpreadsheetSession({documentId,userId: userId(),@@ -202,6 +225,7 @@ function SpreadsheetBlockContent(props: { share?: string }) {mentions={spreadsheetMentions}store={store}name={name()}+ onDownloadReady={sheetDownload.register}onExportXlsx={(bytes) =>downloadFile(new Blob([bytes.slice().buffer], {diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-download.ts b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-download.tsnew file mode 100644index 0000000000..32b4e050a7--- /dev/null+++ b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-download.ts@@ -0,0 +1,28 @@+import { toast } from '@core/component/Toast/Toast';+import { createSignal } from 'solid-js';++export type SpreadsheetDownloadFormat = 'xlsx' | 'csv';++type SpreadsheetDownload = (format: SpreadsheetDownloadFormat) => boolean;++/**+ * The editor toolbar's downloads, offered outside it (the file menu). The+ * mounted editor registers them; until it has, or while the sheet can't be+ * exported, asking says so instead of doing nothing.+ */+export function createSpreadsheetDownload() {+ const [registered, setRegistered] = createSignal<SpreadsheetDownload>();++ const download = (format: SpreadsheetDownloadFormat) => {+ if (registered()?.(format)) return;+ toast.failure(+ "The spreadsheet isn't ready to download yet. Try again in a moment."+ );+ };++ return {+ register: (run: SpreadsheetDownload) => setRegistered(() => run),+ clear: () => setRegistered(undefined),+ download,+ };+}diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsxindex e5a36ac4f7..8a3cee37cf 100644--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx@@ -97,6 +97,7 @@ import { createGoalSeek } from '../primitives/create-goal-seek';import { createGridController } from '../primitives/create-grid-controller';import { createRangeMove } from '../primitives/create-range-move';import { createSheetActions } from '../primitives/create-sheet-actions';+import type { SpreadsheetDownloadFormat } from '../primitives/create-spreadsheet-download';import type { SpreadsheetStore } from '../primitives/create-spreadsheet-store';import { createTableActions } from '../primitives/create-table-actions';import { createWorkbookActions } from '../primitives/create-workbook-actions';@@ -115,6 +116,13 @@ export function SpreadsheetEditor(props: {ownsClipboard?: (event: ClipboardEvent) => boolean;onExport: (content: string) => void;onExportXlsx: (bytes: Uint8Array) => void;+ /**+ * Hands the toolbar's downloads to actions outside it, such as the file+ * menu. The function returns false while the sheet can't be exported yet.+ */+ onDownloadReady?: (+ download: (format: SpreadsheetDownloadFormat) => boolean+ ) => void;}) {let gridElement: HTMLDivElement | undefined;let editorElement!: HTMLElement;@@ -538,6 +546,17 @@ export function SpreadsheetEditor(props: {editor.setSelectionRange(editor.value.length, editor.value.length);} else focusGrid();};+ const canExport = () =>+ props.store.ready() &&+ !calculation.busy() &&+ !calculation.error() &&+ !grid.editing() &&+ !workbookActions.busy();+ props.onDownloadReady?.((format) => {+ if (!canExport()) return false;+ command(format === 'xlsx' ? 'export-xlsx' : 'export-csv');+ return true;+ });const menuCommand = (action: SpreadsheetCommand) => {// Create a new focus owner only after the menu's focus trap has closed.if (@@ -1446,13 +1465,7 @@ export function SpreadsheetEditor(props: {readonly={!editable() || actions.pending() || !!workbookActions.busy()}- canExport={- props.store.ready() &&- !calculation.busy() &&- !calculation.error() &&- !grid.editing() &&- !workbookActions.busy()- }+ canExport={canExport()}onCommand={menuCommand}onRestoreFocus={restoreEditorFocus}/>diff --git a/apps/web/src/features/block-write/DocxBlock.tsx b/apps/web/src/features/block-write/DocxBlock.tsxindex 12972c2a20..cc8ed6f258 100644--- a/apps/web/src/features/block-write/DocxBlock.tsx+++ b/apps/web/src/features/block-write/DocxBlock.tsx@@ -29,12 +29,14 @@ import {} from '@core/signal/permissions';import { getDisplayName, tryMacroId } from '@core/user';import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';-import { downloadFile } from '@filesystem/download';+import { fireAndForget } from '@core/util/fireAndForget';import IconShared from '@icon/share.svg';+import DownloadSimple from '@icon/system/regular/download-simple.svg';import { useMessageRootsQuery } from '@queries/messages/document-messages';import { Badge } from '@ui';-import { createMemo, Match, onMount, Show, Switch } from 'solid-js';+import { createMemo, Match, onCleanup, onMount, Show, Switch } from 'solid-js';import type { DocxBlockData } from './definition';+import { createDocxDownload } from './primitives/create-docx-download';import {buildDocxSeed,connectDocxSync,@@ -46,9 +48,6 @@ import { createDocxSession } from './queries/docx-session';import { DocxCommentMargin, DocxDetachedComments } from './views/DocxComments';import { DocxEditorView } from './views/DocxEditorView';-const DOCX_MIME =- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';-function displayName(userId: string | undefined) {return getDisplayName(tryMacroId(userId ?? ''), {emailFallback: 'local-part',@@ -97,6 +96,11 @@ export default function DocxBlock(props: { share?: string }) {error instanceof Error ? error.message : 'Something went wrong');};+ const docxDownload = createDocxDownload({+ documentId,+ fileName,+ onError: reportError,+ });return (<DocumentBlockContainer>@@ -135,6 +139,13 @@ export default function DocxBlock(props: { share?: string }) {{ op: 'rename' },{ op: 'copy' },{ op: 'moveToProject' },+ {+ group: 'file',+ label: 'Download',+ icon: DownloadSimple,+ action: () =>+ fireAndForget(docxDownload.download(), 'docx-download'),+ },{ op: 'delete' },]}tools={[@@ -198,58 +209,60 @@ export default function DocxBlock(props: { share?: string }) {</div></Match><Match when={target()} keyed>- {({ doc, original }) => (- <DocxEditorView- doc={doc}- original={original}- canEdit={!!doc && canEdit()}- canComment={() => !!doc && canComment()}- fileName={fileName()}- peers={session.peers}- displayName={displayName}- author={displayName(userId())}- documentId={documentId}- onSelection={session.setSelection}- commentRoots={doc ? rootThreads : undefined}- margin={(context) => (- <DocxCommentMargin- documentId={documentId}- comments={context.comments}- geometry={context.geometry}- selectionTop={context.selectionTop}- canComment={() => !!doc && canComment()}- isOwner={isOwner}- userId={userId}- />- )}- footer={(comments) => (- <>- <DocxDetachedComments+ {({ doc, original }) => {+ onCleanup(() => docxDownload.setEditor(undefined));+ return (+ <DocxEditorView+ doc={doc}+ original={original}+ canEdit={!!doc && canEdit()}+ canComment={() => !!doc && canComment()}+ fileName={fileName()}+ peers={session.peers}+ displayName={displayName}+ author={displayName(userId())}+ documentId={documentId}+ onSelection={session.setSelection}+ commentRoots={doc ? rootThreads : undefined}+ margin={(context) => (+ <DocxCommentMargindocumentId={documentId}- threads={comments.detached()}- canComment={canComment}+ comments={context.comments}+ geometry={context.geometry}+ selectionTop={context.selectionTop}+ canComment={() => !!doc && canComment()}isOwner={isOwner}+ userId={userId}/>- <EntityDiscussion- parent={parent()}- canWrite={canComment()}- canModerate={isOwner()}- link={{ type: 'write', id: documentId }}- label="Discussion"- />- </>- )}- onDownload={(bytes) =>- downloadFile(- new Blob([bytes.slice().buffer], {- type: DOCX_MIME,- }),- fileName()- )- }- onError={reportError}- />- )}+ )}+ footer={(comments) => (+ <>+ <DocxDetachedComments+ documentId={documentId}+ threads={comments.detached()}+ canComment={canComment}+ isOwner={isOwner}+ />+ <EntityDiscussion+ parent={parent()}+ canWrite={canComment()}+ canModerate={isOwner()}+ link={{ type: 'write', id: documentId }}+ label="Discussion"+ />+ </>+ )}+ onDownload={(bytes) =>+ fireAndForget(+ docxDownload.save(bytes),+ 'docx-download'+ )+ }+ onError={reportError}+ onReady={docxDownload.setEditor}+ />+ );+ }}</Match></Switch>);diff --git a/apps/web/src/features/block-write/primitives/create-docx-download.test.ts b/apps/web/src/features/block-write/primitives/create-docx-download.test.tsnew file mode 100644index 0000000000..847e1ed725--- /dev/null+++ b/apps/web/src/features/block-write/primitives/create-docx-download.test.ts@@ -0,0 +1,86 @@+import { createRoot } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ downloadFile: vi.fn(async (_blob: Blob, _name: string) => ({ saved: true })),+ downloadExportedDocument: vi.fn(async () => new Uint8Array([9])),+}));+vi.mock('@filesystem/download', () => ({ downloadFile: mocks.downloadFile }));+vi.mock('@service-storage/util/downloadExportedDocument', () => ({+ downloadExportedDocument: mocks.downloadExportedDocument,+}));++import { createDocxDownload } from './create-docx-download';+import type { DocxEditor } from './create-docx-editor';++const savedBlob = () =>+ mocks.downloadFile.mock.calls.at(-1)?.[0] as unknown as Blob;++const setup = () =>+ createRoot(() =>+ createDocxDownload({+ documentId: 'doc-1',+ fileName: () => 'Plan.docx',+ onError: vi.fn(),+ })+ );++describe('createDocxDownload', () => {+ it('saves the mounted editor once its edits have synced', async () => {+ const order: string[] = [];+ const editor = {+ idle: async () => {+ order.push('idle');+ },+ save: async () => {+ order.push('save');+ return new Uint8Array([1, 2]);+ },+ } as unknown as DocxEditor;+ const download = setup();+ download.setEditor(editor);++ await download.download();++ expect(order).toEqual(['idle', 'save']);+ expect(mocks.downloadExportedDocument).not.toHaveBeenCalled();+ expect(savedBlob().size).toBe(2);+ expect(savedBlob().type).toBe(+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'+ );+ expect(mocks.downloadFile.mock.calls.at(-1)?.[1]).toBe('Plan.docx');+ });++ it("falls back to the server's export before the editor mounts", async () => {+ const download = setup();++ await download.download();++ expect(mocks.downloadExportedDocument).toHaveBeenCalledWith({+ documentId: 'doc-1',+ });+ expect(savedBlob().size).toBe(1);+ });++ it('reports a failed save instead of rejecting', async () => {+ const onError = vi.fn();+ const failure = new Error('save failed');+ const download = createRoot(() =>+ createDocxDownload({+ documentId: 'doc-1',+ fileName: () => 'Plan.docx',+ onError,+ })+ );+ download.setEditor({+ idle: async () => {},+ save: async () => {+ throw failure;+ },+ } as unknown as DocxEditor);++ await download.download();++ expect(onError).toHaveBeenCalledWith(failure);+ });+});diff --git a/apps/web/src/features/block-write/primitives/create-docx-download.ts b/apps/web/src/features/block-write/primitives/create-docx-download.tsnew file mode 100644index 0000000000..1328c4cf3f--- /dev/null+++ b/apps/web/src/features/block-write/primitives/create-docx-download.ts@@ -0,0 +1,44 @@+import { downloadFile } from '@filesystem/download';+import { downloadExportedDocument } from '@service-storage/util/downloadExportedDocument';+import { createSignal } from 'solid-js';+import type { DocxEditor } from './create-docx-editor';++const DOCX_MIME =+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';++/**+ * Saving a Word document as a `.docx`, for the editor toolbar and the file+ * menu alike. The mounted editor saves its live state, unsynced edits+ * included; before it mounts, the server's export is the latest copy.+ */+export function createDocxDownload(options: {+ documentId: string;+ fileName: () => string;+ onError: (error: unknown) => void;+}) {+ const [editor, setEditor] = createSignal<DocxEditor>();++ const save = (bytes: Uint8Array) =>+ downloadFile(+ new Blob([bytes.slice().buffer], { type: DOCX_MIME }),+ options.fileName()+ );++ const download = async () => {+ const current = editor();+ try {+ if (current) {+ await current.idle();+ await save(await current.save());+ } else {+ await save(+ await downloadExportedDocument({ documentId: options.documentId })+ );+ }+ } catch (error) {+ options.onError(error);+ }+ };++ return { setEditor, save, download };+}diff --git a/apps/web/src/features/block-write/views/DocxEditorView.tsx b/apps/web/src/features/block-write/views/DocxEditorView.tsxindex ca433bdc13..b3f4cbbc67 100644--- a/apps/web/src/features/block-write/views/DocxEditorView.tsx+++ b/apps/web/src/features/block-write/views/DocxEditorView.tsx@@ -75,7 +75,7 @@ export type DocxEditorViewProps = {footer?: (comments: DocxComments) => JSX.Element;onDownload: (bytes: Uint8Array) => void;onError?: (error: unknown) => void;- /** Test hook: the mounted editor. */+ /** The mounted editor, for actions outside its toolbar (file menu Download). */onReady?: (editor: DocxEditor) => void;};diff --git a/apps/web/src/features/drive-view/components/DriveBreadcrumbs.tsx b/apps/web/src/features/drive-view/components/DriveBreadcrumbs.tsxindex 44040605e2..2f99e38aa9 100644--- a/apps/web/src/features/drive-view/components/DriveBreadcrumbs.tsx+++ b/apps/web/src/features/drive-view/components/DriveBreadcrumbs.tsx@@ -47,6 +47,7 @@ function FolderBreadcrumbMenu(props: {group: 'sharing',},{ op: 'rename' },+ { op: 'copy' },{ op: 'moveToProject' },{ op: 'delete' },];diff --git a/apps/web/src/features/drive-view/drive-folder-actions.tsx b/apps/web/src/features/drive-view/drive-folder-actions.tsxindex ff6f5e73cf..d21a33405b 100644--- a/apps/web/src/features/drive-view/drive-folder-actions.tsx+++ b/apps/web/src/features/drive-view/drive-folder-actions.tsx@@ -1,10 +1,15 @@import { openBulkEditModal } from '@app/features/entity/bulk-edit/BulkEditEntityModal';import {+ makeCopyAction,+ makeCopyEntityIdAction,makeCopyLinkAction,makeDeleteAction,makeFavoriteAction,+ makeMuteAction,+ makeShareAction,} from '@app/features/next-soup/actions';import { t } from '@app/lib/i18n';+import { useGlobalNotificationSource } from '@components/app/GlobalAppState';import { MenuItem, MenuSeparator } from '@core/component/ContextMenu';import { toast } from '@core/component/Toast/Toast';import { useUserId } from '@core/context/user';@@ -29,6 +34,13 @@ export function DriveFolderActions(props: { folder: DriveFolderMetadata }) {const favorite = makeFavoriteAction();const copyLink = makeCopyLinkAction();+ const copyEntityId = makeCopyEntityIdAction();+ const duplicate = makeCopyAction();+ const share = makeShareAction();+ const notificationSource = useGlobalNotificationSource();+ const mute = makeMuteAction({+ notificationSource: () => notificationSource,+ });const deleteFolder = makeDeleteAction({userId,@@ -73,16 +85,50 @@ export function DriveFolderActions(props: { folder: DriveFolderMetadata }) {fireAndForget(favorite.execute([entity()]), 'drive-view')}/>- <MenuItem- text={t('entityActions.moveToFolder')}- onClick={() => editFolder('moveToProject')}- />+ <Show when={mute.canExecute(entity())}>+ <MenuItem+ text={t('entityActions.snoozeNotifications')}+ onClick={() => mute.snooze([entity()])}+ />+ <MenuItem+ text={+ mute.isMuted(entity())+ ? t('entityActions.unmuteNotifications')+ : t('entityActions.muteNotifications')+ }+ onClick={() => fireAndForget(mute.execute([entity()]), 'drive-view')}+ />+ </Show>+ <Show when={entity().ownerId === userId()}>+ <MenuItem+ text={t('entityActions.moveToFolder')}+ onClick={() => editFolder('moveToProject')}+ />+ </Show>+ <Show when={duplicate.canExecute(entity())}>+ <MenuItem+ text={t('entityActions.duplicate')}+ onClick={() =>+ fireAndForget(duplicate.execute([entity()]), 'drive-view')+ }+ />+ </Show><MenuItemtext={t('entityActions.copyLink')}onClick={() =>fireAndForget(copyLink.execute([entity()]), 'drive-view')}/>+ <MenuItem+ text={t('entityActions.copyId')}+ onClick={() =>+ fireAndForget(copyEntityId.executeById(entity().id), 'drive-view')+ }+ />+ <MenuItem+ text={t('entityActions.share')}+ onClick={() => fireAndForget(share.execute(entity()), 'drive-view')}+ /><Show when={deleteFolder.canExecute(entity())}><MenuSeparator /><MenuItemdiff --git a/apps/web/src/features/drive-view/queries/drive-sidebar-source.ts b/apps/web/src/features/drive-view/queries/drive-sidebar-source.tsindex 354ee5574a..1174b051af 100644--- a/apps/web/src/features/drive-view/queries/drive-sidebar-source.ts+++ b/apps/web/src/features/drive-view/queries/drive-sidebar-source.ts@@ -34,6 +34,8 @@ function createSidebarFavorites() {.filter((favorite) =>favorite.entityType === 'project' ||+ favorite.entityType === 'database' ||+ favorite.entityType === 'form' ||(favorite.entityType === 'document' &&favorite.documentSubType !== 'task'))diff --git a/apps/web/src/features/drive-view/views/drive-list.tsx b/apps/web/src/features/drive-view/views/drive-list.tsxindex 5b205e94d1..a5b35383b5 100644--- a/apps/web/src/features/drive-view/views/drive-list.tsx+++ b/apps/web/src/features/drive-view/views/drive-list.tsx@@ -94,6 +94,11 @@ export function DriveList() {list.selection.items().map((row) => row.entity));+ const viewedFolderId = () => {+ const { location } = state.value();+ return location.kind === 'folder' ? (location.id ?? undefined) : undefined;+ };+const actionContext = () =>resolveEntityActionViewContext({activeListView: 'documents',@@ -412,6 +417,7 @@ export function DriveList() {list={actionState}selectedEntities={selected}viewContext={actionContext()}+ viewedProjectId={viewedFolderId()}onOpenChange={(open) => {if (!open) return;diff --git a/apps/web/src/features/entity/queries/dss.test.tsx b/apps/web/src/features/entity/queries/dss.test.tsxindex 88b91ce31e..29e71b324e 100644--- a/apps/web/src/features/entity/queries/dss.test.tsx+++ b/apps/web/src/features/entity/queries/dss.test.tsx@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => ({vi.mock('@core/component/FileList/itemOperations', () => ({deleteItem: mocks.deleteItem,copyItem: mocks.copyItem,+ canDuplicateItemType: () => true,moveToFolder: mocks.moveToFolder,}));vi.mock('@core/component/Toast/Toast', () => ({diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.tsindex d1b8b048e0..f08dfa3bba 100644--- a/apps/web/src/features/entity/queries/dss.ts+++ b/apps/web/src/features/entity/queries/dss.ts@@ -2,6 +2,7 @@import { scheduledActionKeys } from '@app/features/routines/queries/keys';import {+ canDuplicateItemType,copyItem,deleteItem,moveToFolder,@@ -401,11 +402,11 @@ function getSoupEntityProjectId(entityId: string): string | undefined {}export function createBulkCopyDssEntityMutation() {- // Only support chat + document, same as single-copy version- const isUnsupportedEntity = (entity: EntityData) => {- const type = entity.type;- return type !== 'chat' && type !== 'document';- };+ const isUnsupportedEntity = (entity: EntityData) =>+ (entity.type !== 'chat' &&+ entity.type !== 'document' &&+ entity.type !== 'project') ||+ !canDuplicateItemType(entity.type);return useMutation(() => ({mutationFn: async ({@@ -422,7 +423,7 @@ export function createBulkCopyDssEntityMutation() {const results = await Promise.all(entities.map((e) =>copyItem({- itemType: e.type as 'document' | 'chat',+ itemType: e.type,id: e.id,name: typeof name === 'function' ? name(e.name) : name,})@@ -448,8 +449,8 @@ export function createBulkCopyDssEntityMutation() {onSettled: (data, error, { entities }) => {if (error) {+ // The copy action shows the failure, with the folder-size hint.console.error(`Failed bulk copy`, entities, data, error);- toast.failure('Failed to copy items');}// Trigger refetch so new items appeardiff --git a/apps/web/src/features/home/components/HomeList.tsx b/apps/web/src/features/home/components/HomeList.tsxindex 29640ea6d3..b7baab39c9 100644--- a/apps/web/src/features/home/components/HomeList.tsx+++ b/apps/web/src/features/home/components/HomeList.tsx@@ -653,6 +653,9 @@ export function HomeList(props: HomeListProps) {selectedEntities={selectedEntities}viewContext={entityActionViewContext()}markDoneDelegate={source.markDoneDelegate}+ createActionNavigationHandler={+ createActionNavigationHandler+ }onOpenChange={(open) => {if (!open) return;focusActionRow({diff --git a/apps/web/src/features/next-soup/actions/entity-action-context.test.ts b/apps/web/src/features/next-soup/actions/entity-action-context.test.tsindex 4c4371ae18..5e10310bf6 100644--- a/apps/web/src/features/next-soup/actions/entity-action-context.test.ts+++ b/apps/web/src/features/next-soup/actions/entity-action-context.test.ts@@ -7,7 +7,11 @@ vi.mock('./make-mark-done-action', () => ({canExecuteMarkDoneOnView: () => true,}));-import { toSingleEntityActionListState } from './entity-action-context';+import {+ emailSenderBucket,+ resolveEntityActionViewContext,+ toSingleEntityActionListState,+} from './entity-action-context';const channel: EntityData = {id: 'channel',@@ -47,3 +51,44 @@ describe('toSingleEntityActionListState', () => {});});});++describe('resolveEntityActionViewContext sender bucket', () => {+ const bucket = (activeListView: string, activeTab: string | undefined) =>+ resolveEntityActionViewContext({ activeListView, activeTab }).senderBucket;++ it('follows the Signal and Noise tabs', () => {+ expect(bucket('mail', 'important')).toBe('signal');+ expect(bucket('home', 'signal')).toBe('signal');+ expect(bucket('home', 'noise')).toBe('noise');+ });++ it('has none for views without those tabs', () => {+ expect(bucket('search', 'all')).toBeUndefined();+ expect(bucket('project-1', undefined)).toBeUndefined();+ });+});++describe('emailSenderBucket', () => {+ const email = (isSignal?: boolean) =>+ ({+ type: 'email',+ id: 't1',+ name: 'Thread',+ ownerId: 'owner',+ isRead: true,+ isDraft: false,+ isImportant: false,+ done: false,+ isSignal,+ }) as EntityData;++ it("reads an email's own Signal or Noise placement", () => {+ expect(emailSenderBucket(email(true))).toBe('signal');+ expect(emailSenderBucket(email(false))).toBe('noise');+ });++ it('is unknown when the server did not say, or for other rows', () => {+ expect(emailSenderBucket(email())).toBeUndefined();+ expect(emailSenderBucket(channel)).toBeUndefined();+ });+});diff --git a/apps/web/src/features/next-soup/actions/entity-action-context.ts b/apps/web/src/features/next-soup/actions/entity-action-context.tsindex 0543b3730e..8682065782 100644--- a/apps/web/src/features/next-soup/actions/entity-action-context.ts+++ b/apps/web/src/features/next-soup/actions/entity-action-context.ts@@ -63,19 +63,23 @@ type AdaptedRow = {entity: EntityData;};+/** The Signal or Noise bucket an email is in, when the server said. */+export function emailSenderBucket(+ entity: EntityData | undefined+): EntityActionSenderBucket | undefined {+ if (entity?.type !== 'email' || entity.isSignal === undefined) return;+ return entity.isSignal ? 'signal' : 'noise';+}++/**+ * The sender bucket a view's tab shows. Views without a Signal or Noise tab+ * (Search, folders, Recent) have none, so their rows offer no sender moves.+ */function resolveSenderBucket(activeTab: string | undefined): EntityActionSenderBucket | undefined {if (activeTab === 'noise') return 'noise';-- if (- activeTab === undefined ||- activeTab === 'signal' ||- activeTab === 'important'- ) {- return 'signal';- }-+ if (activeTab === 'signal' || activeTab === 'important') return 'signal';return undefined;}diff --git a/apps/web/src/features/next-soup/actions/index.ts b/apps/web/src/features/next-soup/actions/index.tsindex 52731ae369..3cc235b0ed 100644--- a/apps/web/src/features/next-soup/actions/index.ts+++ b/apps/web/src/features/next-soup/actions/index.ts@@ -5,12 +5,14 @@ export {type EntityActionNavigationHandler,type EntityActionSenderBucket,type EntityActionViewContext,+ emailSenderBucket,resolveEntityActionViewContext,type ToEntityActionListStateOptions,toEntityActionListState,toSingleEntityActionListState,} from './entity-action-context';export { makeAddTagAction } from './make-add-tag-action';+export { makeArchiveSessionAction } from './make-archive-session-action';export { makeBlockSenderAction } from './make-block-sender-action';export { makeChannelPictureAction } from './make-channel-picture-action';export { makeCopyAction } from './make-copy-action';@@ -19,7 +21,9 @@ export { makeCopyEntityIdAction } from './make-copy-entity-id-action';export { makeCopyLinkAction } from './make-copy-link-action';export { makeCreateReminderAction } from './make-create-reminder-action';export { makeDeleteAction } from './make-delete-action';+export { makeDownloadAction } from './make-download-action';export { makeFavoriteAction } from './make-favorite-action';+export { makeGithubLinkAction } from './make-github-link-action';export { makeHideCompanyAction } from './make-hide-company-action';export { makeMarkDoneAction } from './make-mark-done-action';export { makeMarkNotDoneAction } from './make-mark-not-done-action';diff --git a/apps/web/src/features/next-soup/actions/make-archive-session-action.test.ts b/apps/web/src/features/next-soup/actions/make-archive-session-action.test.tsnew file mode 100644index 0000000000..57151c7cd2--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-archive-session-action.test.ts@@ -0,0 +1,45 @@+import type { EntityData } from '@entity';+import { describe, expect, it, vi } from 'vitest';++const archive = vi.hoisted(() => vi.fn(async () => true));+vi.mock(+ '@app/features/block-agent/queries/change-session-archive-state',+ () => ({+ changeSessionArchiveState: archive,+ })+);++import { makeArchiveSessionAction } from './make-archive-session-action';++const ME = 'macro|[email protected]';++const session = (overrides: Partial<EntityData> = {}) =>+ ({+ type: 'agent_session',+ id: 's1',+ name: 'Session',+ ownerId: ME,+ ...overrides,+ }) as EntityData;++const action = makeArchiveSessionAction({ userId: () => ME });++describe('makeArchiveSessionAction', () => {+ it('offers archiving only to the session owner', () => {+ expect(action.canExecute(session())).toBe(true);+ expect(action.canExecute(session({ ownerId: 'macro|other' }))).toBe(false);+ expect(+ action.canExecute({ ...session(), type: 'chat' } as EntityData)+ ).toBe(false);+ });++ it('archives an active session and unarchives an archived one', async () => {+ await action.execute([session()]);+ expect(archive).toHaveBeenLastCalledWith('s1', true);++ await action.execute([+ session({ isArchived: true } as Partial<EntityData>),+ ]);+ expect(archive).toHaveBeenLastCalledWith('s1', false);+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-archive-session-action.ts b/apps/web/src/features/next-soup/actions/make-archive-session-action.tsnew file mode 100644index 0000000000..dac3588105--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-archive-session-action.ts@@ -0,0 +1,25 @@+import { changeSessionArchiveState } from '@app/features/block-agent/queries/change-session-archive-state';+import type { EntityData } from '@entity';++type MakeArchiveSessionOptions = {+ userId: () => string | undefined;+};++/** Archive or unarchive an agent session; only its owner may. */+export const makeArchiveSessionAction = (+ options: MakeArchiveSessionOptions+) => {+ const canExecute = (entity: EntityData): boolean =>+ entity.type === 'agent_session' && entity.ownerId === options.userId();++ const isArchived = (entity: EntityData): boolean =>+ entity.type === 'agent_session' && entity.isArchived === true;++ const execute = async (entities: EntityData[]) => {+ const entity = entities[0];+ if (!entity || !canExecute(entity)) return;+ await changeSessionArchiveState(entity.id, !isArchived(entity));+ };++ return { canExecute, isArchived, execute };+};diff --git a/apps/web/src/features/next-soup/actions/make-copy-action.test.ts b/apps/web/src/features/next-soup/actions/make-copy-action.test.tsnew file mode 100644index 0000000000..4e50da58fa--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-copy-action.test.ts@@ -0,0 +1,40 @@+import type { EntityData } from '@entity';+import { describe, expect, it, vi } from 'vitest';++const flags = vi.hoisted(() => ({ graphqlSoup: false }));+vi.mock('@core/constant/featureFlags', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ isFeatureEnabled: () => flags.graphqlSoup,+}));+vi.mock('@entity', () => ({+ createBulkCopyDssEntityMutation: () => ({ mutateAsync: vi.fn() }),+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: vi.fn(), dismiss: vi.fn() },+}));++import { makeCopyAction } from './make-copy-action';++const entity = (type: EntityData['type']) =>+ ({ type, id: 'e1', name: 'Thing', ownerId: 'macro|me' }) as EntityData;++const { canExecute } = makeCopyAction();++describe('makeCopyAction.canExecute', () => {+ it('offers duplicating documents and chats', () => {+ expect(canExecute(entity('document'))).toBe(true);+ expect(canExecute(entity('chat'))).toBe(true);+ });++ it('duplicates folders only through the GraphQL entity mutation', () => {+ flags.graphqlSoup = true;+ expect(canExecute(entity('project'))).toBe(true);+ flags.graphqlSoup = false;+ expect(canExecute(entity('project'))).toBe(false);+ });++ it('refuses types the copy mutation rejects', () => {+ expect(canExecute(entity('call'))).toBe(false);+ expect(canExecute(entity('calendar_event'))).toBe(false);+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-copy-action.ts b/apps/web/src/features/next-soup/actions/make-copy-action.tsindex dcbe6b3728..6fd619d3ba 100644--- a/apps/web/src/features/next-soup/actions/make-copy-action.ts+++ b/apps/web/src/features/next-soup/actions/make-copy-action.ts@@ -1,4 +1,5 @@import { t } from '@app/lib/i18n';+import { canDuplicateItemType } from '@core/component/FileList/itemOperations';import { toast } from '@core/component/Toast/Toast';import type { EntityData } from '@entity';import { createBulkCopyDssEntityMutation } from '@entity';@@ -7,25 +8,28 @@ import type { EntityActionListState } from './entity-action-context';export const makeCopyAction = () => {const bulkCopyMutation = createBulkCopyDssEntityMutation();- const canExecute = (entity: EntityData): boolean => {- return (- entity.type !== 'database' &&- entity.type !== 'form' &&- entity.type !== 'agent_session' &&- entity.type !== 'channel' &&- entity.type !== 'email' &&- entity.type !== 'channel_message' &&- entity.type !== 'channel_thread' &&- entity.type !== 'foreign' &&- entity.type !== 'routine'- );- };+ // The types the copy mutation duplicates; it rejects any other.+ const canExecute = (entity: EntityData): boolean =>+ (entity.type === 'document' ||+ entity.type === 'chat' ||+ entity.type === 'project') &&+ canDuplicateItemType(entity.type);const execute = async (entities: EntityData[]) => {- await bulkCopyMutation.mutateAsync({- entities,- name: (name) => name,- });+ try {+ await bulkCopyMutation.mutateAsync({+ entities,+ name: (name) => name,+ });+ } catch {+ toast.failure(+ t('entityActions.toastCopyFailed', { count: entities.length }),+ entities.some((entity) => entity.type === 'project')+ ? { subtext: t('entityActions.folderDuplicateLimitHint') }+ : undefined+ );+ return;+ }toast.success(entities.length > 1? t('entityActions.toastCopiedCount', { count: entities.length })diff --git a/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.test.ts b/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.test.tsnew file mode 100644index 0000000000..2f0c94fc95--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.test.ts@@ -0,0 +1,60 @@+import type { EntityData } from '@entity';+import { afterEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ copyTaskBranch: vi.fn(async () => {}),+ success: vi.fn(),+}));+vi.mock('@core/util/branchName', () => ({+ copyBranchNameToClipboard: mocks.copyTaskBranch,+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: mocks.success, failure: vi.fn() },+}));++import { makeCopyBranchNameAction } from './make-copy-branch-name-action';++const pullRequest = (headBranch?: string) =>+ ({+ type: 'foreign',+ foreignSource: 'github_pull_request',+ id: 'pr-1',+ name: 'Fix reply state',+ ownerId: '',+ metadata: { url: 'https://github.com/o/r/pull/1', headBranch },+ }) as unknown as EntityData;++const task = {+ type: 'document',+ fileType: 'md',+ subType: { type: 'task', is_completed: false },+ id: 'task-1',+ name: 'Task',+ ownerId: '',+} as EntityData;++const writeText = vi.fn(async () => {});+Object.assign(navigator, { clipboard: { writeText } });++afterEach(() => vi.clearAllMocks());++describe('makeCopyBranchNameAction', () => {+ const action = makeCopyBranchNameAction();++ it("copies a pull request's head branch", async () => {+ expect(action.canExecute(pullRequest('fix/reply-state'))).toBe(true);+ await action.execute([pullRequest('fix/reply-state')]);+ expect(writeText).toHaveBeenCalledWith('fix/reply-state');+ expect(mocks.copyTaskBranch).not.toHaveBeenCalled();+ });++ it('skips a pull request whose branch was not stored', () => {+ expect(action.canExecute(pullRequest())).toBe(false);+ });++ it("still copies a task's derived branch name", async () => {+ expect(action.canExecute(task)).toBe(true);+ await action.execute([task]);+ expect(mocks.copyTaskBranch).toHaveBeenCalledWith('task-1');+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts b/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.tsindex cd6b205b86..c83bbbb113 100644--- a/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts+++ b/apps/web/src/features/next-soup/actions/make-copy-branch-name-action.ts@@ -1,15 +1,30 @@+import { t } from '@app/lib/i18n';+import { toast } from '@core/component/Toast/Toast';import { copyBranchNameToClipboard } from '@core/util/branchName';-import { type EntityData, isTaskEntity } from '@entity';+import { type EntityData, isGithubPrEntity, isTaskEntity } from '@entity';import type { EntityActionListState } from './entity-action-context';+/**+ * Copy the branch to work on: a task's derived branch name, or the branch a+ * pull request was opened from, when it was stored.+ */export const makeCopyBranchNameAction = () => {const canExecute = (entity: EntityData): boolean => {+ if (isGithubPrEntity(entity)) return !!entity.metadata.headBranch;return isTaskEntity(entity);};const execute = async (entities: EntityData[]) => {const entity = entities[0];- if (!entity || !isTaskEntity(entity)) return;+ if (!entity) return;+ if (isGithubPrEntity(entity)) {+ const branch = entity.metadata.headBranch;+ if (!branch) return;+ await navigator.clipboard.writeText(branch);+ toast.success(t('entityActions.toastBranchNameCopied'));+ return;+ }+ if (!isTaskEntity(entity)) return;await copyBranchNameToClipboard(entity.id);};diff --git a/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts b/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.tsindex 96b41127a2..643f087549 100644--- a/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts+++ b/apps/web/src/features/next-soup/actions/make-copy-entity-id-action.ts@@ -4,9 +4,10 @@ import type { EntityData } from '@entity';import type { EntityActionListState } from './entity-action-context';export const makeCopyEntityIdAction = () => {- const canExecute = (_entity: EntityData): boolean => {- return true;- };+ // A channel message or thread row's id joins its channel's and its own, so+ // it names nothing a user can look up.+ const canExecute = (entity: EntityData): boolean =>+ entity.type !== 'channel_message' && entity.type !== 'channel_thread';/** Copying an id needs nothing but the id, so callers that only have one* (e.g. a block, which is keyed by its entity id) can skip resolving thediff --git a/apps/web/src/features/next-soup/actions/make-delete-action.test.ts b/apps/web/src/features/next-soup/actions/make-delete-action.test.tsindex ceceb4a30c..d20c1aaad3 100644--- a/apps/web/src/features/next-soup/actions/make-delete-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-delete-action.test.ts@@ -491,4 +491,12 @@ describe('makeDeleteAction.canExecute', () => {expect(canExecute(entity('channel_message'))).toBe(false);expect(canExecute(entity('channel_thread'))).toBe(false);});++ it('offers only what the delete mutation removes', () => {+ expect(canExecute(entity('call'))).toBe(true);+ expect(canExecute(entity('routine'))).toBe(true);+ expect(canExecute(entity('calendar_event'))).toBe(false);+ expect(canExecute(entity('initiative'))).toBe(false);+ expect(canExecute(entity('foreign'))).toBe(false);+ });});diff --git a/apps/web/src/features/next-soup/actions/make-delete-action.ts b/apps/web/src/features/next-soup/actions/make-delete-action.tsindex f4cb5bc474..56a12ba862 100644--- a/apps/web/src/features/next-soup/actions/make-delete-action.ts+++ b/apps/web/src/features/next-soup/actions/make-delete-action.ts@@ -99,18 +99,18 @@ export const makeDeleteAction = (options: MakeDeleteOptions) => {const { userId } = options;const canExecute = (entity: EntityData): boolean => {- if (- entity.type === 'database' ||- entity.type === 'form' ||- entity.type === 'channel_message' ||- entity.type === 'channel_thread'- ) {- return false;- }if (entity.type === 'email') {return true;}- if (entity.type === 'channel') {+ // The types the delete mutation supports; it skips any other.+ if (+ entity.type !== 'agent_session' &&+ entity.type !== 'document' &&+ entity.type !== 'chat' &&+ entity.type !== 'project' &&+ entity.type !== 'call' &&+ entity.type !== 'routine'+ ) {return false;}return entity.ownerId === userId();diff --git a/apps/web/src/features/next-soup/actions/make-download-action.test.ts b/apps/web/src/features/next-soup/actions/make-download-action.test.tsnew file mode 100644index 0000000000..742e9037f4--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-download-action.test.ts@@ -0,0 +1,183 @@+import type { EntityData } from '@entity';+import { storageServiceClient } from '@service-storage/client';+import { ok } from 'neverthrow';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ save: vi.fn(),+ exportDocument: vi.fn(),+ fetch: vi.fn(),+ success: vi.fn(),+ failure: vi.fn(),+}));++// Gating resolves file types through every block definition, whose clients+// would open websockets.+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));+vi.mock('@filesystem/download', () => ({ downloadFile: mocks.save }));+vi.mock('@service-storage/util/downloadExportedDocument', () => ({+ downloadExportedDocument: mocks.exportDocument,+}));+vi.mock('@core/util/platformFetch', () => ({ platformFetch: mocks.fetch }));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: mocks.success, failure: mocks.failure, custom: vi.fn() },+}));++import { makeDownloadAction } from './make-download-action';++const documentRow = (+ fileType: string | undefined,+ name = 'Plan'+): EntityData => ({+ type: 'document',+ id: 'doc-1',+ name,+ ownerId: 'macro|[email protected]',+ fileType,+});++const savedFile = (): File => mocks.save.mock.calls[0][0];++beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ mocks.save.mockResolvedValue({ saved: true });+});++describe('download type gating', () => {+ it.each([+ 'png',+ 'mp4',+ 'ts',+ 'csv',+ 'zip',+ 'xlsx',+ 'pptx',+ 'psd',+ 'ai',+ 'fig',+ 'docx',+ ])('offers stored or exported %s files', (fileType) => {+ expect(makeDownloadAction().canExecute(documentRow(fileType))).toBe(true);+ });++ it.each(['md', 'pdf', 'canvas', 'spreadsheet', undefined])(+ 'leaves %s documents to their open editor or viewer',+ (fileType) => {+ expect(makeDownloadAction().canExecute(documentRow(fileType))).toBe(+ false+ );+ }+ );++ it('leaves tasks and other entities out', () => {+ const action = makeDownloadAction();+ expect(+ action.canExecute({+ type: 'document',+ id: 'task-1',+ name: 'Ship it',+ ownerId: 'macro|[email protected]',+ fileType: 'md',+ subType: { type: 'task' },+ })+ ).toBe(false);+ expect(+ action.canExecute({+ type: 'chat',+ id: 'chat-1',+ name: 'Chat',+ ownerId: 'macro|[email protected]',+ })+ ).toBe(false);+ });+});++describe('download by id', () => {+ it("saves a Word document's server export under the editor's filename", async () => {+ mocks.exportDocument.mockResolvedValue(new Uint8Array([1, 2, 3]));++ await makeDownloadAction().execute([documentRow('docx')]);++ expect(mocks.exportDocument).toHaveBeenCalledWith({ documentId: 'doc-1' });+ expect(savedFile().name).toBe('Plan.docx');+ expect(savedFile().type).toBe(+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'+ );+ expect(savedFile().size).toBe(3);+ });++ it('saves the latest stored version under its stored name', async () => {+ const metadata = vi+ .spyOn(storageServiceClient, 'getDocumentMetadata')+ .mockResolvedValue(+ ok({+ documentMetadata: {+ documentId: 'doc-1',+ documentName: 'Diagram',+ documentVersionId: 7,+ fileType: 'png',+ owner: 'macro|[email protected]',+ },+ userAccessLevel: 'view',+ })+ );+ const location = vi+ .spyOn(storageServiceClient, 'getDocumentLocation')+ .mockResolvedValue(+ ok({+ data: {+ type: 'presignedUrl',+ presignedUrl: 'https://files.example/doc-1/7',+ content: { state: 'ready' },+ metadata: {+ documentId: 'doc-1',+ documentName: 'Diagram',+ owner: 'macro|[email protected]',+ },+ },+ })+ );+ mocks.fetch.mockResolvedValue(+ new Response('image', { headers: { 'Content-Type': 'image/png' } })+ );++ await makeDownloadAction().execute([documentRow('png', 'Old name')]);++ expect(metadata.mock.calls[0][0].documentId).toBe('doc-1');+ expect(location).toHaveBeenCalledWith({+ documentId: 'doc-1',+ versionId: 7,+ });+ expect(mocks.fetch.mock.calls[0][0]).toBe('https://files.example/doc-1/7');+ expect(savedFile().name).toBe('Diagram.png');+ expect(savedFile().size).toBe(5);+ });++ it('reports a failed export without saving anything', async () => {+ mocks.exportDocument.mockRejectedValue(new Error('export failed'));++ await makeDownloadAction().execute([documentRow('docx')]);++ expect(mocks.save).not.toHaveBeenCalled();+ expect(mocks.failure).toHaveBeenCalledOnce();+ });++ it('downloads nothing for a multi-row selection', async () => {+ await makeDownloadAction().execute([+ documentRow('docx'),+ documentRow('docx'),+ ]);++ expect(mocks.exportDocument).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-download-action.ts b/apps/web/src/features/next-soup/actions/make-download-action.tsnew file mode 100644index 0000000000..c7bf1bc88a--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-download-action.ts@@ -0,0 +1,112 @@+import type { BlockName } from '@core/block';+import { fileTypeToResolvedBlockName } from '@core/constant/allBlocks';+import {+ createFileDownload,+ type DownloadSource,+} from '@core/util/createFileDownload';+import { fireAndForget } from '@core/util/fireAndForget';+import type { EntityData } from '@entity';+import {+ exportedDocxDownloadSource,+ storedDocumentDownloadSource,+} from '@queries/storage/document-download';+import { createRoot } from 'solid-js';+import { match } from 'ts-pattern';+import type { EntityActionListState } from './entity-action-context';++/**+ * Where a list row's document downloads from without its editor open, or+ * undefined when only the open editor or viewer can produce the file.+ */+function documentDownloadSource(+ entity: EntityData+): DownloadSource | undefined {+ if (entity.type !== 'document' || !entity.fileType) return undefined;+ const { id, name, fileType } = entity;+ // Storage rebuilds a Word document from its parts, whichever block opens it.+ if (fileType === 'docx') return exportedDocxDownloadSource(id, name);+ return (+ match<BlockName, DownloadSource | undefined>(+ fileTypeToResolvedBlockName(fileType)+ )+ .with(+ 'image',+ 'video',+ 'code',+ 'unknown',+ 'pptx',+ 'psd',+ 'ai',+ 'fig',+ () => storedDocumentDownloadSource(id)+ )+ // Markdown, canvas and spreadsheet content lives in the sync service and+ // exports from the open editor; a PDF's download bakes in the markup and+ // comments its open viewer has loaded.+ .with('md', 'canvas', 'spreadsheet', 'pdf', () => undefined)+ .with(+ 'write',+ 'call',+ 'calendar',+ 'chat',+ 'database',+ 'form',+ 'channel',+ 'project',+ 'email',+ 'contact',+ 'company',+ 'routine',+ 'pr',+ 'agent',+ 'initiative',+ 'pipeline',+ () => undefined+ )+ .exhaustive()+ );+}++/**+ * Downloads under a root of its own. The controller cancels its transfer when+ * its owner is disposed, and choosing the item disposes the menu it sits in.+ */+async function downloadDocument(source: DownloadSource) {+ await createRoot(async (dispose) => {+ try {+ await createFileDownload(() => source).start();+ } finally {+ dispose();+ }+ });+}++/**+ * Downloads one document row by id through the shared file download+ * controller (native save picker, toasts, `file.download` trace), under the+ * filename the file's own Download uses. Offer it for a single entity.+ */+export const makeDownloadAction = () => {+ const canExecute = (entity: EntityData): boolean =>+ documentDownloadSource(entity) !== undefined;++ /** Resolves once the file is handed off or its failure is reported. */+ const execute = async (entities: EntityData[]) => {+ const [entity] = entities;+ if (!entity || entities.length !== 1) return;+ const source = documentDownloadSource(entity);+ if (!source) return;+ await downloadDocument(source);+ };++ const executeWithSoup = async (+ entities: EntityData[],+ _soup: EntityActionListState+ ) => {+ // Return at once so the menu or drawer closes while the file loads; the+ // selection and focus stay as they were.+ fireAndForget(execute(entities), 'soup-entity-download');+ };++ return { canExecute, execute, executeWithSoup };+};diff --git a/apps/web/src/features/next-soup/actions/make-favorite-action.ts b/apps/web/src/features/next-soup/actions/make-favorite-action.tsindex a13f6b9919..b27ea74e48 100644--- a/apps/web/src/features/next-soup/actions/make-favorite-action.ts+++ b/apps/web/src/features/next-soup/actions/make-favorite-action.ts@@ -23,10 +23,10 @@ export const makeFavoriteAction = () => {const addMutation = useAddFavoriteMutation();const removeMutation = useRemoveFavoriteMutation();+ // Foreign entities (pull requests included) are not offered; favorites+ // already saved for them stay removable from the sidebar.const canExecute = (entity: EntityData): boolean =>- (entity.type !== 'foreign' ||- entity.foreignSource === 'github_pull_request') &&- favoriteEntityType(entity.type) !== undefined;+ entity.type !== 'foreign' && favoriteEntityType(entity.type) !== undefined;const isFavorited = (entity: EntityData): boolean => {const type = favoriteEntityType(entity.type);diff --git a/apps/web/src/features/next-soup/actions/make-github-link-action.ts b/apps/web/src/features/next-soup/actions/make-github-link-action.tsnew file mode 100644index 0000000000..d2dc41c577--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-github-link-action.ts@@ -0,0 +1,23 @@+import { t } from '@app/lib/i18n';+import { toast } from '@core/component/Toast/Toast';+import { openExternalUrl } from '@core/util/url';+import { type EntityData, isGithubPrEntity } from '@entity';++/** A pull request's own GitHub page: open it, or copy its address. */+export const makeGithubLinkAction = () => {+ const canExecute = (entity: EntityData): boolean =>+ isGithubPrEntity(entity) && entity.metadata.url.length > 0;++ const open = (entity: EntityData) => {+ if (!isGithubPrEntity(entity)) return;+ openExternalUrl(entity.metadata.url);+ };++ const copy = async (entity: EntityData) => {+ if (!isGithubPrEntity(entity)) return;+ await navigator.clipboard.writeText(entity.metadata.url);+ toast.success(t('entityActions.toastGithubLinkCopied'));+ };++ return { canExecute, open, copy };+};diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.test.tsindex e9de505558..217b21ed93 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.test.ts@@ -196,6 +196,11 @@ describe('canExecuteMarkDoneOnView', () => {it('allows mark done on the archived tab', () => {expect(canExecuteMarkDoneOnView('mail', 'archived')).toBe(true);});++ it('allows mark done in Search but not in task lists', () => {+ expect(canExecuteMarkDoneOnView('search', 'all')).toBe(true);+ expect(canExecuteMarkDoneOnView('tasks', 'my-tasks')).toBe(false);+ });});describe('makeMarkDoneAction', () => {diff --git a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts b/apps/web/src/features/next-soup/actions/make-mark-done-action.tsindex ed15a7e2e4..2022b6eef7 100644--- a/apps/web/src/features/next-soup/actions/make-mark-done-action.ts+++ b/apps/web/src/features/next-soup/actions/make-mark-done-action.ts@@ -55,6 +55,9 @@ const VALID_MARK_DONE_LIST_VIEWS: `${ListView}-${string}`[] = ['mail-calendar','mail-shared','mail-archived',+ // Search lists done and open rows alike, like mail "All": a marked row flips+ // to done (or drops out of a not-done filter) and focus moves on.+ 'search-all',];export const canExecuteMarkDoneOnView = (view: ListView, tabId: string) => {diff --git a/apps/web/src/features/next-soup/actions/make-move-to-project-action.test.ts b/apps/web/src/features/next-soup/actions/make-move-to-project-action.test.tsnew file mode 100644index 0000000000..efe55e4ee0--- /dev/null+++ b/apps/web/src/features/next-soup/actions/make-move-to-project-action.test.ts@@ -0,0 +1,44 @@+import type { EntityData } from '@entity';+import { describe, expect, it, vi } from 'vitest';++vi.mock('@app/features/entity/bulk-edit/BulkEditEntityModal', () => ({+ openBulkEditModal: vi.fn(),+}));+vi.mock('@core/component/Toast/Toast', () => ({+ toast: { success: vi.fn(), failure: vi.fn(), dismiss: vi.fn() },+}));+vi.mock('../utils', () => ({+ restoreSoupFocus: vi.fn(),+}));++import { makeMoveToProjectAction } from './make-move-to-project-action';++const entity = (type: EntityData['type']) =>+ ({ type, id: 'e1', name: 'Thing', ownerId: 'macro|me' }) as EntityData;++const { canExecute } = makeMoveToProjectAction({ userId: () => 'macro|me' });++describe('makeMoveToProjectAction.canExecute', () => {+ it('offers moving what the move mutation moves', () => {+ expect(canExecute(entity('document'))).toBe(true);+ expect(canExecute(entity('chat'))).toBe(true);+ expect(canExecute(entity('project'))).toBe(true);+ expect(canExecute(entity('email'))).toBe(true);+ });++ it('refuses items someone else owns', () => {+ expect(+ canExecute({+ ...entity('document'),+ ownerId: 'macro|other',+ } as EntityData)+ ).toBe(false);+ });++ it('refuses types the move mutation rejects', () => {+ expect(canExecute(entity('call'))).toBe(false);+ expect(canExecute(entity('calendar_event'))).toBe(false);+ expect(canExecute(entity('routine'))).toBe(false);+ expect(canExecute(entity('agent_session'))).toBe(false);+ });+});diff --git a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts b/apps/web/src/features/next-soup/actions/make-move-to-project-action.tsindex 16c4e36a8e..387488d67b 100644--- a/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts+++ b/apps/web/src/features/next-soup/actions/make-move-to-project-action.ts@@ -6,18 +6,25 @@ import type { EntityData } from '@entity';import { restoreSoupFocus } from '../utils';import type { EntityActionListState } from './entity-action-context';-export const makeMoveToProjectAction = () => {- const canExecute = (entity: EntityData): boolean => {- return (- entity.type !== 'database' &&- entity.type !== 'form' &&- entity.type !== 'agent_session' &&- entity.type !== 'channel' &&- entity.type !== 'channel_message' &&- entity.type !== 'channel_thread' &&- entity.type !== 'foreign'- );- };+type MakeMoveToProjectOptions = {+ userId: () => string | undefined;+};++/**+ * Move items into a folder. Only an item's owner may: a folder is one+ * location shared by everyone, and its sharing passes to what it holds, so+ * a move changes where the owner finds the item and who can see it.+ */+export const makeMoveToProjectAction = (options: MakeMoveToProjectOptions) => {+ // The types the move mutation supports; it rejects any other.+ const canMoveType = (entity: EntityData): boolean =>+ entity.type === 'document' ||+ entity.type === 'chat' ||+ entity.type === 'project' ||+ entity.type === 'email';++ const canExecute = (entity: EntityData): boolean =>+ canMoveType(entity) && entity.ownerId === options.userId();const execute = async (entities: EntityData[]) => {openBulkEditModal({@@ -68,5 +75,5 @@ export const makeMoveToProjectAction = () => {});};- return { canExecute, execute, executeWithSoup };+ return { canMoveType, canExecute, execute, executeWithSoup };};diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.test.ts b/apps/web/src/features/next-soup/actions/make-rename-action.test.tsindex 0c12db00cc..66ff2d496f 100644--- a/apps/web/src/features/next-soup/actions/make-rename-action.test.ts+++ b/apps/web/src/features/next-soup/actions/make-rename-action.test.ts@@ -104,4 +104,12 @@ describe('makeRenameAction.canExecute', () => {expect(canExecute(entity('email'))).toBe(false);expect(canExecute(entity('foreign'))).toBe(false);});++ it('offers only what the rename mutation renames', () => {+ expect(canExecute(entity('call'))).toBe(true);+ expect(canExecute(entity('chat'))).toBe(true);+ expect(canExecute(entity('calendar_event'))).toBe(false);+ expect(canExecute(entity('initiative'))).toBe(false);+ expect(canExecute(entity('routine'))).toBe(false);+ });});diff --git a/apps/web/src/features/next-soup/actions/make-rename-action.ts b/apps/web/src/features/next-soup/actions/make-rename-action.tsindex e0f5b81f74..2fe3e9bee1 100644--- a/apps/web/src/features/next-soup/actions/make-rename-action.ts+++ b/apps/web/src/features/next-soup/actions/make-rename-action.ts@@ -15,18 +15,16 @@ export const makeRenameAction = (options: MakeRenameOptions) => {const canExecute = (entity: EntityData): boolean => {if (entity.type === 'agent_session' && entity.isArchived) return false;+ if (entity.type === 'channel') return canEditChannelIdentity(entity);+ // The types the rename mutation supports; it rejects any other.if (- entity.type === 'email' ||- entity.type === 'database' ||- entity.type === 'form'+ entity.type !== 'agent_session' &&+ entity.type !== 'document' &&+ entity.type !== 'chat' &&+ entity.type !== 'project' &&+ entity.type !== 'call')return false;- if (entity.type === 'channel_message' || entity.type === 'channel_thread') {- return false;- }- if (entity.type === 'foreign') return false;-- if (entity.type === 'channel') return canEditChannelIdentity(entity);return entity.ownerId === userId();};diff --git a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts b/apps/web/src/features/next-soup/actions/use-block-entity-commands.tsindex 3c5cbbb8b4..36b3174ebc 100644--- a/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts+++ b/apps/web/src/features/next-soup/actions/use-block-entity-commands.ts@@ -95,7 +95,9 @@ export const useBlockEntityCommands = (});const renameAction = makeRenameAction({ userId: () => userId() });const copyAction = makeCopyAction();- const moveToProjectAction = makeMoveToProjectAction();+ const moveToProjectAction = makeMoveToProjectAction({+ userId: () => userId(),+ });const copyLinkAction = makeCopyLinkAction();const copyBranchNameAction = makeCopyBranchNameAction();const copyEntityIdAction = makeCopyEntityIdAction();diff --git a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.tsindex d7619b74bd..0ece53d1c9 100644--- a/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts+++ b/apps/web/src/features/next-soup/actions/use-entity-action-hotkeys.ts@@ -109,7 +109,9 @@ export const useEntityActionHotkeys = (const copyAction = makeCopyAction();- const moveToProjectAction = makeMoveToProjectAction();+ const moveToProjectAction = makeMoveToProjectAction({+ userId: () => userId(),+ });const copyLinkAction = makeCopyLinkAction();diff --git a/apps/web/src/features/reviews-view/components/ReviewContextMenu.tsx b/apps/web/src/features/reviews-view/components/ReviewContextMenu.tsxnew file mode 100644index 0000000000..179d9aecfd--- /dev/null+++ b/apps/web/src/features/reviews-view/components/ReviewContextMenu.tsx@@ -0,0 +1,47 @@+import { makeCopyLinkAction } from '@app/features/next-soup/actions';+import { t } from '@app/lib/i18n';+import { globalSplitManager } from '@app/signal/splitLayout';+import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';+import { fireAndForget } from '@core/util/fireAndForget';+import { openExternalUrl } from '@core/util/url';+import type { GithubPullRequestEntity } from '@entity';+import ArrowSquareOutIcon from '@icon/system/regular/arrow-square-out.svg';+import SplitIcon from '@icon/system/regular/columns.svg';+import CopyIcon from '@icon/system/regular/copy.svg';+import { ContextMenu } from '@kobalte/core/context-menu';++const copyLink = makeCopyLinkAction();++/** A pull request's right-click actions, for list rows and board cards alike. */+export function ReviewContextMenuContent(props: {+ review: GithubPullRequestEntity;+ onOpen: (foreignEntityId: string, newSplit: boolean) => void;+}) {+ return (+ <ContextMenu.Portal>+ <ContextMenuContent class="min-w-56 max-w-[22rem] text-xs text-ink-muted">+ <MenuItem+ icon={SplitIcon}+ text={t('entityActions.openInNewSplit')}+ disabled={!globalSplitManager()?.canAppendSplit()}+ onClick={() => {+ if (globalSplitManager()?.canAppendSplit())+ props.onOpen(props.review.id, true);+ }}+ />+ <MenuItem+ icon={CopyIcon}+ text={t('entityActions.copyLinkCommand')}+ onClick={() =>+ fireAndForget(copyLink.execute([props.review]), 'reviews-view')+ }+ />+ <MenuItem+ icon={ArrowSquareOutIcon}+ text={t('entityActions.openOnGitHub')}+ onClick={() => openExternalUrl(props.review.metadata.url)}+ />+ </ContextMenuContent>+ </ContextMenu.Portal>+ );+}diff --git a/apps/web/src/features/reviews-view/components/ReviewsBoard.tsx b/apps/web/src/features/reviews-view/components/ReviewsBoard.tsxindex ed6531d0b3..599d280d9a 100644--- a/apps/web/src/features/reviews-view/components/ReviewsBoard.tsx+++ b/apps/web/src/features/reviews-view/components/ReviewsBoard.tsx@@ -12,9 +12,10 @@ import {} from '@block-pr/component/PrLinks';import { PrStatusIcon } from '@block-pr/component/PrStatus';import { priorityTaskName } from '@block-pr/data/pr-links';+import { pullRequestFailureMessage } from '@block-pr/primitives/create-merge-pull-request-action';import { prDisplayName } from '@block-pr/util/prKey';+import { ContextMenuTrigger } from '@core/component/ContextMenu';import { toast } from '@core/component/Toast/Toast';-import { ThrownResultError } from '@core/util/result';import type { GithubPullRequestEntity } from '@entity';import { GithubLabelPills } from '@entity/components/GithubLabelPill';import {@@ -22,6 +23,7 @@ import {GithubPullRequestChecksIndicator,} from '@entity/composed/list-entity/foreign';import { PrAgentSessionsChip } from '@entity/views/PrAgentSessionsChip';+import { ContextMenu } from '@kobalte/core/context-menu';import { queryClient } from '@queries/client';import { soupKeys } from '@queries/soup/keys';import { useSetGithubPullRequestDraftMutation } from '@queries/storage/pr-draft';@@ -38,18 +40,12 @@ import {reviewsBoardAction,reviewsBoardStage,} from '../core/reviews-board';+import { ReviewContextMenuContent } from './ReviewContextMenu';import type { ReviewsListLinks } from './ReviewsList';/** A stage set by a move, kept until the pull request itself changes. */type PendingStage = { stage: ReviewsBoardStage; updatedAt: unknown };-function failureMessage(error: unknown, fallback: string) {- // GitHub's own reason when it declined; anything else is ours.- return error instanceof ThrownResultError && error.errors.length > 0- ? error.message- : fallback;-}-const ACTION_COPY: Record<ReviewsBoardAction,{ done: string; failed: string }@@ -186,7 +182,9 @@ export function ReviewsBoard(props: {.exhaustive();} catch (error) {updatePending(review.id);- toast.failure(failureMessage(error, ACTION_COPY[action].failed));+ toast.failure(+ pullRequestFailureMessage(error, ACTION_COPY[action].failed)+ );return false;} finally {updateSet(review.id, false);@@ -249,11 +247,19 @@ export function ReviewsBoard(props: {props.onOpen(card().id, event.shiftKey)}>- <ReviewsBoardCard- review={review()}- links={props.links}- onOpen={props.onOpen}- />+ <ContextMenu>+ <ContextMenuTrigger as="div">+ <ReviewsBoardCard+ review={review()}+ links={props.links}+ onOpen={props.onOpen}+ />+ </ContextMenuTrigger>+ <ReviewContextMenuContent+ review={review()}+ onOpen={props.onOpen}+ />+ </ContextMenu></TaskBoard.Card>)}</Show>diff --git a/apps/web/src/features/reviews-view/components/ReviewsList.tsx b/apps/web/src/features/reviews-view/components/ReviewsList.tsxindex 804d49d0c5..a7d4dc7057 100644--- a/apps/web/src/features/reviews-view/components/ReviewsList.tsx+++ b/apps/web/src/features/reviews-view/components/ReviewsList.tsx@@ -1,14 +1,10 @@import { useListInteractions } from '@app/components/list';import {- makeCopyLinkAction,- makeFavoriteAction,toEntityActionListState,useEntityActionHotkeys,} from '@app/features/next-soup/actions';import { DateGroupHeading } from '@app/features/next-soup/soup-view/date-group-heading';-import { t } from '@app/lib/i18n';import { useInfiniteScrollSentinel } from '@app/lib/primitives/infinite-scroll-sentinel';-import { globalSplitManager } from '@app/signal/splitLayout';import {type OpenPrLink,PrLinkChips,@@ -17,7 +13,6 @@ import {} from '@block-pr/component/PrLinks';import { type PrLinks, priorityTaskName } from '@block-pr/data/pr-links';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';-import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';import { fireAndForget } from '@core/util/fireAndForget';import {EntitySelectionToolbar,@@ -25,11 +20,7 @@ import {ListEntity,ListLayoutProvider,} from '@entity';-import ArrowSquareOutIcon from '@icon/system/regular/arrow-square-out.svg';-import SplitIcon from '@icon/system/regular/columns.svg';-import CopyIcon from '@icon/system/regular/copy.svg';import SpinnerIcon from '@icon/system/regular/spinner.svg';-import StarIcon from '@icon/system/regular/star.svg';import { ContextMenu } from '@kobalte/core/context-menu';import type { GithubLinkStatus } from '@queries/auth/github-link';import { createElementSize } from '@solid-primitives/resize-observer';@@ -55,6 +46,7 @@ import {type ReviewsSortId,scopeMatchesViewerGithubId,} from '../reviews-types';+import { ReviewContextMenuContent } from './ReviewContextMenu';import { ReviewsEmptyState } from './ReviewsEmptyState';/** What each row links to, loaded alongside the list. */@@ -82,8 +74,6 @@ export type ReviewsListProps = {links: ReviewsListLinks;};-const copyLink = makeCopyLinkAction();-function ReviewListElement(props: JSX.HTMLAttributes<HTMLUListElement>) {return <ul {...props} aria-label="Pull requests" />;}@@ -93,7 +83,6 @@ function ReviewRow(props: {authorDisplayName?: string;checked: boolean;onChecked: (checked: boolean, shiftKey: boolean) => void;- favoriteAction: ReturnType<typeof makeFavoriteAction>;onOpen: ReviewsListProps['onOpen'];links: ReviewsListLinks;onActivate: (newSplit: boolean) => void;@@ -148,58 +137,13 @@ function ReviewRow(props: {}/></ContextMenu.Trigger>- <ContextMenu.Portal>- <ContextMenuContent class="min-w-56 max-w-[22rem] text-xs text-ink-muted">- <MenuItem- icon={SplitIcon}- text={t('entityActions.openInNewSplit')}- disabled={!globalSplitManager()?.canAppendSplit()}- onClick={() => {- if (globalSplitManager()?.canAppendSplit())- props.onOpen(props.review.id, true);- }}- />- <MenuItem- icon={StarIcon}- text={- props.favoriteAction.isFavorited(props.review)- ? t('entityActions.removeFromFavorites')- : t('entityActions.addToFavorites')- }- onClick={() =>- fireAndForget(- props.favoriteAction.execute([props.review]),- 'reviews-view'- )- }- />- <MenuItem- icon={CopyIcon}- text={t('entityActions.copyLinkCommand')}- onClick={() =>- fireAndForget(copyLink.execute([props.review]), 'reviews-view')- }- />- <MenuItem- icon={ArrowSquareOutIcon}- text={t('entityActions.openOnGitHub')}- onClick={() =>- window.open(- props.review.metadata.url,- '_blank',- 'noopener,noreferrer'- )- }- />- </ContextMenuContent>- </ContextMenu.Portal>+ <ReviewContextMenuContent review={props.review} onOpen={props.onOpen} /></ContextMenu>);}export function ReviewsList(props: ReviewsListProps) {const panel = useSplitPanelOrThrow();- const favoriteAction = makeFavoriteAction();const source = props.source;const list = props.list;const reviews = list.items.all;@@ -465,7 +409,6 @@ export function ReviewsList(props: ReviewsListProps) {? props.viewerName: undefined}- favoriteAction={favoriteAction}onOpen={props.onOpen}links={props.links}onChecked={(checked, shiftKey) =>diff --git a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsxindex df9b61fbc0..9a2d2cdb6e 100644--- a/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx+++ b/apps/web/src/features/reviews-view/components/ReviewsPrDetail.tsx@@ -3,8 +3,11 @@ import { ChangesSplit } from '@app/features/changes/changes';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { useRouteParams } from '@app/lib/split-router';import { reviewsPrRoute } from '@app/routes/routes';+import { confirmMergePullRequest } from '@block-pr/component/MergePullRequestButton';import { PrChangesProvider } from '@block-pr/component/PrChanges';import { PrStatusIcon } from '@block-pr/component/PrStatus';+import { createPrActions } from '@block-pr/primitives/create-pr-actions';+import { usePrFileOperations } from '@block-pr/primitives/pr-file-operations';import { prDisplayName, prHtmlUrl } from '@block-pr/util/prKey';import {PrDetailActions,@@ -12,7 +15,10 @@ import {usePrDetail,} from '@block-pr/views/PrDetail';import { SidePanel } from '@components/app/side-panel';-import { SplitFileMenu } from '@components/app/split-layout/components/SplitFileMenu';+import {+ type FileOperation,+ SplitFileMenu,+} from '@components/app/split-layout/components/SplitFileMenu';import { SplitPanel } from '@components/app/split-panel';import { Permissions } from '@core/component/SharePermissions';import { fireAndForget } from '@core/util/fireAndForget';@@ -22,6 +28,7 @@ function ReviewsPrBreadcrumb(props: {foreignEntityId: string;name: string;status?: string;+ operations: FileOperation[];}) {return (<ViewBreadcrumbs.Item@@ -50,7 +57,7 @@ function ReviewsPrBreadcrumb(props: {name={props.name}entityKind="pr"permissions={Permissions.CAN_VIEW}- ops={[]}+ ops={props.operations}/></div></div>@@ -62,6 +69,8 @@ function ReviewsPrBreadcrumb(props: {export function ReviewsPrDetail(props: { foreignEntityId: string }) {const analytics = useAnalytics();const detail = usePrDetail(() => props.foreignEntityId);+ const actions = createPrActions(detail.data, confirmMergePullRequest);+ const operations = usePrFileOperations(detail.data, actions);const name = () => {const data = detail.data();return (@@ -93,13 +102,14 @@ export function ReviewsPrDetail(props: { foreignEntityId: string }) {foreignEntityId={props.foreignEntityId}name={name()}status={detail.data()?.pullRequest.status ?? undefined}+ operations={operations()}/><ChangesSplit><div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden @container"><ViewShell.TopBar class="touch:flex touch:h-auto touch:min-h-12 touch:pt-[calc(var(--mobile-content-inset-top,var(--safe-top,0px))+0.75rem)]"><SplitPanel.CloseButton class="hidden shrink-0 touch:flex" /><ViewBreadcrumbs.Outlet aria-label="Pull request location" />- <PrDetailActions detail={detail.data()} />+ <PrDetailActions detail={detail.data()} actions={actions} /></ViewShell.TopBar><PrDetailContentforeignEntityId={props.foreignEntityId}diff --git a/apps/web/src/features/sharing/global-share-modal/shareable-entity.ts b/apps/web/src/features/sharing/global-share-modal/shareable-entity.tsindex 36f372a107..0eadfd598a 100644--- a/apps/web/src/features/sharing/global-share-modal/shareable-entity.ts+++ b/apps/web/src/features/sharing/global-share-modal/shareable-entity.ts@@ -8,7 +8,8 @@ export type ShareableEntityType =| 'project'| 'email'| 'form'- | 'agent_session';+ | 'agent_session'+ | 'call';/** The subset of {@link EntityData} the global share modal accepts. */export type ShareableEntityData = Extract<@@ -32,6 +33,7 @@ export const isShareableEntityType = (type === 'chat' ||type === 'project' ||type === 'form' ||- type === 'agent_session'+ type === 'agent_session' ||+ type === 'call');};diff --git a/apps/web/src/features/sharing/global-share-modal/tests/shareable-entity.test.ts b/apps/web/src/features/sharing/global-share-modal/tests/shareable-entity.test.tsindex 29efc4ec31..ed29be67b3 100644--- a/apps/web/src/features/sharing/global-share-modal/tests/shareable-entity.test.ts+++ b/apps/web/src/features/sharing/global-share-modal/tests/shareable-entity.test.ts@@ -9,10 +9,11 @@ describe('isShareableEntityType', () => {expect(isShareableEntityType('email')).toBe(true);expect(isShareableEntityType('agent_session')).toBe(true);expect(isShareableEntityType('form')).toBe(true);+ expect(isShareableEntityType('call')).toBe(true);});it('rejects entity types with no share flow', () => {expect(isShareableEntityType('channel')).toBe(false);- expect(isShareableEntityType('call')).toBe(false);+ expect(isShareableEntityType('calendar_event')).toBe(false);});});diff --git a/apps/web/src/features/soup/SoupEntityActionDrawerContext.ts b/apps/web/src/features/soup/SoupEntityActionDrawerContext.tsindex 802e6a338d..364eed8ef6 100644--- a/apps/web/src/features/soup/SoupEntityActionDrawerContext.ts+++ b/apps/web/src/features/soup/SoupEntityActionDrawerContext.ts@@ -1,7 +1,9 @@import type {EntityActionListState,+ EntityActionNavigationHandler,EntityActionViewContext,} from '@app/features/next-soup/actions';+import type { MarkDoneDelegate } from '@app/features/next-soup/actions/mark-done-delegate';import type { EntityData } from '@entity';import { type Accessor, createContext, useContext } from 'solid-js';@@ -9,6 +11,11 @@ export type EntityActionDrawerEntry = {entity: EntityData;list: EntityActionListState;viewContext: EntityActionViewContext;+ markDoneDelegate?: () => MarkDoneDelegate | undefined;+ createActionNavigationHandler?: () =>+ | EntityActionNavigationHandler+ | undefined;+ viewedProjectId?: string;};export type SoupEntityActionDrawerState = {diff --git a/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsx b/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsxindex bdb4fcaf26..77229c1076 100644--- a/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsx+++ b/apps/web/src/features/soup/SoupEntityActionDrawerManager.tsx@@ -25,7 +25,9 @@ import {function ConfiguredSoupEntityActionDrawer() {const panel = useSplitPanelOrThrow();const drawerState = useSoupEntityActionDrawer();- const { buildActionGroups } = createSoupEntityActions();+ const { buildActionGroups } = createSoupEntityActions({+ markDoneDelegate: () => drawerState?.entry()?.markDoneDelegate?.(),+ });const [projectTasks, setProjectTasks] = createSignal<string[]>();if (!drawerState) {@@ -40,8 +42,10 @@ function ConfiguredSoupEntityActionDrawer() {const content = panel.handle.content();return buildActionGroups(entry.list, [entry.entity], {viewContext: entry.viewContext,- viewedProjectId: viewedProjectIdFromContent(content),+ viewedProjectId:+ entry.viewedProjectId ?? viewedProjectIdFromContent(content),splitHandle: panel.handle,+ createActionNavigationHandler: entry.createActionNavigationHandler,openProjectPicker: () => {const ids = [entry.entity.id];drawerState.close();diff --git a/apps/web/src/features/soup/SoupEntityActionsMenu.test.tsx b/apps/web/src/features/soup/SoupEntityActionsMenu.test.tsxindex 66cac8159c..e94c926706 100644--- a/apps/web/src/features/soup/SoupEntityActionsMenu.test.tsx+++ b/apps/web/src/features/soup/SoupEntityActionsMenu.test.tsx@@ -14,6 +14,9 @@ type TestGroup = {const actions = vi.hoisted(() => ({groups: [] as TestGroup[],+ context: undefined as+ | { viewedProjectId?: string; createActionNavigationHandler?: unknown }+ | undefined,options: undefined as| { markDoneDelegate?: () => MarkDoneDelegate | undefined }| undefined,@@ -27,7 +30,16 @@ vi.mock('@components/app/split-layout/layoutUtils', () => ({vi.mock('./createSoupEntityActions', () => ({createSoupEntityActions: (options?: typeof actions.options) => {actions.options = options;- return { buildActionGroups: () => actions.groups };+ return {+ buildActionGroups: (+ _list: unknown,+ _entities: unknown,+ context: typeof actions.context+ ) => {+ actions.context = context;+ return actions.groups;+ },+ };},viewedProjectIdFromContent: () => undefined,}));@@ -81,6 +93,23 @@ describe('SoupEntityActionsMenu mark done', () => {expect(actions.options?.markDoneDelegate?.()).toBe(delegate);});});+describe('SoupEntityActionsMenu view context', () => {+ it("uses the host's folder when the split content doesn't name one", () => {+ const navigate = () => undefined;+ render(() => (+ <SoupEntityActionsMenu+ entities={[]}+ list={{} as EntityActionListState}+ viewContext={viewContext}+ viewedProjectId="folder-1"+ createActionNavigationHandler={navigate}+ />+ ));++ expect(actions.context?.viewedProjectId).toBe('folder-1');+ expect(actions.context?.createActionNavigationHandler).toBe(navigate);+ });+});afterEach(cleanup);describe('SoupEntityActionsMenu separators', () => {diff --git a/apps/web/src/features/soup/SoupEntityActionsMenu.tsx b/apps/web/src/features/soup/SoupEntityActionsMenu.tsxindex 570801e512..023e492f7a 100644--- a/apps/web/src/features/soup/SoupEntityActionsMenu.tsx+++ b/apps/web/src/features/soup/SoupEntityActionsMenu.tsx@@ -1,5 +1,6 @@import type {EntityActionListState,+ EntityActionNavigationHandler,EntityActionViewContext,} from '@app/features/next-soup/actions';import type { MarkDoneDelegate } from '@app/features/next-soup/actions/mark-done-delegate';@@ -23,6 +24,12 @@ interface SoupEntityActionsMenuProps {extraItems?: JSX.Element;/** A list that completes its own rows, such as Home's work feed. */markDoneDelegate?: () => MarkDoneDelegate | undefined;+ /** Where the view moves after an action that removes the row. */+ createActionNavigationHandler?: () =>+ | EntityActionNavigationHandler+ | undefined;+ /** The folder the list shows, when the split's content doesn't say. */+ viewedProjectId?: string;}export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {@@ -40,10 +47,12 @@ export const SoupEntityActionsMenu = (props: SoupEntityActionsMenuProps) => {const content = panel.handle.content();return buildActionGroups(props.list, props.entities, {viewContext: props.viewContext,- viewedProjectId: viewedProjectIdFromContent(content),+ viewedProjectId:+ props.viewedProjectId ?? viewedProjectIdFromContent(content),openTagPicker: props.onEditTags,openProjectPicker: props.onSetProject,splitHandle: panel.handle,+ createActionNavigationHandler: props.createActionNavigationHandler,});};diff --git a/apps/web/src/features/soup/SoupEntityContextMenu.tsx b/apps/web/src/features/soup/SoupEntityContextMenu.tsxindex 2ceeb2f775..62456bc238 100644--- a/apps/web/src/features/soup/SoupEntityContextMenu.tsx+++ b/apps/web/src/features/soup/SoupEntityContextMenu.tsx@@ -1,5 +1,6 @@import type {EntityActionListState,+ EntityActionNavigationHandler,EntityActionViewContext,} from '@app/features/next-soup/actions';import type { MarkDoneDelegate } from '@app/features/next-soup/actions/mark-done-delegate';@@ -43,8 +44,17 @@ interface SoupEntityContextMenuProps {* them. Desktop only: the mobile long-press drawer shows the actions alone.*/extraItems?: JSX.Element;- /** A list that completes its own rows, such as Home's work feed. Desktop only. */+ /** A list that completes its own rows, such as Home's work feed. */markDoneDelegate?: () => MarkDoneDelegate | undefined;+ /** Where the view moves after an action that removes the row (Mark Done). */+ createActionNavigationHandler?: () =>+ | EntityActionNavigationHandler+ | undefined;+ /**+ * The folder the list shows, when the split's content doesn't say so+ * itself (Drive hosts folders inside its own view).+ */+ viewedProjectId?: string;}export const SoupEntityContextMenu: FlowComponent<@@ -76,6 +86,10 @@ export const SoupEntityContextMenu: FlowComponent<entity: props.entity,list: props.list,viewContext: props.viewContext,+ markDoneDelegate: props.markDoneDelegate,+ createActionNavigationHandler:+ props.createActionNavigationHandler,+ viewedProjectId: props.viewedProjectId,});},}));@@ -106,6 +120,10 @@ export const SoupEntityContextMenu: FlowComponent<onEditTags={pickers.openTagPicker()}extraItems={props.extraItems}markDoneDelegate={props.markDoneDelegate}+ createActionNavigationHandler={+ props.createActionNavigationHandler+ }+ viewedProjectId={props.viewedProjectId}/></ContextMenuContent></Show>diff --git a/apps/web/src/features/soup/createSoupEntityActions.ts b/apps/web/src/features/soup/createSoupEntityActions.tsindex a87afd9076..19f60a1c8a 100644--- a/apps/web/src/features/soup/createSoupEntityActions.ts+++ b/apps/web/src/features/soup/createSoupEntityActions.ts@@ -3,6 +3,8 @@ import {type EntityActionListState,type EntityActionNavigationHandler,type EntityActionViewContext,+ emailSenderBucket,+ makeArchiveSessionAction,makeBlockSenderAction,makeChannelPictureAction,makeCopyAction,@@ -11,7 +13,9 @@ import {makeCopyLinkAction,makeCreateReminderAction,makeDeleteAction,+ makeDownloadAction,makeFavoriteAction,+ makeGithubLinkAction,makeMarkDoneAction,makeMarkNotDoneAction,makeMarkNotificationsReadAction,@@ -29,7 +33,10 @@ import type { MarkDoneDelegate } from '@app/features/next-soup/actions/mark-doneimport {markCalendarNotificationSeenOnOpen,openEntityInSplitFromUnifiedList,+ restoreSoupFocus,} from '@app/features/next-soup/utils';+import { useAllProperties } from '@app/features/property/editor/hooks/useAllProperties';+import { openPropertyEditor } from '@app/features/property/editor/state/propertyEditor';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { t } from '@app/lib/i18n';@@ -41,8 +48,10 @@ import { enableProjects, isFeatureEnabled } from '@core/constant/featureFlags';import { useUserId } from '@core/context/user';import { type HotkeyToken, TOKENS } from '@core/hotkey/tokens';import { isMobile } from '@core/mobile/isMobile';+import { fireAndForget } from '@core/util/fireAndForget';import type { EntityData } from '@entity';-import { isEmailEntity, isTaskEntity } from '@entity';+import { isEmailEntity, isGithubPrEntity, isTaskEntity } from '@entity';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';import type { Component, JSX } from 'solid-js';type SoupEntityActionItem = {@@ -138,7 +147,9 @@ export function createSoupEntityActions(const muteAction = makeMuteAction({notificationSource: () => notificationSource,});- const moveToProjectAction = makeMoveToProjectAction();+ const moveToProjectAction = makeMoveToProjectAction({+ userId: () => userId(),+ });const removeFromProjectAction = makeRemoveFromProjectAction();const copyLinkAction = makeCopyLinkAction();const copyBranchNameAction = makeCopyBranchNameAction();@@ -146,6 +157,14 @@ export function createSoupEntityActions(const createReminderAction = makeCreateReminderAction();const shareAction = makeShareAction();const blockSenderAction = makeBlockSenderAction();+ const archiveSessionAction = makeArchiveSessionAction({+ userId: () => userId(),+ });+ const githubLinkAction = makeGithubLinkAction();+ const downloadAction = makeDownloadAction();+ const allProperties = useAllProperties();+ const taskProperty = (propertyId: string) =>+ allProperties().find(({ id }) => id === propertyId);const markSenderSignalAction = makeMarkSenderSignalAction();const markSenderNoiseAction = makeMarkSenderNoiseAction();@@ -246,8 +265,10 @@ export function createSoupEntityActions(if (isMobile()) return undefined;if (entities.length !== 1) return undefined;const entity = entities[0];- // TODO(dev-rb/github): Allow GitHub PRs once they map to /pr.- if (!entity || entity.type === 'foreign') return undefined;+ if (!entity) return undefined;+ // Pull requests open their Reviews detail; other foreign rows don't open.+ if (entity.type === 'foreign' && !isGithubPrEntity(entity))+ return undefined;const splitManager = globalSplitManager();if (!splitManager) return undefined;// Reminder route claims perform identity reuse when the action runs.@@ -294,7 +315,8 @@ export function createSoupEntityActions(});}- // Middle group: Rename, Move to folder, Duplicate, Copy Link, Copy Branch Name, Share+ // Middle group: Rename, Archive, Set status/priority/assignee, Move to+ // folder, Duplicate, Copy Link, Copy Branch Name, Copy ID, GitHub, Shareconst middleItems: SoupEntityActionItem[] = [];if (canExecuteAll(renameAction.canExecute)) {@@ -306,6 +328,16 @@ export function createSoupEntityActions(});}+ if (entities.length === 1 && archiveSessionAction.canExecute(entities[0])) {+ middleItems.push({+ id: 'archive-session',+ label: archiveSessionAction.isArchived(entities[0])+ ? t('entityActions.unarchive')+ : t('entityActions.archive'),+ onClick: () => archiveSessionAction.execute(entities),+ });+ }+// Sits with Rename because it edits the same channel identity, under the// same participant rule. Single-entity only: one upload, one channel.if (entities.length === 1 && channelPictureAction.canExecute(entities[0])) {@@ -394,6 +426,44 @@ export function createSoupEntityActions(});}+ // The task properties the hotkeys and command menu set, as the CRM group+ // below sets a company's.+ if (canExecuteAll(isTaskEntity)) {+ for (const [propertyId, label, hotkeyToken] of [+ [+ SYSTEM_PROPERTY_IDS.STATUS,+ t('entityActions.setStatus'),+ TOKENS.entity.action.status,+ ],+ [+ SYSTEM_PROPERTY_IDS.PRIORITY,+ t('entityActions.setPriority'),+ TOKENS.entity.action.priority,+ ],+ [+ SYSTEM_PROPERTY_IDS.ASSIGNEES,+ t('entityActions.setAssignee'),+ TOKENS.entity.action.assignee,+ ],+ ] as const) {+ const property = taskProperty(propertyId);+ if (!property) continue;+ middleItems.push({+ id: `set-${propertyId}`,+ label,+ hotkeyToken,+ onClick: () =>+ openPropertyEditor(entities, 'direct', property, {+ restoreFocus: () =>+ fireAndForget(+ restoreSoupFocus(entities[0]?.id),+ 'entity-actions'+ ),+ }),+ });+ }+ }+if (canExecuteAll(moveToProjectAction.canExecute)) {middleItems.push({id: 'move-to-folder',@@ -439,11 +509,37 @@ export function createSoupEntityActions(});}- middleItems.push({- id: 'copy-entity-id',- label: t('entityActions.copyId'),- onClick: handle(copyEntityIdAction.executeWithSoup),- });+ if (downloadAction.canExecute(entities[0])) {+ middleItems.push({+ id: 'download',+ label: t('entityActions.download'),+ onClick: handle(downloadAction.executeWithSoup),+ });+ }++ if (copyEntityIdAction.canExecute(entities[0])) {+ middleItems.push({+ id: 'copy-entity-id',+ label: t('entityActions.copyId'),+ onClick: handle(copyEntityIdAction.executeWithSoup),+ });+ }++ const entity = entities[0];+ if (githubLinkAction.canExecute(entity)) {+ middleItems.push(+ {+ id: 'copy-github-link',+ label: t('entityActions.copyGithubLink'),+ onClick: () => githubLinkAction.copy(entity),+ },+ {+ id: 'open-on-github',+ label: t('entityActions.openOnGitHub'),+ onClick: () => githubLinkAction.open(entity),+ }+ );+ }if (shareAction.canExecute(entities[0])) {middleItems.push({@@ -457,9 +553,14 @@ export function createSoupEntityActions(// Sender group: Sender → Signal, Sender → Noise, Block Senderconst senderItems: SoupEntityActionItem[] = [];+ // Each email's own bucket decides, falling back to the view's tab; with+ // neither known (some Search rows), both moves are offered.+ const senderBucketOf = (entity: EntityData) =>+ emailSenderBucket(entity) ?? viewContext.senderBucket;+if (- viewContext.senderBucket === 'noise' &&- canExecuteAll(markSenderSignalAction.canExecute)+ canExecuteAll(markSenderSignalAction.canExecute) &&+ entities.some((entity) => senderBucketOf(entity) !== 'signal')) {senderItems.push({id: 'sender-signal',@@ -469,8 +570,8 @@ export function createSoupEntityActions(}if (- viewContext.senderBucket === 'signal' &&- canExecuteAll(markSenderNoiseAction.canExecute)+ canExecuteAll(markSenderNoiseAction.canExecute) &&+ entities.some((entity) => senderBucketOf(entity) !== 'noise')) {senderItems.push({id: 'sender-noise',diff --git a/apps/web/src/features/tasks-view/tasks-board.test.tsx b/apps/web/src/features/tasks-view/tasks-board.test.tsxnew file mode 100644index 0000000000..abc33f5641--- /dev/null+++ b/apps/web/src/features/tasks-view/tasks-board.test.tsx@@ -0,0 +1,190 @@+import type {+ EntityActionListState,+ EntityActionViewContext,+} from '@app/features/next-soup/actions';+import type { EntityData } from '@entity';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ within,+} from '@solidjs/testing-library';+import type { Accessor } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { TaskBoardColumn, TaskBoardTask } from './core/task-board';+import { TasksBoard } from './tasks-board';+import { boardEntity } from './tests/task-board-fixture';++const mocks = vi.hoisted(() => ({+ menus: [] as {+ list: EntityActionListState;+ entities: EntityData[];+ viewContext: EntityActionViewContext;+ }[],+ openTask: vi.fn(() => true),+ save: vi.fn(async () => {}),+}));++const tasks: TaskBoardTask[] = [+ { id: 'brief', name: 'Write the brief', assigneeIds: [], projectIds: [] },+ { id: 'review', name: 'Review the draft', assigneeIds: [], projectIds: [] },+];+const columns: TaskBoardColumn[] = [+ {+ id: 'not-started',+ label: 'Not started',+ tasks,+ hasMore: false,+ loadingMore: false,+ },+];++vi.mock('./tasks-view-context', () => ({+ useTasksView: () => ({+ state: {+ tab: 'my-tasks',+ groupBy: 'status',+ search: '',+ facets: {},+ sort: [],+ },+ source: {+ items: () => [],+ isLoading: () => false,+ error: () => undefined,+ hasMore: () => false,+ isLoadingMore: () => false,+ },+ openTask: mocks.openTask,+ projectsEnabled: () => false,+ setFacets: vi.fn(),+ }),+}));+vi.mock('./queries/task-board-queries', () => ({+ createTaskBoardQueries: () => ({+ columns: () => columns,+ hiddenColumnCount: () => 0,+ task: (id: string) => tasks.find((task) => task.id === id),+ entity: (id: string) => boardEntity(id),+ actions: {+ canEditTask: () => true,+ canMoveTo: () => true,+ save: mocks.save,+ },+ property: () => undefined,+ canEditProperty: () => false,+ saveProperty: async () => {},+ definitionError: () => false,+ retryDefinitions: async () => {},+ }),+}));+vi.mock('@components/app/split-layout/layoutUtils', () => ({+ useSplitPanelOrThrow: () => ({+ handle: {+ id: 'split',+ content: () => ({ type: 'component', id: 'tasks' }),+ },+ }),+}));+vi.mock('@components/app/split-layout/layout', () => ({+ useSplitLayout: () => ({ popoverSplit: vi.fn() }),+}));+vi.mock('@app/features/command/context/create-context', () => ({+ useCreateContext: () => ({ snapshot: () => ({}) }),+}));+vi.mock('@core/context/user', () => ({ useUserId: () => () => 'viewer' }));+vi.mock('@property/hooks/usePropertyUserDisplay', () => ({+ usePropertyUserDisplay: () => ({ name: () => undefined }),+}));+// The real menu builds its items from live queries; record what it was asked+// for and offer two fixed actions instead.+vi.mock('@app/features/soup/createSoupEntityActions', () => ({+ createSoupEntityActions: () => ({+ buildActionGroups: (+ list: EntityActionListState,+ entities: EntityData[],+ options: { viewContext: EntityActionViewContext }+ ) => {+ mocks.menus.push({ list, entities, viewContext: options.viewContext });+ return [+ {+ items: [+ { id: 'rename', label: 'Rename', onClick: () => {} },+ { id: 'delete', label: 'Delete', onClick: () => {} },+ ],+ },+ ];+ },+ }),+ viewedProjectIdFromContent: () => undefined,+}));+// Mount every column and card without layout measurement.+vi.mock('@app/components/kanban/kanban-virtualizer', () => ({+ createKanbanVirtualizer: (options: {+ keys: Accessor<readonly (string | number)[]>;+ getScrollElement: () => HTMLDivElement | undefined;+ }) => ({+ get scrollElement() {+ return options.getScrollElement();+ },+ getVirtualItems: () =>+ options+ .keys()+ .map((key, index) => ({ key, index, start: index * 100, size: 100 })),+ getTotalSize: () => options.keys().length * 100,+ scrollToIndex: vi.fn(),+ measureElement: vi.fn(),+ takeSnapshot: () => [],+ }),+}));++let motionStyles: HTMLStyleElement;+beforeEach(() => {+ motionStyles = document.createElement('style');+ motionStyles.textContent =+ '[role="menu"] { animation-name: none; transition-duration: 0s; }';+ document.head.append(motionStyles);+ vi.stubGlobal('scrollTo', vi.fn());+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe = vi.fn();+ unobserve = vi.fn();+ disconnect = vi.fn();+ }+ );+});+afterEach(() => {+ cleanup();+ motionStyles.remove();+ mocks.menus = [];+ vi.clearAllMocks();+ vi.unstubAllGlobals();+});++it('opens the right-clicked card’s task actions without opening or moving it', async () => {+ render(() => <TasksBoard />);+ const title = screen.getByRole('button', { name: 'Review the draft' });++ fireEvent.mouseDown(title, { button: 2, clientX: 40, clientY: 40 });+ // Keyboard users raise the same event with Shift+F10 on the focused title.+ expect(fireEvent.contextMenu(title, { clientX: 40, clientY: 40 })).toBe(+ false+ );+ fireEvent.mouseMove(document, { clientX: 400, clientY: 40 });+ fireEvent.mouseUp(document, { button: 2, clientX: 400, clientY: 40 });++ const menu = await screen.findByRole('menu');+ expect(+ within(menu)+ .getAllByRole('menuitem')+ .map((item) => item.textContent)+ ).toEqual(['Rename', 'Delete']);+ const opened = mocks.menus.at(-1);+ expect(opened?.entities.map((entity) => entity.id)).toEqual(['review']);+ expect(opened?.list.items.count()).toBe(1);+ expect(opened?.viewContext.supportsOpenInNewSplit).toBe(true);+ expect(mocks.openTask).not.toHaveBeenCalled();+ expect(mocks.save).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/tasks-view/tasks-board.tsx b/apps/web/src/features/tasks-view/tasks-board.tsxindex 6257a9d66b..78e104dcc3 100644--- a/apps/web/src/features/tasks-view/tasks-board.tsx+++ b/apps/web/src/features/tasks-view/tasks-board.tsx@@ -1,12 +1,17 @@import { useCreateContext } from '@app/features/command/context/create-context';+import {+ resolveEntityActionViewContext,+ toSingleEntityActionListState,+} from '@app/features/next-soup/actions';import { openEntityInSplitFromUnifiedList } from '@app/features/next-soup/utils';+import { SoupEntityContextMenu } from '@app/features/soup';import { useSplitLayout } from '@components/app/split-layout/layout';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { useUserId } from '@core/context/user';import { fireAndForget } from '@core/util/fireAndForget';import { usePropertyUserDisplay } from '@property/hooks/usePropertyUserDisplay';-import type { Accessor } from 'solid-js';-import { toTaskBoardGrouping } from './core/task-board';+import { type Accessor, type JSX, Show } from 'solid-js';+import { type TaskBoardTask, toTaskBoardGrouping } from './core/task-board';import { createTaskBoardQueries } from './queries/task-board-queries';import { taskBoardComposerContext } from './task-composer';import { useTasksView } from './tasks-view-context';@@ -34,6 +39,31 @@ export function TasksBoard(props: { ref?: (element: HTMLDivElement) => void }) {usePropertyUserDisplay(id).name,};+ const viewContext = () =>+ resolveEntityActionViewContext({+ activeListView: panel.handle.content().id,+ activeTab: state.tab,+ });+ // Cards have no selection, so like Gantt bars the menu acts on its own task.+ const renderCard = (task: Accessor<TaskBoardTask>, content: JSX.Element) => {+ const entity = () => data.entity(task().id);+ return (+ <Show when={entity()} fallback={content}>+ {(current) => (+ <SoupEntityContextMenu+ as="div"+ entity={current()}+ list={toSingleEntityActionListState(entity)}+ selectedEntities={() => []}+ viewContext={viewContext()}+ >+ {content}+ </SoupEntityContextMenu>+ )}+ </Show>+ );+ };+const canCreate = () => !!context.createTask || !context.scopeKey;const createTask = (columnId: string) => {if (!canCreate()) return;@@ -60,6 +90,7 @@ export function TasksBoard(props: { ref?: (element: HTMLDivElement) => void }) {ref={props.ref}data={data}onCreate={canCreate() ? createTask : undefined}+ renderCard={renderCard}onOpen={(task, event) => {const opened = openTask({ id: task.id, fallbackName: task.name },diff --git a/apps/web/src/features/tasks-view/views/task-board-view.tsx b/apps/web/src/features/tasks-view/views/task-board-view.tsxindex 5d2bf167fb..014401d80b 100644--- a/apps/web/src/features/tasks-view/views/task-board-view.tsx+++ b/apps/web/src/features/tasks-view/views/task-board-view.tsx@@ -4,7 +4,14 @@ import PlusIcon from '@icon/system/regular/plus.svg';import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';import { hasValue } from '@property/utils/typeGuards';import { Button } from '@ui/components/Button';-import { type Accessor, createSignal, For, Show, Suspense } from 'solid-js';+import {+ type Accessor,+ createSignal,+ For,+ type JSX,+ Show,+ Suspense,+} from 'solid-js';import { TaskBoard } from '../components/task-board';import {TaskBoardColumnIcon,@@ -32,6 +39,11 @@ export function TaskBoardView(props: {data: TaskBoardData;onOpen(task: TaskBoardTask, event: MouseEvent): void;onCreate?: (columnId: string) => void;+ /** Wraps a card's content, such as in the host's context menu. */+ renderCard: (+ task: Accessor<TaskBoardTask>,+ content: JSX.Element+ ) => JSX.Element;ref?: (element: HTMLDivElement) => void;}) {const { state, source, projectsEnabled, setFacets } = useTasksView();@@ -140,7 +152,7 @@ export function TaskBoardView(props: {</Show>);- const renderCard = (+ const renderCardContent = (task: Accessor<TaskBoardTask>,readOnly: Accessor<boolean>) => (@@ -305,7 +317,10 @@ export function TaskBoardView(props: {pending={board.pending(task().id)}onOpen={props.onOpen}>- {renderCard(task, readOnly)}+ {props.renderCard(+ task,+ renderCardContent(task, readOnly)+ )}</TaskBoard.Card>);}}diff --git a/apps/web/src/lib/core/component/DocumentDownloadButton.tsx b/apps/web/src/lib/core/component/DocumentDownloadButton.tsxindex 058d6a7a78..9cdc0ccfe2 100644--- a/apps/web/src/lib/core/component/DocumentDownloadButton.tsx+++ b/apps/web/src/lib/core/component/DocumentDownloadButton.tsx@@ -1,42 +1,11 @@import { createFileDownload } from '@core/util/createFileDownload';-import { catchToResult } from '@core/util/result';-import {- getFileDocumentBlob,- loadFileDocumentData,-} from '@queries/storage/file-document';-import { formatDocumentName } from '@service-storage/util/filename';+import { storedDocumentDownloadSource } from '@queries/storage/document-download';import { FileDownloadButton } from './FileDownload';/** Downloads a linked file without opening its viewer or loading it on hover. */export function DocumentDownloadButton(props: { documentId: string }) {- const download = createFileDownload(() => {- const documentId = props.documentId;- return {- id: documentId,- name: 'download',- load: (options) =>- catchToResult(async () => {- const { documentMetadata } = await loadFileDocumentData(- documentId,- options- );- options.signal.throwIfAborted();- return {- blob: await getFileDocumentBlob(- {- documentId,- documentVersionId: documentMetadata.documentVersionId,- },- options- ),- name: formatDocumentName(- documentMetadata.documentName || 'download',- documentMetadata.fileType,- { caseInsensitiveSuffix: true }- ),- };- }),- };- });+ const download = createFileDownload(() =>+ storedDocumentDownloadSource(props.documentId)+ );return <FileDownloadButton download={download} iconOnly />;}diff --git a/apps/web/src/lib/core/component/FileList/itemOperations.ts b/apps/web/src/lib/core/component/FileList/itemOperations.tsindex 681bd4e077..9002e8702f 100644--- a/apps/web/src/lib/core/component/FileList/itemOperations.ts+++ b/apps/web/src/lib/core/component/FileList/itemOperations.ts@@ -390,9 +390,17 @@ export async function bulkMoveToFolder(};}-/** NOTE: Currently we do not support copying projects */+/**+ * Whether an item type can be duplicated. Folders copy with their contents+ * only through the GraphQL entity mutation, which has no REST counterpart.+ */+export function canDuplicateItemType(itemType: ItemType): boolean {+ if (itemType === 'document' || itemType === 'chat') return true;+ return itemType === 'project' && isFeatureEnabled(enableGraphqlSoup);+}+export async function copyItem(args: {- itemType: Exclude<ItemType, 'project'>;+ itemType: ItemType;id: string;name: string;}): Promise<string | null> {@@ -405,13 +413,13 @@ export async function copyItem(args: {let newId = '';if (isFeatureEnabled(enableGraphqlSoup) &&- (itemType === 'document' || itemType === 'chat')+ (itemType === 'document' || itemType === 'chat' || itemType === 'project')) {const result = await catchToResult(() =>duplicateEntity({ type: ENTITY_TYPES[itemType], id },// The REST chat endpoint also ignores the supplied name and names the copy itself.- itemType === 'document' ? createCopyName(name) : undefined+ itemType === 'chat' ? undefined : createCopyName(name)));if (itemType === 'chat' && isPaymentError(result)) showPaywall();@@ -470,7 +478,7 @@ export async function bulkCopy(const results = await Promise.allSettled(chunk.map((item) =>copyItem({- itemType: item.type as Exclude<ItemType, 'project'>,+ itemType: item.type,id: item.id,name: item.name,})diff --git a/apps/web/src/lib/core/component/FileList/useItemOperations.ts b/apps/web/src/lib/core/component/FileList/useItemOperations.tsindex 4e37c22a30..b27cb702a9 100644--- a/apps/web/src/lib/core/component/FileList/useItemOperations.ts+++ b/apps/web/src/lib/core/component/FileList/useItemOperations.ts@@ -1,3 +1,4 @@+import { t } from '@app/lib/i18n';import { DEV_MODE_ENV } from '@core/constant/featureFlags';import {getDeletedItems,@@ -80,17 +81,17 @@ export const useItemOperations = createSingletonRoot(() => {);const copyItem = createCallback(- async (args: {- itemType: Exclude<ItemType, 'project'>;- id: string;- name: string;- }) => {+ async (args: { itemType: ItemType; id: string; name: string }) => {const id = await copyItemOp(args);const success = id !== null;if (success) {toast.success(`${args.name} copied`);+ } else if (args.itemType === 'project') {+ toast.failure(t('entityActions.toastDuplicateFolderFailed'), {+ subtext: t('entityActions.folderDuplicateLimitHint'),+ });} else {- toast.failure('Unable to copy item');+ toast.failure(t('entityActions.toastCopyFailed', { count: 1 }));}return id;}diff --git a/apps/web/src/lib/i18n/locales/en/entity-actions.ts b/apps/web/src/lib/i18n/locales/en/entity-actions.tsindex e900be9251..a838ffcae6 100644--- a/apps/web/src/lib/i18n/locales/en/entity-actions.ts+++ b/apps/web/src/lib/i18n/locales/en/entity-actions.ts@@ -201,4 +201,32 @@ export default {},toastRenameFailed: 'Failed to rename',toastFolderUpdateFailed: 'Failed to update folder',+ toastCopyFailed: {+ one: 'Unable to copy item',+ other: 'Unable to copy items',+ },+ toastDuplicateFolderFailed: 'Unable to duplicate folder',+ folderDuplicateLimitHint:+ 'Folders with more than 100 files, chats, and subfolders can’t be duplicated.',+ toastGithubLinkCopied: 'GitHub link copied to clipboard',+ toastBranchNameCopied: 'Branch name copied to clipboard',+ download: 'Download',+ copyGithubLink: 'Copy GitHub Link',+ prMerge: 'Merge',+ prMerging: 'Merging…',+ prMergeWaitsOnChecksTooltip: 'Merge is available once every check passes',+ prReadyForReview: 'Ready for review',+ prConvertToDraft: 'Convert to draft',+ prClose: 'Close pull request',+ prReopen: 'Reopen pull request',+ prActions: 'Pull request actions',+ prMoreActions: 'More pull request actions',+ toastPrReopened: 'Reopened {{name}}',+ toastPrReopenFailed: 'Failed to reopen pull request',+ toastPrReadyForReview: 'Ready for review: {{name}}',+ toastPrReadyForReviewFailed: 'Failed to mark pull request ready for review',+ toastPrConvertedToDraft: 'Converted to draft: {{name}}',+ toastPrConvertToDraftFailed: 'Failed to convert pull request to a draft',+ toastPrClosed: 'Closed {{name}}',+ toastPrCloseFailed: 'Failed to close pull request',};diff --git a/apps/web/src/lib/queries/favorites/favorites.ts b/apps/web/src/lib/queries/favorites/favorites.tsindex 5211902e20..be43af273c 100644--- a/apps/web/src/lib/queries/favorites/favorites.ts+++ b/apps/web/src/lib/queries/favorites/favorites.ts@@ -65,6 +65,10 @@ export function favoriteEntityType(return 'crm_contact';case 'foreign':return 'foreign_entity';+ case 'database':+ return 'database';+ case 'form':+ return 'form';default:return undefined;}diff --git a/apps/web/src/lib/queries/storage/document-download.ts b/apps/web/src/lib/queries/storage/document-download.tsnew file mode 100644index 0000000000..8dbd7ee204--- /dev/null+++ b/apps/web/src/lib/queries/storage/document-download.ts@@ -0,0 +1,64 @@+import type { DownloadSource } from '@core/util/createFileDownload';+import { catchToResult } from '@core/util/result';+import { downloadExportedDocument } from '@service-storage/util/downloadExportedDocument';+import { formatDocumentName } from '@service-storage/util/filename';+import { getFileDocumentBlob, loadFileDocumentData } from './file-document';++const DOCX_MIME =+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';++/**+ * An uploaded document's latest stored file under its own name and+ * extension, fetched without opening its viewer.+ */+export function storedDocumentDownloadSource(+ documentId: string+): DownloadSource {+ return {+ id: documentId,+ name: 'download',+ load: (options) =>+ catchToResult(async () => {+ const { documentMetadata } = await loadFileDocumentData(+ documentId,+ options+ );+ options.signal.throwIfAborted();+ return {+ blob: await getFileDocumentBlob(+ {+ documentId,+ documentVersionId: documentMetadata.documentVersionId,+ },+ options+ ),+ name: formatDocumentName(+ documentMetadata.documentName || 'download',+ documentMetadata.fileType,+ { caseInsensitiveSuffix: true }+ ),+ };+ }),+ };+}++/**+ * A Word document as document storage rebuilds it from its stored parts,+ * named like the Word editor's own download.+ */+export function exportedDocxDownloadSource(+ documentId: string,+ documentName: string+): DownloadSource {+ return {+ id: documentId,+ name: formatDocumentName(documentName || 'Document', 'docx', {+ caseInsensitiveSuffix: true,+ }),+ load: () =>+ catchToResult(async () => {+ const bytes = await downloadExportedDocument({ documentId });+ return { blob: new Blob([bytes.slice().buffer], { type: DOCX_MIME }) };+ }),+ };+}diff --git a/apps/web/src/lib/queries/storage/entity-mutations.ts b/apps/web/src/lib/queries/storage/entity-mutations.tsindex 237fd92a75..24c5317578 100644--- a/apps/web/src/lib/queries/storage/entity-mutations.ts+++ b/apps/web/src/lib/queries/storage/entity-mutations.ts@@ -72,7 +72,10 @@ export async function duplicateEntity(if ((entity.type === 'DOCUMENT' &&effect.item.__typename === 'GraphqlSoupDocument') ||- (entity.type === 'CHAT' && effect.item.__typename === 'GraphqlSoupChat')+ (entity.type === 'CHAT' &&+ effect.item.__typename === 'GraphqlSoupChat') ||+ (entity.type === 'PROJECT' &&+ effect.item.__typename === 'GraphqlSoupProject'))return effect.item.id;}diff --git a/apps/web/src/lib/queries/storage/pr-state.ts b/apps/web/src/lib/queries/storage/pr-state.tsnew file mode 100644index 0000000000..9e8cfc4aa9--- /dev/null+++ b/apps/web/src/lib/queries/storage/pr-state.ts@@ -0,0 +1,23 @@+import { throwOnErr } from '@core/util/result';+import { authServiceClient } from '@service-auth/client';+import type { SetGithubPullRequestStateRequest } from '@service-auth/generated/schemas';+import { useMutation } from '@tanstack/solid-query';+import { invalidateMergedPullRequestCaches } from './pr-merge';++export type SetGithubPullRequestStateInput = SetGithubPullRequestStateRequest;++/**+ * Close a GitHub pull request, or reopen it, as the signed-in user. A refusal+ * rejects with GitHub's message as the error text. The route patches the+ * stored entity before answering, so the same caches a merge refreshes are+ * refreshed here.+ */+export function useSetGithubPullRequestStateMutation() {+ return useMutation(() => ({+ mutationFn: async (input: SetGithubPullRequestStateInput) =>+ await throwOnErr(() =>+ authServiceClient.setGithubPullRequestState(input)+ ),+ onSuccess: () => invalidateMergedPullRequestCaches(),+ }));+}diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex cd66148a7e..ec79c788b6 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -42,6 +42,8 @@ import type {SendMobileWelcomeEmailResponse,SetGithubPullRequestDraftRequest,SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest,+ SetGithubPullRequestStateResponse,TrialEligibility,UserQuota,} from './generated/schemas';@@ -292,7 +294,8 @@ const githubMergeErrorResponseHandler = githubChangeErrorResponseHandler({rejected: 'GitHub declined to merge the pull request',});-const githubDraftErrorResponseHandler = githubChangeErrorResponseHandler({+/** Shared by the draft and open/closed state routes, which fail the same ways. */+const githubUpdateErrorResponseHandler = githubChangeErrorResponseHandler({noLink: 'Connect GitHub in Settings to change pull requests',rejected: 'GitHub declined to change the pull request',});@@ -585,7 +588,19 @@ export const authServiceClient = {>(`${authHost}/github_pull_requests/draft`, {method: 'POST',body: JSON.stringify(args),- errorResponseHandler: githubDraftErrorResponseHandler,+ errorResponseHandler: githubUpdateErrorResponseHandler,+ })+ ).map((result) => result);+ },+ async setGithubPullRequestState(args: SetGithubPullRequestStateRequest) {+ return (+ await fetchWithAuth<+ SetGithubPullRequestStateResponse,+ GithubMergeErrorCode+ >(`${authHost}/github_pull_requests/state`, {+ method: 'POST',+ body: JSON.stringify(args),+ errorResponseHandler: githubUpdateErrorResponseHandler,})).map((result) => result);},diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex 8e32c03939..4c1696b18b 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -89,6 +89,8 @@ import type {SendMobileWelcomeEmailResponse,SetGithubPullRequestDraftRequest,SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest,+ SetGithubPullRequestStateResponse,SsoLoginParams,SsoRequiredResponse,StripeSessionResponse,@@ -1745,6 +1747,91 @@ export const getGithubPullRequestMergeability = async (} as getGithubPullRequestMergeabilityResponse;};+/**+ * @summary Closes a GitHub pull request, or reopens it, as the authenticated user+with their own GitHub grant.+ */+export type setGithubPullRequestStateResponse200 = {+ data: SetGithubPullRequestStateResponse;+ status: 200;+};++export type setGithubPullRequestStateResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type setGithubPullRequestStateResponse403 = {+ data: ErrorResponse;+ status: 403;+};++export type setGithubPullRequestStateResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type setGithubPullRequestStateResponse422 = {+ data: ErrorResponse;+ status: 422;+};++export type setGithubPullRequestStateResponse428 = {+ data: ErrorResponse;+ status: 428;+};++export type setGithubPullRequestStateResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type setGithubPullRequestStateResponseSuccess =+ setGithubPullRequestStateResponse200 & {+ headers: Headers;+ };+export type setGithubPullRequestStateResponseError = (+ | setGithubPullRequestStateResponse401+ | setGithubPullRequestStateResponse403+ | setGithubPullRequestStateResponse404+ | setGithubPullRequestStateResponse422+ | setGithubPullRequestStateResponse428+ | setGithubPullRequestStateResponse500+) & {+ headers: Headers;+};++export type setGithubPullRequestStateResponse =+ | setGithubPullRequestStateResponseSuccess+ | setGithubPullRequestStateResponseError;++export const getSetGithubPullRequestStateUrl = () => {+ return `/github_pull_requests/state`;+};++export const setGithubPullRequestState = async (+ setGithubPullRequestStateRequest: SetGithubPullRequestStateRequest,+ options?: RequestInit+): Promise<setGithubPullRequestStateResponse> => {+ const res = await fetch(getSetGithubPullRequestStateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(setGithubPullRequestStateRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: setGithubPullRequestStateResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as setGithubPullRequestStateResponse;+};+/*** @summary Lists invite links, newest first. Macro staff only.*/diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestState.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestState.tsnew file mode 100644index 0000000000..aa86746955--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestState.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether a pull request is open or closed, as a user sets it. Merging is a+separate action, so unlike `GithubPullRequestStatus` there is no merged+state.+ */+export type GithubPullRequestState =+ (typeof GithubPullRequestState)[keyof typeof GithubPullRequestState];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const GithubPullRequestState = {+ open: 'open',+ closed: 'closed',+} as const;diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex e1912550a9..7d80e03a6e 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -117,6 +117,7 @@ export * from './githubPullRequestReview';export * from './githubPullRequestReviewReviewerLogin';export * from './githubPullRequestReviewState';export * from './githubPullRequestReviewSubmittedAt';+export * from './githubPullRequestState';export * from './githubPullRequestStatus';export * from './githubPullRequestUser';export * from './githubPullRequestUserLogin';@@ -200,6 +201,9 @@ export * from './sendMobileWelcomeEmailResponse';export * from './setGithubPullRequestDraftRequest';export * from './setGithubPullRequestDraftResponse';export * from './setGithubPullRequestDraftResponsePullRequest';+export * from './setGithubPullRequestStateRequest';+export * from './setGithubPullRequestStateResponse';+export * from './setGithubPullRequestStateResponsePullRequest';export * from './ssoLoginParams';export * from './ssoRequiredResponse';export * from './stripeSessionResponse';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateRequest.tsnew file mode 100644index 0000000000..8bccf55f6a--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateRequest.ts@@ -0,0 +1,24 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { GithubPullRequestState } from './githubPullRequestState';++/**+ * A request to close one pull request, or reopen it, on the user's behalf.+ */+export interface SetGithubPullRequestStateRequest {+ /**+ * The GitHub pull request number.+ * @minimum 0+ */+ number: number;+ /** The GitHub repository owner or organization. */+ owner: string;+ /** The GitHub repository name. */+ repo: string;+ /** `closed` closes the pull request; `open` reopens it. */+ state: GithubPullRequestState;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateResponse.tsnew file mode 100644index 0000000000..69eb4347f2--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateResponse.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++import type { GithubPullRequestState } from './githubPullRequestState';+import type { SetGithubPullRequestStateResponsePullRequest } from './setGithubPullRequestStateResponsePullRequest';++/**+ * Response body for a pull request that was closed or reopened.+ */+export interface SetGithubPullRequestStateResponse {+ pullRequest?: SetGithubPullRequestStateResponsePullRequest;+ /** Whether the pull request is now open or closed. */+ state: GithubPullRequestState;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateResponsePullRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateResponsePullRequest.tsnew file mode 100644index 0000000000..a543700656--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/setGithubPullRequestStateResponsePullRequest.ts@@ -0,0 +1,10 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { EnrichedGithubPullRequest } from './enrichedGithubPullRequest';++export type SetGithubPullRequestStateResponsePullRequest =+ null | EnrichedGithubPullRequest;diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 22c26686a5..53b5a2db7d 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -1374,6 +1374,95 @@}}},+ "/github_pull_requests/state": {+ "post": {+ "tags": ["github_pull_requests"],+ "summary": "Closes a GitHub pull request, or reopens it, as the authenticated user\nwith their own GitHub grant.",+ "operationId": "set_github_pull_request_state",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetGithubPullRequestStateRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetGithubPullRequestStateResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "The user cannot change the pull request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "No GitHub link, or the pull request is not visible to the user",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "GitHub declined the change",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "428": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/gtm-invite/links": {"get": {"tags": ["gtm_invite"],@@ -6898,6 +6987,11 @@"description": "What a reviewer's latest review on a pull request said.","enum": ["approved", "changes_requested", "commented", "dismissed"]},+ "GithubPullRequestState": {+ "type": "string",+ "description": "Whether a pull request is open or closed, as a user sets it. Merging is a\nseparate action, so unlike `GithubPullRequestStatus` there is no merged\nstate.",+ "enum": ["open", "closed"]+ },"GithubPullRequestStatus": {"type": "string","description": "The normalized lifecycle status for a GitHub pull request.",@@ -7817,6 +7911,53 @@}}},+ "SetGithubPullRequestStateRequest": {+ "type": "object",+ "description": "A request to close one pull request, or reopen it, on the user's behalf.",+ "required": ["owner", "repo", "number", "state"],+ "properties": {+ "number": {+ "type": "integer",+ "format": "int64",+ "description": "The GitHub pull request number.",+ "minimum": 0+ },+ "owner": {+ "type": "string",+ "description": "The GitHub repository owner or organization."+ },+ "repo": {+ "type": "string",+ "description": "The GitHub repository name."+ },+ "state": {+ "$ref": "#/components/schemas/GithubPullRequestState",+ "description": "`closed` closes the pull request; `open` reopens it."+ }+ }+ },+ "SetGithubPullRequestStateResponse": {+ "type": "object",+ "description": "Response body for a pull request that was closed or reopened.",+ "required": ["state"],+ "properties": {+ "pullRequest": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EnrichedGithubPullRequest",+ "description": "The pull request as GitHub reports it after the change, when the\nrefresh succeeded."+ }+ ]+ },+ "state": {+ "$ref": "#/components/schemas/GithubPullRequestState",+ "description": "Whether the pull request is now open or closed."+ }+ }+ },"SsoRequiredResponse": {"type": "object","required": ["idp_id"],diff --git a/apps/web/src/lib/utils/favorites.ts b/apps/web/src/lib/utils/favorites.tsindex 0d9b74e3a3..e0565ac659 100644--- a/apps/web/src/lib/utils/favorites.ts+++ b/apps/web/src/lib/utils/favorites.ts@@ -87,6 +87,8 @@ function favoritePreviewEntity(favorite: Favorite): ItemEntity | undefined {case 'project':case 'call':case 'crm_company':+ case 'database':+ case 'form':return { id: favorite.entityId, type: favorite.entityType };default:return undefined;diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex 37d61aff5c..2579bddde0 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -73,6 +73,7 @@"auth.enrichGithubPullRequests": "Enrich Github Pull Requests","auth.mergeGithubPullRequest": "Merge Github Pull Request","auth.getGithubPullRequestMergeability": "Get Github Pull Request Mergeability",+ "auth.setGithubPullRequestState": "Set Github Pull Request State","auth.listGtmInviteLinks": "List Gtm Invite Links","auth.createGtmInviteLink": "Create Gtm Invite Link","auth.revokeGtmInviteLink": "Revoke Gtm Invite Link",diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex ba42292460..11ed02f191 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -9,7 +9,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=y.pop()??"";for(let a of y){let i=a.split(``),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},A7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},C7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},gj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(A7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=P7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},yj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=C7(x),X=Object.entries(S).map(([K,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var F7=/\{[^{}]+\}/g,E7=({path:$,url:O})=>{let j=O,x=O.match(F7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,gj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,yj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},J2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=E7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function dx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var V2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=gj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=yj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=CO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},L2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},w7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function N2($){for(let O of $.security??[]){if(w7($,O.name))continue;let j=await V2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var lx=($)=>J2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),rx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=hj($.headers,O.headers),j},q7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},hj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?q7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class vj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var U2=()=>({error:new vj,request:new vj,response:new vj}),f7=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),b7={"Content-Type":"application/json"},jj=($={})=>({...W2,headers:b7,parseAs:"auto",querySerializer:f7,...$});var px=($={})=>{let O=rx(jj(),$),j=()=>({...O}),x=(Q)=>{return O=rx(O,Q),j()},S=U2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await N2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=lx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:dx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?L2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return Q2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:dx(I),url:z})};return{buildUrl:(Q)=>lx({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var z2=px(jj());class I2{client;constructor($){this.client=$?.client??z2}}class T2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends I2{static __registry=new T2;constructor($){super($);mj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function H2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{T.removeEventListener("abort",g),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var P7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},A7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},C7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},gj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((K)=>encodeURIComponent(K))).join(A7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let G=P7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return CO({allowReserved:$,name:j,value:X})}).join(G);return x==="label"||x==="matrix"?G+Z:Z},CO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},yj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:G})=>{if(S instanceof Date)return G?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let K=[];Object.entries(S).forEach(([Q,J])=>{K=[...K,Q,$?J:encodeURIComponent(J)]});let L=K.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=C7(x),X=Object.entries(S).map(([K,L])=>CO({allowReserved:$,name:x==="deepObject"?`${j}[${K}]`:K,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var F7=/\{[^{}]+\}/g,E7=({path:$,url:O})=>{let j=O,x=O.match(F7);if(x)for(let S of x){let G=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))G=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let K=$[Z];if(K===void 0||K===null)continue;if(Array.isArray(K)){j=j.replace(S,gj({explode:G,name:Z,style:X,value:K}));continue}if(typeof K==="object"){j=j.replace(S,yj({explode:G,name:Z,style:X,value:K,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${CO({name:Z,value:K})}`);continue}let L=encodeURIComponent(X==="label"?`.${K}`:K);j=j.replace(S,L)}return j},J2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let G=S.startsWith("/")?S:`/${S}`,Z=($??"")+G;if(O)Z=E7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function dx($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var V2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var W2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var B2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let G in x){let Z=x[G];if(Z===void 0||Z===null)continue;let X=$[G]||O;if(Array.isArray(Z)){let K=gj({allowReserved:X.allowReserved,explode:!0,name:G,style:"form",value:Z,...X.array});if(K)S.push(K)}else if(typeof Z==="object"){let K=yj({allowReserved:X.allowReserved,explode:!0,name:G,style:"deepObject",value:Z,...X.object});if(K)S.push(K)}else{let K=CO({allowReserved:X.allowReserved,name:G,value:Z});if(K)S.push(K)}}return S.join("&")}},L2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},w7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function N2($){for(let O of $.security??[]){if(w7($,O.name))continue;let j=await V2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var lx=($)=>J2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:B2($.querySerializer),url:$.url}),rx=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=hj($.headers,O.headers),j},q7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},hj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?q7(j):Object.entries(j);for(let[S,G]of x)if(G===null)O.delete(S);else if(Array.isArray(G))for(let Z of G)O.append(S,Z);else if(G!==void 0)O.set(S,typeof G==="object"?JSON.stringify(G):G)}return O};class vj{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var U2=()=>({error:new vj,request:new vj,response:new vj}),f7=B2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),b7={"Content-Type":"application/json"},jj=($={})=>({...W2,headers:b7,parseAs:"auto",querySerializer:f7,...$});var px=($={})=>{let O=rx(jj(),$),j=()=>({...O}),x=(Q)=>{return O=rx(O,Q),j()},S=U2(),G=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:hj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await N2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=lx(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await G(Q),T={redirect:"follow",...V,body:dx(V)};z=new Request(B,T);for(let N of S.request.fns)if(N)z=await N(z,V);let C=V.fetch;W=await C(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?L2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let _=await W.text(),w;try{w=JSON.parse(_)}catch{}throw w??_}catch(V){let B=V;for(let T of S.error.fns)if(T)B=await T(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),K=(Q)=>async(J)=>{let{opts:I,url:z}=await G(J);return Q2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let T of S.request.fns)if(T)B=await T(B,I);return B},serializedBody:dx(I),url:z})};return{buildUrl:(Q)=>lx({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:K("CONNECT"),delete:K("DELETE"),get:K("GET"),head:K("HEAD"),options:K("OPTIONS"),patch:K("PATCH"),post:K("POST"),put:K("PUT"),trace:K("TRACE")},trace:X("TRACE")}};var z2=px(jj());class I2{client;constructor($){this.client=$?.client??z2}}class T2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class mj extends I2{static __registry=new T2;constructor($){super($);mj.__registry.set(this,$?.key)}deleteAgentApiKey($){return($.client??this.client).delete({url:"/agents/{agent_id}/api-key",...$})}getAgentApiKey($){return($.client??this.client).get({url:"/agents/{agent_id}/api-key",...$})}putAgentApiKey($){return($.client??this.client).put({url:"/agents/{agent_id}/api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingAutoReload($){return($.client??this.client).patch({url:"/ai-billing/auto-reload",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAiCreditCheckout($){return($.client??this.client).post({url:"/ai-billing/credits/checkout",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateAiBillingOverage($){return($.client??this.client).patch({url:"/ai-billing/overage",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAiBillingPlans($){return($?.client??this.client).get({url:"/ai-billing/plans",...$})}getAiBillingSummary($){return($?.client??this.client).get({url:"/ai-billing/summary",...$})}disconnectCodex($){return($?.client??this.client).delete({url:"/codex",...$})}getCodexConnection($){return($?.client??this.client).get({url:"/codex",...$})}configureCodex($){return($.client??this.client).put({url:"/codex/config",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCodexEnvironments($){return($?.client??this.client).get({url:"/codex/environments",...$})}startCodexLogin($){return($?.client??this.client).post({url:"/codex/login",...$})}cancelCodexLogin($){return($.client??this.client).delete({url:"/codex/login/{attempt_id}",...$})}pollCodexLogin($){return($.client??this.client).get({url:"/codex/login/{attempt_id}",...$})}deleteCursorApiKey($){return($?.client??this.client).delete({url:"/cursor-api-key",...$})}getCursorApiKey($){return($?.client??this.client).get({url:"/cursor-api-key",...$})}putCursorApiKey($){return($.client??this.client).put({url:"/cursor-api-key",...$,headers:{"Content-Type":"application/json",...$.headers}})}putCursorDefaultModel($){return($.client??this.client).put({url:"/cursor-api-key/default-model",...$,headers:{"Content-Type":"application/json",...$.headers}})}listCursorModels($){return($?.client??this.client).get({url:"/cursor-api-key/models",...$})}verifyFusionauthUserEmail($){return($.client??this.client).get({url:"/email/fusionauth/verify/{verification_id}",...$})}resendFusionauthVerifyUserEmail($){return($.client??this.client).post({url:"/email/fusionauth_resend",...$,headers:{"Content-Type":"application/json",...$.headers}})}generateEmailLink($){return($.client??this.client).post({url:"/email/generate/link",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyEmailLink($){return($.client??this.client).get({url:"/email/verify/{verification_id}",...$})}setGithubPullRequestDraft($){return($.client??this.client).post({url:"/github_pull_requests/draft",...$,headers:{"Content-Type":"application/json",...$.headers}})}enrichGithubPullRequests($){return($.client??this.client).post({url:"/github_pull_requests/enrich",...$,headers:{"Content-Type":"application/json",...$.headers}})}mergeGithubPullRequest($){return($.client??this.client).post({url:"/github_pull_requests/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}getGithubPullRequestMergeability($){return($.client??this.client).post({url:"/github_pull_requests/mergeability",...$,headers:{"Content-Type":"application/json",...$.headers}})}setGithubPullRequestState($){return($.client??this.client).post({url:"/github_pull_requests/state",...$,headers:{"Content-Type":"application/json",...$.headers}})}listGtmInviteLinks($){return($?.client??this.client).get({url:"/gtm-invite/links",...$})}createGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/links",...$,headers:{"Content-Type":"application/json",...$.headers}})}revokeGtmInviteLink($){return($.client??this.client).delete({url:"/gtm-invite/links/{id}",...$})}getGtmInviteOffer($){return($?.client??this.client).get({url:"/gtm-invite/offer",...$})}resolveGtmInviteLink($){return($.client??this.client).get({url:"/gtm-invite/public/{token}",...$})}redeemGtmInviteLink($){return($.client??this.client).post({url:"/gtm-invite/redeem",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}macroApiToken($){return($.client??this.client).get({url:"/jwt/macro_api_token",...$})}refresh($){return($?.client??this.client).post({url:"/jwt/refresh",...$})}createInProgressLink($){return($?.client??this.client).post({url:"/link",...$})}emailConnectionProviders($){return($?.client??this.client).get({url:"/link/email/providers",...$})}deleteGithubLink($){return($?.client??this.client).delete({url:"/link/github",...$})}initGithubLink($){return($.client??this.client).post({url:"/link/github",...$})}checkGithubLinkStatus($){return($?.client??this.client).get({url:"/link/github/status",...$})}initGmailLink($){return($.client??this.client).post({url:"/link/gmail",...$})}checkGmailLinkStatus($){return($?.client??this.client).get({url:"/link/gmail/status",...$})}initOutlookLink($){return($?.client??this.client).post({url:"/link/outlook",...$})}appleLogin($){return($.client??this.client).post({url:"/login/apple",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordLogin($){return($.client??this.client).post({url:"/login/password",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessLogin($){return($.client??this.client).post({url:"/login/passwordless",...$,headers:{"Content-Type":"application/json",...$.headers}})}ssoLogin($){return($.client??this.client).get({url:"/login/sso",...$})}logout($){return($?.client??this.client).post({url:"/logout",...$})}createMergeRequest($){return($.client??this.client).post({url:"/merge",...$,headers:{"Content-Type":"application/json",...$.headers}})}verifyMergeRequest($){return($.client??this.client).get({url:"/merge/verify/{code}",...$})}sendMobileWelcomeEmail($){return($.client??this.client).post({url:"/mobile-welcome-email",...$,headers:{"Content-Type":"application/json",...$.headers}})}passwordlessCallback($){return($.client??this.client).get({url:"/oauth/passwordless/{code}",...$})}oauthRedirect($){return($?.client??this.client).get({url:"/oauth/redirect",...$})}oauth2Callback($){return($.client??this.client).get({url:"/oauth2/{provider}/callback",...$})}getPermissions($){return($?.client??this.client).get({url:"/permissions",...$})}getUserPermissions($){return($?.client??this.client).get({url:"/permissions/me",...$})}getReferralCode($){return($?.client??this.client).get({url:"/referral/code",...$})}sendReferralCode($){return($.client??this.client).post({url:"/referral/send",...$,headers:{"Content-Type":"application/json",...$.headers}})}sessionCreation($){return($?.client??this.client).post({url:"/session",...$})}sessionLogin($){return($.client??this.client).get({url:"/session/login/{session_code}",...$})}deleteTeam($){return($?.client??this.client).delete({url:"/team",...$})}getTeam($){return($?.client??this.client).get({url:"/team",...$})}patchTeam($){return($.client??this.client).patch({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}createTeam($){return($.client??this.client).post({url:"/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamAutoJoinDomain($){return($?.client??this.client).post({url:"/team/auto-join-domain/toggle",...$})}patchTeamCrmSettings($){return($.client??this.client).patch({url:"/team/crm",...$,headers:{"Content-Type":"application/json",...$.headers}})}inviteToTeam($){return($.client??this.client).post({url:"/team/invite",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteLink($){return($?.client??this.client).delete({url:"/team/invite-link",...$})}getTeamInviteLink($){return($?.client??this.client).get({url:"/team/invite-link",...$})}createTeamInviteLink($){return($?.client??this.client).post({url:"/team/invite-link",...$})}joinTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/join",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTeamByInviteLink($){return($.client??this.client).post({url:"/team/invite-link/team",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteTeamInviteHandler($){return($.client??this.client).delete({url:"/team/invite/{team_invite_id}",...$})}getTeamInvites($){return($?.client??this.client).get({url:"/team/invites",...$})}rejectInvitation($){return($.client??this.client).delete({url:"/team/join/{team_invite_id}",...$})}joinTeam($){return($.client??this.client).get({url:"/team/join/{team_invite_id}",...$})}patchTeamMemberPlan($){return($.client??this.client).patch({url:"/team/members/{member_user_id}/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}toggleTeamNonAdminInvites($){return($?.client??this.client).post({url:"/team/non-admin-invites/toggle",...$})}removeUserFromTeam($){return($.client??this.client).delete({url:"/team/remove/{remove_user_id}",...$})}getUserTeams($){return($?.client??this.client).get({url:"/team/user",...$})}getUserInvites($){return($?.client??this.client).get({url:"/team/user/invites",...$})}getUserNames($){return($.client??this.client).post({url:"/user/get_names",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserNamesWithEmail($){return($.client??this.client).post({url:"/user/get_names_with_email",...$,headers:{"Content-Type":"application/json",...$.headers}})}patchUserGroup($){return($.client??this.client).patch({url:"/user/group",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserLanguage($){return($?.client??this.client).get({url:"/user/language",...$})}putUserLanguage($){return($.client??this.client).put({url:"/user/language",...$,headers:{"Content-Type":"application/json",...$.headers}})}getLegacyUserPermissions($){return($?.client??this.client).get({url:"/user/legacy_user_permissions",...$})}getUserLinkExists($){return($.client??this.client).get({url:"/user/link_exists",...$})}deleteUser($){return($?.client??this.client).delete({url:"/user/me",...$})}getUserInfo($){return($?.client??this.client).get({url:"/user/me",...$})}getUserName($){return($?.client??this.client).get({url:"/user/name",...$})}putUserName($){return($?.client??this.client).put({url:"/user/name",...$})}patchUserOnboarding($){return($.client??this.client).patch({url:"/user/onboarding",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserOrganization($){return($?.client??this.client).get({url:"/user/organization",...$})}putProfilePicture($){return($.client??this.client).put({url:"/user/profile_picture",...$})}postProfilePictures($){return($.client??this.client).post({url:"/user/profile_pictures",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUserQuota($){return($?.client??this.client).get({url:"/user/quota",...$})}createCheckoutSessionV2($){return($.client??this.client).post({url:"/user/stripe/checkoutv2",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSubscriptionStatus($){return($?.client??this.client).get({url:"/user/stripe/plan",...$})}changePlan($){return($.client??this.client).post({url:"/user/stripe/plan",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPortalSession($){return($.client??this.client).post({url:"/user/stripe/portal",...$,headers:{"Content-Type":"application/json",...$.headers}})}getTrialEligibility($){return($?.client??this.client).get({url:"/user/stripe/trial_eligibility",...$})}patchUserTutorial($){return($.client??this.client).patch({url:"/user/tutorial",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function H2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:G,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:K,url:L,...Q}){let J,I=K??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=G??3000,B=0,T=Q.signal??new AbortController().signal;while(!0){if(T.aborted)break;B++;let C=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)C.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:C,signal:T},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{H.cancel()}catch{}};T.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await H.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`diff --git a/crates/favorites/src/domain/mutation_service.rs b/crates/favorites/src/domain/mutation_service.rsindex 6a42bcbecd..5883035954 100644--- a/crates/favorites/src/domain/mutation_service.rs+++ b/crates/favorites/src/domain/mutation_service.rs@@ -99,7 +99,9 @@ fn validate_favoritable(entity_type: EntityType) -> Result<(), FavoritesError> {| EntityType::CrmCompany| EntityType::CrmContact| EntityType::ExternalChat- | EntityType::AgentSession => Ok(()),+ | EntityType::AgentSession+ | EntityType::Database+ | EntityType::Form => Ok(()),EntityType::User| EntityType::Team| EntityType::ChannelMessage@@ -109,10 +111,8 @@ fn validate_favoritable(entity_type: EntityType) -> Result<(), FavoritesError> {| EntityType::Skill| EntityType::ScheduledAction| EntityType::Initiative- // Databases and forms are not favoritable yet, and rows never are.- | EntityType::Database| EntityType::CrmPipeline- | EntityType::DatabaseRow- | EntityType::Form => Err(FavoritesError::UnsupportedEntityType(entity_type)),+ // Database rows are never favoritable.+ | EntityType::DatabaseRow => Err(FavoritesError::UnsupportedEntityType(entity_type)),}}diff --git a/crates/favorites/src/domain/mutation_service/test.rs b/crates/favorites/src/domain/mutation_service/test.rsindex c365142160..ff0b415218 100644--- a/crates/favorites/src/domain/mutation_service/test.rs+++ b/crates/favorites/src/domain/mutation_service/test.rs@@ -360,6 +360,8 @@ async fn every_supported_interactive_entity_can_be_added_and_removed() {EntityType::CrmCompany,EntityType::CrmContact,EntityType::AgentSession,+ EntityType::Database,+ EntityType::Form,] {let favorites = Arc::new(FakeFavoritesService::default());let authorizer = Arc::new(FakeAuthorizer::default());diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rsindex d6698c603a..b71306c1d2 100644--- a/crates/github/src/domain/models.rs+++ b/crates/github/src/domain/models.rs@@ -22,10 +22,12 @@ pub use github_pull_requests::domain::models::{GithubPullRequestLabel, GithubPullRequestMerge, GithubPullRequestMergeability,GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest,GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef,- GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus,- GithubPullRequestUpdateRejection, GithubPullRequestUser, GithubRepositoryMergeSettings,- MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,- SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, latest_reviews,+ GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState,+ GithubPullRequestStatus, GithubPullRequestUpdateRejection, GithubPullRequestUser,+ GithubRepositoryMergeSettings, GithubStateOutcome, MergeGithubPullRequestRequest,+ MergeGithubPullRequestResponse, SetGithubPullRequestDraftRequest,+ SetGithubPullRequestDraftResponse, SetGithubPullRequestStateRequest,+ SetGithubPullRequestStateResponse, latest_reviews,};pub use installation_state::{InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rsindex 66c3182a1b..0e482df175 100644--- a/crates/github/src/domain/ports/link.rs+++ b/crates/github/src/domain/ports/link.rs@@ -7,9 +7,10 @@ use crate::domain::models::{GithubExchangeTokenResponse, GithubGrantLinkOutcome, GithubLink, GithubLinkStatus,GithubMergeMethod, GithubMergeOutcome, GithubPullRequestDetails,GithubPullRequestMergeabilityEntry, GithubPullRequestNumber, GithubPullRequestRef,- GithubRepositoryMergeSettings, GithubUserInfo, MergeGithubPullRequestRequest,- MergeGithubPullRequestResponse, SetGithubPullRequestDraftRequest,- SetGithubPullRequestDraftResponse,+ GithubPullRequestState, GithubRepositoryMergeSettings, GithubStateOutcome, GithubUserInfo,+ MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,+ SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};@@ -172,6 +173,17 @@ pub trait GithubOauth: Send + Sync + 'static {draft: bool,) -> impl Future<Output = Result<GithubDraftOutcome, Self::Err>> + Send;+ /// Closes a pull request, or reopens it, as the user. A change GitHub+ /// declines is a [`GithubStateOutcome::Rejected`] value, not an error.+ fn set_pull_request_state(+ &self,+ access_token: &str,+ owner: &str,+ repo: &str,+ number: u64,+ state: GithubPullRequestState,+ ) -> impl Future<Output = Result<GithubStateOutcome, Self::Err>> + Send;+/// Reads whether each pull request merges cleanly, as the user sees it./// Pull requests the user cannot see are left out.fn get_pull_request_mergeability(@@ -275,6 +287,17 @@ pub trait GithubLinkService: Send + Sync + 'static {request: SetGithubPullRequestDraftRequest,) -> impl Future<Output = Result<SetGithubPullRequestDraftResponse, GithubError>> + Send;+ /// Closes a pull request, or reopens it, as the user with their own+ /// GitHub grant.+ ///+ /// A change GitHub declines is+ /// [`GithubError::PullRequestUpdateRejected`] with GitHub's message.+ fn set_pull_request_state(+ &self,+ user_id: &MacroUserId<Lowercase<'static>>,+ request: SetGithubPullRequestStateRequest,+ ) -> impl Future<Output = Result<SetGithubPullRequestStateResponse, GithubError>> + Send;+/// Reads whether each pull request merges cleanly into its base, as the/// user sees it. More than/// [`GithubPullRequestMergeabilityRequest::MAX`](crate::domain::models::GithubPullRequestMergeabilityRequest::MAX)diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rsindex ff0533299b..ecb82989ae 100644--- a/crates/github/src/domain/service/link.rs+++ b/crates/github/src/domain/service/link.rs@@ -13,8 +13,9 @@ use crate::domain::{GithubGrantLinkOutcome, GithubLink, GithubLinkStatus, GithubMergeMethod,GithubMergeOutcome, GithubMergeRejection, GithubPullRequestMergeabilityEntry,GithubPullRequestMergeabilityRequest, GithubPullRequestNumber, GithubPullRequestRef,- MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,+ GithubStateOutcome, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse,},ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},};@@ -152,9 +153,10 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService>}}- /// The pull request as GitHub reports it after a merge or draft change,- /// written back to its foreign entities so the app shows the change- /// before the webhook arrives. Best-effort: the change already happened.+ /// The pull request as GitHub reports it after a merge, a draft change, or+ /// a close or reopen, written back to its foreign entities so the app+ /// shows the change before the webhook arrives. Best-effort: the change+ /// already happened.async fn refresh_changed_pull_request(&self,access_token: &GithubAccessToken,@@ -355,6 +357,43 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github})}+ #[tracing::instrument(skip(self), err)]+ async fn set_pull_request_state(+ &self,+ macro_user_id: &MacroUserId<Lowercase<'static>>,+ request: SetGithubPullRequestStateRequest,+ ) -> Result<SetGithubPullRequestStateResponse, GithubError> {+ let access_token = self.validated_access_token(macro_user_id).await?;++ let outcome = self+ .oauth+ .set_pull_request_state(+ access_token.as_str(),+ &request.owner,+ &request.repo,+ request.number,+ request.state,+ )+ .await+ .map_err(|error| GithubError::Internal(error.into()))?;++ let state = match outcome {+ GithubStateOutcome::Changed { state } => state,+ GithubStateOutcome::Rejected { rejection, message } => {+ return Err(GithubError::PullRequestUpdateRejected { rejection, message });+ }+ };++ let pull_request = self+ .refresh_changed_pull_request(&access_token, request.to_reference())+ .await;++ Ok(SetGithubPullRequestStateResponse {+ state,+ pull_request,+ })+ }+#[tracing::instrument(skip(self), err)]async fn get_pull_request_mergeability(&self,diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rsindex f8d3289f05..8ab5b37fc0 100644--- a/crates/github/src/domain/service/link_test.rs+++ b/crates/github/src/domain/service/link_test.rs@@ -1,4 +1,5 @@mod lookup;+mod pull_request_state;mod recovery;use std::sync::{Arc, Mutex};@@ -27,8 +28,9 @@ use crate::domain::{GithubLink, GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection,GithubPullRequestDetails, GithubPullRequestMerge, GithubPullRequestMergeability,GithubPullRequestMergeabilityEntry, GithubPullRequestNumber, GithubPullRequestRef,- GithubPullRequestUpdateRejection, GithubRepositoryMergeSettings, GithubUserInfo,- MergeGithubPullRequestRequest, SetGithubPullRequestDraftRequest,+ GithubPullRequestState, GithubPullRequestUpdateRejection, GithubRepositoryMergeSettings,+ GithubStateOutcome, GithubUserInfo, MergeGithubPullRequestRequest,+ SetGithubPullRequestDraftRequest,},ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},};@@ -215,6 +217,8 @@ struct StubGithubOauthState {merge_calls: Vec<MergeCall>,draft_outcome: Option<GithubDraftOutcome>,draft_calls: Vec<(String, u64, bool)>,+ state_outcome: Option<GithubStateOutcome>,+ state_calls: Vec<(String, u64, GithubPullRequestState)>,mergeability_calls: Vec<Vec<GithubPullRequestNumber>>,}@@ -294,6 +298,15 @@ impl StubGithubOauth {self.state.lock().unwrap().draft_calls.clone()}+ fn with_state_outcome(self, outcome: GithubStateOutcome) -> Self {+ self.state.lock().unwrap().state_outcome = Some(outcome);+ self+ }++ fn state_calls(&self) -> Vec<(String, u64, GithubPullRequestState)> {+ self.state.lock().unwrap().state_calls.clone()+ }+fn mergeability_calls(&self) -> Vec<Vec<GithubPullRequestNumber>> {self.state.lock().unwrap().mergeability_calls.clone()}@@ -469,6 +482,24 @@ impl GithubOauth for StubGithubOauth {.ok_or_else(|| anyhow::anyhow!("GitHub unreachable"))}+ async fn set_pull_request_state(+ &self,+ _access_token: &str,+ owner: &str,+ repo: &str,+ number: u64,+ pull_request_state: GithubPullRequestState,+ ) -> Result<GithubStateOutcome, Self::Err> {+ let mut state = self.state.lock().unwrap();+ state+ .state_calls+ .push((format!("{owner}/{repo}"), number, pull_request_state));+ state+ .state_outcome+ .clone()+ .ok_or_else(|| anyhow::anyhow!("GitHub unreachable"))+ }+async fn get_pull_request_mergeability(&self,_access_token: &str,diff --git a/crates/github/src/domain/service/link_test/pull_request_state.rs b/crates/github/src/domain/service/link_test/pull_request_state.rsnew file mode 100644index 0000000000..559ad88411--- /dev/null+++ b/crates/github/src/domain/service/link_test/pull_request_state.rs@@ -0,0 +1,90 @@+use super::*;+use crate::domain::models::SetGithubPullRequestStateRequest;++fn state_request(state: GithubPullRequestState) -> SetGithubPullRequestStateRequest {+ SetGithubPullRequestStateRequest {+ owner: "macro".to_string(),+ repo: "app".to_string(),+ number: 7,+ state,+ }+}++#[tokio::test]+async fn set_pull_request_state_closes_and_refreshes() {+ let user_id = test_user_id();+ let oauth = StubGithubOauth::new(false).with_state_outcome(GithubStateOutcome::Changed {+ state: GithubPullRequestState::Closed,+ });+ let service = service(+ StubGithubRepo::linked(test_link(&user_id)),+ oauth.clone(),+ StubAuth::new("valid-token"),+ );++ let response = service+ .set_pull_request_state(&user_id, state_request(GithubPullRequestState::Closed))+ .await+ .unwrap();++ assert_eq!(response.state, GithubPullRequestState::Closed);+ assert_eq!(+ response+ .pull_request+ .map(|pull_request| pull_request.github_key),+ Some("macro/app/pull/7".to_string())+ );+ assert_eq!(+ oauth.state_calls(),+ vec![("macro/app".to_string(), 7, GithubPullRequestState::Closed)]+ );+ assert_eq!(oauth.pull_request_detail_calls().len(), 1);+}++#[tokio::test]+async fn set_pull_request_state_surfaces_githubs_refusal() {+ let user_id = test_user_id();+ let oauth = StubGithubOauth::new(false).with_state_outcome(GithubStateOutcome::Rejected {+ rejection: GithubPullRequestUpdateRejection::Invalid,+ message: "state cannot be changed. The head branch was deleted.".to_string(),+ });+ let service = service(+ StubGithubRepo::linked(test_link(&user_id)),+ oauth.clone(),+ StubAuth::new("valid-token"),+ );++ let result = service+ .set_pull_request_state(&user_id, state_request(GithubPullRequestState::Open))+ .await;++ match result {+ Err(GithubError::PullRequestUpdateRejected { rejection, message }) => {+ assert_eq!(rejection, GithubPullRequestUpdateRejection::Invalid);+ assert_eq!(+ message,+ "state cannot be changed. The head branch was deleted."+ );+ }+ other => panic!("expected an update rejection, got {other:?}"),+ }+ assert!(oauth.pull_request_detail_calls().is_empty());+}++#[tokio::test]+async fn set_pull_request_state_requires_a_valid_grant() {+ let user_id = test_user_id();+ let oauth = StubGithubOauth::new(true);+ let service = service(+ StubGithubRepo::linked(test_link(&user_id)),+ oauth.clone(),+ StubAuth::new("expired-token"),+ );++ let result = service+ .set_pull_request_state(&user_id, state_request(GithubPullRequestState::Closed))+ .await;++ assert!(matches!(result, Err(GithubError::ReauthenticationRequired)));+ assert!(oauth.state_calls().is_empty());+}diff --git a/crates/github/src/outbound/github_oauth_client.rs b/crates/github/src/outbound/github_oauth_client.rsindex f46ed4a6d5..b95545170e 100644--- a/crates/github/src/outbound/github_oauth_client.rs+++ b/crates/github/src/outbound/github_oauth_client.rs@@ -9,7 +9,8 @@ use crate::domain::{GithubDraftOutcome, GithubExchangeTokenResponse, GithubMergeMethod, GithubMergeOutcome,GithubMergeRejection, GithubPullRequestDetails, GithubPullRequestMerge,GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestNumber,- GithubPullRequestUpdateRejection, GithubRepositoryMergeSettings, GithubUserInfo,+ GithubPullRequestState, GithubPullRequestUpdateRejection, GithubRepositoryMergeSettings,+ GithubStateOutcome, GithubUserInfo,},ports::GithubOauth,};@@ -45,6 +46,25 @@ pub struct GithubOauthImpl {#[derive(serde::Deserialize)]struct GithubErrorBody {message: String,+ /// Validation failures; a 422's top-level message is only+ /// "Validation Failed", and the reason is here.+ #[serde(default)]+ errors: Vec<GithubValidationError>,+}++#[derive(serde::Deserialize)]+struct GithubValidationError {+ message: Option<String>,+}++impl GithubErrorBody {+ /// The most specific reason GitHub gave.+ fn reason(self) -> String {+ self.errors+ .into_iter()+ .find_map(|error| error.message)+ .unwrap_or(self.message)+ }}/// Repository settings as GitHub returns them. The `allow_*` fields are only@@ -567,6 +587,70 @@ impl GithubOauth for GithubOauthImpl {Ok(GithubDraftOutcome::Changed { draft })}+ #[tracing::instrument(skip(self, access_token), err)]+ async fn set_pull_request_state(+ &self,+ access_token: &str,+ owner: &str,+ repo: &str,+ number: u64,+ state: GithubPullRequestState,+ ) -> Result<GithubStateOutcome, Self::Err> {+ /// The request body GitHub takes, and the field of the pull request it+ /// answers with.+ #[derive(serde::Serialize, serde::Deserialize)]+ struct PullRequestState {+ state: GithubPullRequestState,+ }++ let response = self+ .client+ .patch(format!(+ "{}/repos/{owner}/{repo}/pulls/{number}",+ self.api_base_url()+ ))+ .header("Authorization", format!("Bearer {access_token}"))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", USER_AGENT)+ .header("X-GitHub-Api-Version", "2022-11-28")+ .json(&PullRequestState { state })+ .timeout(REQUEST_TIMEOUT)+ .send()+ .await?;++ let status = response.status();+ if status.is_success() {+ let changed: PullRequestState = response.json().await?;+ return Ok(GithubStateOutcome::Changed {+ state: changed.state,+ });+ }++ // The statuses GitHub documents for this endpoint, each a decision+ // about the pull request rather than a failure to reach GitHub.+ let rejection = match status {+ reqwest::StatusCode::FORBIDDEN => GithubPullRequestUpdateRejection::Forbidden,+ reqwest::StatusCode::NOT_FOUND => GithubPullRequestUpdateRejection::NotFound,+ reqwest::StatusCode::UNPROCESSABLE_ENTITY => GithubPullRequestUpdateRejection::Invalid,+ _ => {+ let error_body = response+ .text()+ .await+ .unwrap_or_else(|_| "unknown error".to_string());+ anyhow::bail!(+ "failed to change pull request state (status {status}): {error_body}"+ );+ }+ };+ let message = response+ .json::<GithubErrorBody>()+ .await+ .map(GithubErrorBody::reason)+ .unwrap_or_else(|_| "GitHub declined to change the pull request.".to_string());++ Ok(GithubStateOutcome::Rejected { rejection, message })+ }+#[tracing::instrument(skip(self, access_token, pull_requests), fields(count = pull_requests.len()), err)]async fn get_pull_request_mergeability(&self,diff --git a/crates/github/src/outbound/github_oauth_client/test.rs b/crates/github/src/outbound/github_oauth_client/test.rsindex 5f52a2d060..5e5c4eaae5 100644--- a/crates/github/src/outbound/github_oauth_client/test.rs+++ b/crates/github/src/outbound/github_oauth_client/test.rs@@ -395,6 +395,117 @@ async fn set_pull_request_draft_reports_a_missing_pull_request() {server.finish();}+#[tokio::test]+async fn set_pull_request_state_sends_the_state_and_reports_githubs_answer() {+ let server = MockServer::start(MockResponse {+ status: "200 OK",+ body: serde_json::json!({ "number": 7, "state": "closed", "merged": false }).to_string(),+ });+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());++ let outcome = client+ .set_pull_request_state("token", "macro", "app", 7, GithubPullRequestState::Closed)+ .await+ .unwrap();++ assert_eq!(+ outcome,+ GithubStateOutcome::Changed {+ state: GithubPullRequestState::Closed,+ }+ );+ let request = server.finish();+ assert!(request.starts_with("PATCH /repos/macro/app/pulls/7 HTTP/1.1"));+ assert!(+ request+ .to_ascii_lowercase()+ .contains("authorization: bearer token")+ );+ assert!(request.ends_with(r#"{"state":"closed"}"#));+}++#[tokio::test]+async fn set_pull_request_state_maps_access_and_validation_statuses() {+ for (status, expected) in [+ ("403 Forbidden", GithubPullRequestUpdateRejection::Forbidden),+ ("404 Not Found", GithubPullRequestUpdateRejection::NotFound),+ (+ "422 Unprocessable Entity",+ GithubPullRequestUpdateRejection::Invalid,+ ),+ ] {+ let server = MockServer::start(MockResponse {+ status,+ body: serde_json::json!({ "message": "declined" }).to_string(),+ });+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());++ let outcome = client+ .set_pull_request_state("token", "macro", "app", 7, GithubPullRequestState::Open)+ .await+ .unwrap();++ assert_eq!(+ outcome,+ GithubStateOutcome::Rejected {+ rejection: expected,+ message: "declined".to_string(),+ },+ "status {status}"+ );+ let request = server.finish();+ assert!(request.ends_with(r#"{"state":"open"}"#));+ }+}++#[tokio::test]+async fn set_pull_request_state_reports_the_validation_reason() {+ let server = MockServer::start(MockResponse {+ status: "422 Unprocessable Entity",+ body: serde_json::json!({+ "message": "Validation Failed",+ "errors": [{+ "resource": "PullRequest",+ "code": "custom",+ "message": "state cannot be changed. The head branch was deleted."+ }]+ })+ .to_string(),+ });+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());++ let outcome = client+ .set_pull_request_state("token", "macro", "app", 7, GithubPullRequestState::Open)+ .await+ .unwrap();++ assert_eq!(+ outcome,+ GithubStateOutcome::Rejected {+ rejection: GithubPullRequestUpdateRejection::Invalid,+ message: "state cannot be changed. The head branch was deleted.".to_string(),+ }+ );+ server.finish();+}++#[tokio::test]+async fn set_pull_request_state_treats_unexpected_status_as_error() {+ let server = MockServer::start(MockResponse {+ status: "502 Bad Gateway",+ body: "upstream down".to_string(),+ });+ let client = GithubOauthImpl::with_api_base_url(server.base_url.clone());++ let error = client+ .set_pull_request_state("token", "macro", "app", 7, GithubPullRequestState::Closed)+ .await+ .unwrap_err();++ assert!(error.to_string().contains("502"));+ server.finish();+}+#[tokio::test]async fn get_pull_request_mergeability_batches_and_skips_hidden_pull_requests() {let server = MockServer::start(MockResponse {diff --git a/crates/github_pull_requests/src/domain/models.rs b/crates/github_pull_requests/src/domain/models.rsindex 0c61beb453..4c36246aac 100644--- a/crates/github_pull_requests/src/domain/models.rs+++ b/crates/github_pull_requests/src/domain/models.rs@@ -8,6 +8,7 @@ mod diff;mod index;mod key;mod pull_request;+mod update;use chrono::{DateTime, Utc};use foreign_entity::domain::models::{ForeignEntity, ForeignEntityError, SourceId};@@ -25,16 +26,20 @@ pub use index::{PullRequestIndexOutcome, PullRequestIndexRecord, PullRequestIndepub use key::GithubKey;pub use pull_request::{EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,- EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubDraftOutcome,- GithubMergeMethod, GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun,- GithubPullRequestComment, GithubPullRequestDetails, GithubPullRequestLabel,- GithubPullRequestMerge, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubMergeMethod,+ GithubMergeOutcome, GithubMergeRejection, GithubPullRequestCheckRun, GithubPullRequestComment,+ GithubPullRequestDetails, GithubPullRequestLabel, GithubPullRequestMerge,+ GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse,GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview,GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestStatus,- GithubPullRequestUpdateRejection, GithubPullRequestUser, GithubRepositoryMergeSettings,- MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,- SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, latest_reviews,+ GithubPullRequestUser, GithubRepositoryMergeSettings, MergeGithubPullRequestRequest,+ MergeGithubPullRequestResponse, latest_reviews,+};+pub use update::{+ GithubDraftOutcome, GithubPullRequestState, GithubPullRequestUpdateRejection,+ GithubStateOutcome, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse,};/// A pull request's latest data, for the record stored for one source.diff --git a/crates/github_pull_requests/src/domain/models/pull_request.rs b/crates/github_pull_requests/src/domain/models/pull_request.rsindex b7346df0aa..10a2a3aa48 100644--- a/crates/github_pull_requests/src/domain/models/pull_request.rs+++ b/crates/github_pull_requests/src/domain/models/pull_request.rs@@ -812,75 +812,6 @@ pub struct MergeGithubPullRequestResponse {pub pull_request: Option<EnrichedGithubPullRequest>,}-/// A request to mark one pull request as a draft, or as ready for review, on-/// the user's behalf.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[serde(rename_all = "camelCase")]-pub struct SetGithubPullRequestDraftRequest {- /// The GitHub repository owner or organization.- pub owner: String,- /// The GitHub repository name.- pub repo: String,- /// The GitHub pull request number.- pub number: u64,- /// `true` converts the pull request to a draft; `false` marks it ready for review.- pub draft: bool,-}--impl SetGithubPullRequestDraftRequest {- /// The reference enrichment uses for this pull request.- pub fn to_reference(&self) -> GithubPullRequestRef {- GithubPullRequestNumber {- owner: self.owner.clone(),- repo: self.repo.clone(),- number: self.number,- }- .to_reference()- }-}--/// Response body for a pull request whose draft state changed.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]-#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]-#[serde(rename_all = "camelCase")]-pub struct SetGithubPullRequestDraftResponse {- /// Whether the pull request is now a draft.- pub draft: bool,- /// The pull request as GitHub reports it after the change, when the- /// refresh succeeded.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub pull_request: Option<EnrichedGithubPullRequest>,-}--/// Why GitHub declined to change a pull request.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum GithubPullRequestUpdateRejection {- /// The user's token cannot see the pull request.- NotFound,- /// The user may not change the pull request.- Forbidden,- /// GitHub rejected the change, for example on a closed pull request.- Invalid,-}--/// GitHub's answer to a draft change: performed, or declined with its reason.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum GithubDraftOutcome {- /// The pull request's draft state is now the one asked for.- Changed {- /// Whether the pull request is now a draft.- draft: bool,- },- /// GitHub declined, with the message it gave for the user.- Rejected {- /// Why GitHub declined.- rejection: GithubPullRequestUpdateRejection,- /// GitHub's message, written for the person who asked.- message: String,- },-}-/// One pull request, by repository and number.#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]diff --git a/crates/github_pull_requests/src/domain/models/update.rs b/crates/github_pull_requests/src/domain/models/update.rsnew file mode 100644index 0000000000..24dfdc8bc4--- /dev/null+++ b/crates/github_pull_requests/src/domain/models/update.rs@@ -0,0 +1,146 @@+//! Changes a user asks GitHub to make to a pull request, and GitHub's answer.++use serde::{Deserialize, Serialize};++use super::{EnrichedGithubPullRequest, GithubPullRequestNumber, GithubPullRequestRef};++/// A request to mark one pull request as a draft, or as ready for review, on+/// the user's behalf.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SetGithubPullRequestDraftRequest {+ /// The GitHub repository owner or organization.+ pub owner: String,+ /// The GitHub repository name.+ pub repo: String,+ /// The GitHub pull request number.+ pub number: u64,+ /// `true` converts the pull request to a draft; `false` marks it ready for review.+ pub draft: bool,+}++impl SetGithubPullRequestDraftRequest {+ /// The reference enrichment uses for this pull request.+ pub fn to_reference(&self) -> GithubPullRequestRef {+ GithubPullRequestNumber {+ owner: self.owner.clone(),+ repo: self.repo.clone(),+ number: self.number,+ }+ .to_reference()+ }+}++/// Response body for a pull request whose draft state changed.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SetGithubPullRequestDraftResponse {+ /// Whether the pull request is now a draft.+ pub draft: bool,+ /// The pull request as GitHub reports it after the change, when the+ /// refresh succeeded.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pull_request: Option<EnrichedGithubPullRequest>,+}++/// Why GitHub declined to change a pull request.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GithubPullRequestUpdateRejection {+ /// The user's token cannot see the pull request.+ NotFound,+ /// The user may not change the pull request.+ Forbidden,+ /// GitHub rejected the change, for example drafting a closed pull request+ /// or reopening a merged one.+ Invalid,+}++/// GitHub's answer to a draft change: performed, or declined with its reason.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum GithubDraftOutcome {+ /// The pull request's draft state is now the one asked for.+ Changed {+ /// Whether the pull request is now a draft.+ draft: bool,+ },+ /// GitHub declined, with the message it gave for the user.+ Rejected {+ /// Why GitHub declined.+ rejection: GithubPullRequestUpdateRejection,+ /// GitHub's message, written for the person who asked.+ message: String,+ },+}++/// Whether a pull request is open or closed, as a user sets it. Merging is a+/// separate action, so unlike `GithubPullRequestStatus` there is no merged+/// state.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "lowercase")]+pub enum GithubPullRequestState {+ /// The pull request is open.+ Open,+ /// The pull request is closed.+ Closed,+}++/// A request to close one pull request, or reopen it, on the user's behalf.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SetGithubPullRequestStateRequest {+ /// The GitHub repository owner or organization.+ pub owner: String,+ /// The GitHub repository name.+ pub repo: String,+ /// The GitHub pull request number.+ pub number: u64,+ /// `closed` closes the pull request; `open` reopens it.+ pub state: GithubPullRequestState,+}++impl SetGithubPullRequestStateRequest {+ /// The reference enrichment uses for this pull request.+ pub fn to_reference(&self) -> GithubPullRequestRef {+ GithubPullRequestNumber {+ owner: self.owner.clone(),+ repo: self.repo.clone(),+ number: self.number,+ }+ .to_reference()+ }+}++/// Response body for a pull request that was closed or reopened.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct SetGithubPullRequestStateResponse {+ /// Whether the pull request is now open or closed.+ pub state: GithubPullRequestState,+ /// The pull request as GitHub reports it after the change, when the+ /// refresh succeeded.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub pull_request: Option<EnrichedGithubPullRequest>,+}++/// GitHub's answer to closing or reopening a pull request: performed, or+/// declined with its reason.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum GithubStateOutcome {+ /// The pull request is now open or closed as GitHub reports it.+ Changed {+ /// Whether the pull request is now open or closed.+ state: GithubPullRequestState,+ },+ /// GitHub declined, with the message it gave for the user.+ Rejected {+ /// Why GitHub declined.+ rejection: GithubPullRequestUpdateRejection,+ /// GitHub's message, written for the person who asked.+ message: String,+ },+}diff --git a/crates/projects/AGENTS.md b/crates/projects/AGENTS.mdindex 9186ee0361..7bbbe51b75 100644--- a/crates/projects/AGENTS.md+++ b/crates/projects/AGENTS.md@@ -14,20 +14,24 @@ soft delete/restore/purge, and bulk upload into a project tree.authorization, soft-delete/restore/purge, bulk upload orchestration).- `src/domain/events.rs`: the `ProjectMacroEvent` variants published to theevent broker.+- `src/domain/duplicate.rs`: folder duplication (`ProjectDuplicator`, the+ `DuplicateEntity` impl). It recreates subfolders here and copies documents+ and chats through the `ProjectContentCopier` port, which DSS implements+ over the documents and chat capabilities.- `src/outbound/pg_project_repo.rs`, `src/outbound/dynamo_bulk_upload.rs`,`src/outbound/s3_upload_urls.rs`, `src/outbound/sqs_search_indexer.rs`:the adapters behind those ports.## Scope-- Owns: project CRUD, hierarchy, team-share authorization for projects, and- bulk-upload-into-project orchestration.+- Owns: project CRUD, hierarchy, team-share authorization for projects,+ folder duplication, and bulk-upload-into-project orchestration.- Not here: generic item access/sharing primitives → `entity_access`,`entity_access_management`; property values on a project → `properties`.## Boundaries-- Depends on: `entity_access`, `entity_access_management`,+- Depends on: `entity_access`, `entity_access_management`, `entity_mutation`,`macro_event_broker`, `model_owner`, `models_permissions`.- Used by: `ai_tools` (project tools), `soup_realtime`,`services/deleted_item_poller`, `services/search_processing_service`.@@ -43,6 +47,13 @@ soft delete/restore/purge, and bulk upload into a project tree.- AI project tools omit legacy chat targets and results; agent-session lifecycle and sharing belong to `agent_session`.+## Gotchas++- Folder duplication copies at most `MAX_PROJECT_DUPLICATE_ENTRIES` subfolders,+ documents, and chats, and discards the whole copy if any part fails.+ Email threads are filed by a link on the thread, not owned by the folder,+ so they stay with the source.+## Checks- `cargo test -p projects` (`SQLX_OFFLINE` unset; requires local MacroDB).diff --git a/crates/projects/src/domain.rs b/crates/projects/src/domain.rsindex 389b58587f..f68a674583 100644--- a/crates/projects/src/domain.rs+++ b/crates/projects/src/domain.rs@@ -2,6 +2,9 @@/// Event-to-activity mappings for this domain.pub mod activity;+/// Folder duplication through the unified entity-mutation vocabulary.+#[cfg(feature = "service")]+pub mod duplicate;/// Unified entity-mutation capability impls.#[cfg(feature = "service")]pub mod entity_mutation;diff --git a/crates/projects/src/domain/duplicate.rs b/crates/projects/src/domain/duplicate.rsnew file mode 100644index 0000000000..87eb6d30c5--- /dev/null+++ b/crates/projects/src/domain/duplicate.rs@@ -0,0 +1,308 @@+//! Folder duplication: copy a project's live subtree for the requesting user.+//!+//! The copy is a new project owned by the user, named after the source (or+//! the requested name) and placed beside the source when the user may add to+//! its parent, otherwise at the top level. Subfolders are recreated, and+//! documents and chats are duplicated by their own domains through+//! [`ProjectContentCopier`]. Entries the user cannot view are skipped, with+//! everything inside a skipped folder. Email threads are only linked into a+//! folder, not owned by it, so they are left out. A failure part way discards+//! the whole copy, so no partial copy survives.++#[cfg(test)]+mod test;++use std::collections::HashMap;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};++use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};+use entity_mutation::{DuplicateEntity, EntityMutationEffect, EntityMutationErrorCode};+use futures::stream::{self, StreamExt};+use macro_user_id::user_id::MacroUserIdStr;+use model::project::request::CreateProjectRequest;+use model_entity::{Entity, EntityType};+use model_owner::{CreationPrincipal, Owner};+use shared_entity_registry::{OwnedPurgeOutcome, PurgeOwnedEntity};+use tracing::Instrument;+use uuid::Uuid;++use super::models::{ProjectItemKind, ProjectTreeFolder, ProjectTreeItem};+use super::ports::{ProjectContentCopier, ProjectService};++/// Most subfolders, documents, and chats one duplication copies. The copy+/// runs inside one entity-mutation request, so it gets the budget of the most+/// entities such a request may name.+pub const MAX_PROJECT_DUPLICATE_ENTRIES: usize = 100;++/// Documents and chats one duplication copies at once. Low because the+/// mutation router already runs several requested entities concurrently.+const MAX_CONCURRENT_ITEM_COPIES: usize = 4;++/// Duplicates projects: the project service paired with what it borrows from+/// other domains to copy a folder's documents and chats.+pub struct ProjectDuplicator<P, C> {+ projects: Arc<P>,+ contents: C,+}++impl<P, C> ProjectDuplicator<P, C> {+ /// Pair the project service with the user's content copier.+ pub fn new(projects: Arc<P>, contents: C) -> Self {+ Self { projects, contents }+ }+}++/// Counts of what one duplication copied and skipped.+#[derive(Default)]+struct CopiedEntries {+ folders: usize,+ documents: usize,+ chats: usize,+ skipped: usize,+}++/// What became of one document or chat.+enum ItemOutcome {+ Copied(ProjectItemKind),+ Skipped,+ /// Not started because another copy had already failed.+ NotAttempted,+}++fn invalid_id(error: uuid::Error) -> EntityMutationErrorCode {+ EntityMutationErrorCode::internal(rootcause::report!(error))+}++impl<P, C> ProjectDuplicator<P, C>+where+ P: ProjectService + PurgeOwnedEntity,+ C: ProjectContentCopier,+{+ /// Create one folder of the copy, returning its id.+ async fn create_folder(+ &self,+ principal: &CreationPrincipal,+ name: String,+ parent_id: Option<&str>,+ ) -> Result<String, EntityMutationErrorCode> {+ let project_parent_id = parent_id+ .map(Uuid::parse_str)+ .transpose()+ .map_err(invalid_id)?;+ let project = self+ .projects+ .create_project(+ principal,+ CreateProjectRequest {+ name,+ project_parent_id,+ },+ )+ .await?;+ Ok(project.id)+ }++ /// Recreate the subfolders, parents first, recording each copy's id+ /// under its source's id.+ #[tracing::instrument(+ name = "project.duplicate.copy_folders",+ skip_all,+ fields(project.folder_count = folders.len()),+ err(Debug)+ )]+ async fn copy_folders(+ &self,+ principal: &CreationPrincipal,+ folders: Vec<ProjectTreeFolder>,+ copies: &mut HashMap<String, String>,+ copied: &mut CopiedEntries,+ ) -> Result<(), EntityMutationErrorCode> {+ for folder in folders {+ let Some(parent_id) = copies.get(&folder.parent_id).cloned() else {+ copied.skipped += 1;+ continue;+ };+ let entity = EntityType::Project.with_entity_string(folder.id.clone());+ if self.contents.view_receipt(&entity).await?.is_none() {+ copied.skipped += 1;+ continue;+ }+ let copy_id = self+ .create_folder(principal, folder.name, Some(&parent_id))+ .await?;+ copies.insert(folder.id, copy_id);+ copied.folders += 1;+ }+ Ok(())+ }++ /// Copy one document or chat into the copy of its folder.+ async fn copy_item(+ &self,+ item: ProjectTreeItem,+ copies: &HashMap<String, String>,+ ) -> Result<ItemOutcome, EntityMutationErrorCode> {+ let Some(project_id) = copies.get(&item.project_id) else {+ return Ok(ItemOutcome::Skipped);+ };+ let Some(receipt) = self.contents.view_receipt(&item.entity()).await? else {+ return Ok(ItemOutcome::Skipped);+ };+ self.contents+ .copy_into_project(receipt, item.name, project_id)+ .await?;+ Ok(ItemOutcome::Copied(item.kind))+ }++ /// Copy the documents and chats a few at a time. After a failure no new+ /// copy starts, but every started copy settles before this returns, so+ /// discarding the folder tree afterwards catches all of them.+ #[tracing::instrument(+ name = "project.duplicate.copy_items",+ skip_all,+ fields(project.item_count = items.len()),+ err(Debug)+ )]+ async fn copy_items(+ &self,+ items: Vec<ProjectTreeItem>,+ copies: &HashMap<String, String>,+ copied: &mut CopiedEntries,+ ) -> Result<(), EntityMutationErrorCode> {+ let failed = AtomicBool::new(false);+ let outcomes: Vec<_> = stream::iter(items)+ .map(|item| {+ let failed = &failed;+ async move {+ if failed.load(Ordering::Acquire) {+ return Ok(ItemOutcome::NotAttempted);+ }+ let outcome = self.copy_item(item, copies).await;+ if outcome.is_err() {+ failed.store(true, Ordering::Release);+ }+ outcome+ }+ })+ .buffer_unordered(MAX_CONCURRENT_ITEM_COPIES)+ .collect()+ .await;+ for outcome in outcomes {+ match outcome? {+ ItemOutcome::Copied(ProjectItemKind::Document) => copied.documents += 1,+ ItemOutcome::Copied(ProjectItemKind::Chat) => copied.chats += 1,+ ItemOutcome::Skipped => copied.skipped += 1,+ ItemOutcome::NotAttempted => {}+ }+ }+ Ok(())+ }++ /// Permanently delete a partial copy and everything filed in it.+ #[tracing::instrument(name = "project.duplicate.discard", skip(self, owner))]+ async fn discard(&self, copy_id: &str, owner: MacroUserIdStr<'static>) {+ let copy = match Uuid::parse_str(copy_id) {+ Ok(copy) => copy,+ Err(error) => {+ tracing::error!(error = ?error, "unable to discard partial project copy");+ return;+ }+ };+ match self.projects.purge_owned(copy, &Owner::User(owner)).await {+ Ok(OwnedPurgeOutcome::Purged) => {}+ Ok(OwnedPurgeOutcome::OwnedElsewhere) => {+ tracing::error!("partial project copy has another owner; left in place");+ }+ Err(error) => {+ tracing::error!(error = ?error, "unable to discard partial project copy");+ }+ }+ }+}++impl<P, C> DuplicateEntity for ProjectDuplicator<P, C>+where+ P: ProjectService + PurgeOwnedEntity,+ C: ProjectContentCopier,+{+ type Receipt = ViewAccessLevel;++ #[tracing::instrument(+ name = "project.duplicate",+ skip_all,+ fields(+ project.source_id = %entity.entity_id,+ project.copy_id = tracing::field::Empty,+ project.folders_copied = tracing::field::Empty,+ project.documents_copied = tracing::field::Empty,+ project.chats_copied = tracing::field::Empty,+ project.entries_skipped = tracing::field::Empty,+ ),+ err(Debug)+ )]+ async fn duplicate_entity(+ &self,+ entity: Entity<'static>,+ receipt: EntityAccessReceipt<Self::Receipt>,+ user_id: MacroUserIdStr<'static>,+ display_name: Option<String>,+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {+ let source = self+ .projects+ .internal_get_basic_project(&entity.entity_id)+ .await?;+ if source.deleted_at.is_some() {+ return Err(EntityMutationErrorCode::invalid(rootcause::report!(+ "cannot duplicate a deleted project".to_string()+ )));+ }+ let tree = self+ .projects+ .get_project_tree(receipt, MAX_PROJECT_DUPLICATE_ENTRIES + 1)+ .instrument(tracing::info_span!("project.duplicate.load_tree"))+ .await?;+ if tree.folders.len() + tree.items.len() > MAX_PROJECT_DUPLICATE_ENTRIES {+ return Err(EntityMutationErrorCode::invalid(rootcause::report!(+ format!(+ "projects with more than {MAX_PROJECT_DUPLICATE_ENTRIES} folders, documents, and chats cannot be duplicated"+ )+ )));+ }++ let parent_id = match source.parent_id {+ Some(parent_id) if self.contents.can_add_to_project(&parent_id).await? => {+ Some(parent_id)+ }+ Some(_) | None => None,+ };+ let principal = CreationPrincipal::User(user_id.clone());+ let name = display_name.unwrap_or_else(|| format!("{} copy", source.name));+ let copy_id = self+ .create_folder(&principal, name, parent_id.as_deref())+ .await?;+ let span = tracing::Span::current();+ span.record("project.copy_id", copy_id.as_str());++ let mut copied = CopiedEntries::default();+ let mut copies = HashMap::from([(source.id, copy_id.clone())]);+ let result = async {+ self.copy_folders(&principal, tree.folders, &mut copies, &mut copied)+ .await?;+ self.copy_items(tree.items, &copies, &mut copied).await+ }+ .await;+ span.record("project.folders_copied", copied.folders);+ span.record("project.documents_copied", copied.documents);+ span.record("project.chats_copied", copied.chats);+ span.record("project.entries_skipped", copied.skipped);+ if let Err(error) = result {+ self.discard(©_id, user_id).await;+ return Err(error);+ }++ Ok(vec![EntityMutationEffect::updated(+ EntityType::Project.with_entity_string(copy_id),+ )])+ }+}diff --git a/crates/projects/src/domain/duplicate/test.rs b/crates/projects/src/domain/duplicate/test.rsnew file mode 100644index 0000000000..1905a49c35--- /dev/null+++ b/crates/projects/src/domain/duplicate/test.rs@@ -0,0 +1,549 @@+use std::collections::HashSet;+use std::sync::{Arc, Mutex};++use futures::channel::oneshot;++use entity_access_management::domain::models::EntityAccessManagementError;+use entity_access_management::domain::ports::EntityAccessManagementService;+use entity_registry::{BotFacts, EntityRegistryResult, OwnerGrantPolicy};+use entity_registry_db_utils::OwnedEntityRegistrar;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_event_broker::NoopMacroEventBroker;+use sqlx::PgPool;++use super::*;+use crate::domain::ports::{+ ProjectSearchIndexer, ShaCounterPort, UnavailableBulkUploadRequestPort,+ UnavailableProjectUploadUrlPort,+};+use crate::domain::service::ProjectServiceImpl;+use crate::outbound::PgProjectRepo;++const OWNER: &str = "macro|[email protected]";+const ROOT_ID: &str = "10000000-0000-0000-0000-000000000001";+const FIRST_CHILD_ID: &str = "10000000-0000-0000-0000-000000000002";+const DOCUMENT_ID: &str = "20000000-0000-0000-0000-000000000001";+const CHAT_ID: &str = "30000000-0000-0000-0000-000000000001";++#[derive(Clone)]+struct NoBots;++impl BotFacts for NoBots {+ async fn sponsor(&self, _bot: bot_id::BotId) -> EntityRegistryResult<Option<Owner>> {+ Ok(None)+ }+}++/// Accepts the side effects of creating and purging projects.+#[derive(Clone, Copy)]+struct AcceptAll;++impl ShaCounterPort for AcceptAll {+ async fn decrement_counts(&self, _sha_counts: &[(String, i64)]) -> anyhow::Result<()> {+ Ok(())+ }+}++impl ProjectSearchIndexer for AcceptAll {+ async fn remove_documents(&self, _document_ids: Vec<String>) -> anyhow::Result<()> {+ Ok(())+ }++ async fn enqueue_document_deletes(+ &self,+ _documents: Vec<(String, String)>,+ ) -> anyhow::Result<()> {+ Ok(())+ }+}++impl EntityAccessManagementService for AcceptAll {+ async fn add_entity_to_project(+ &self,+ _entity_id: &Uuid,+ _entity_type: EntityType,+ _project_id: &Uuid,+ ) -> Result<(), EntityAccessManagementError> {+ Ok(())+ }++ async fn remove_entity_from_project(+ &self,+ _entity_id: &Uuid,+ _entity_type: EntityType,+ _old_project_id: &Uuid,+ ) -> Result<(), EntityAccessManagementError> {+ Ok(())+ }++ async fn move_project(+ &self,+ _project_id: &Uuid,+ _old_project_id: Option<&Uuid>,+ _new_project_id: Option<&Uuid>,+ ) -> Result<(), EntityAccessManagementError> {+ Ok(())+ }+}++type TestProjects = ProjectServiceImpl<+ PgProjectRepo<NoBots>,+ UnavailableProjectUploadUrlPort,+ UnavailableBulkUploadRequestPort,+ AcceptAll,+ AcceptAll,+ AcceptAll,+ NoopMacroEventBroker,+>;++fn projects(pool: PgPool) -> Arc<TestProjects> {+ Arc::new(ProjectServiceImpl::new(+ PgProjectRepo::new(+ pool,+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(NoBots)),+ ),+ UnavailableProjectUploadUrlPort,+ UnavailableBulkUploadRequestPort,+ AcceptAll,+ AcceptAll,+ AcceptAll,+ None,+ NoopMacroEventBroker,+ ))+}++/// Copies documents and chats as rows in the target folder, the way their+/// domains leave a filed copy, and records what it copied.+#[derive(Clone)]+struct FakeContents {+ pool: PgPool,+ hidden: HashSet<&'static str>,+ can_add_to_parent: bool,+ /// The source whose copy fails, once another copy has finished.+ failing: Option<&'static str>,+ first_copy_done: Arc<Mutex<Option<oneshot::Sender<()>>>>,+ first_copy_waiter: Arc<Mutex<Option<oneshot::Receiver<()>>>>,+ copied: Arc<Mutex<Vec<(String, String, String)>>>,+}++impl FakeContents {+ fn new(pool: PgPool) -> Self {+ let (done, waiter) = oneshot::channel();+ Self {+ pool,+ hidden: HashSet::new(),+ can_add_to_parent: true,+ failing: None,+ first_copy_done: Arc::new(Mutex::new(Some(done))),+ first_copy_waiter: Arc::new(Mutex::new(Some(waiter))),+ copied: Arc::default(),+ }+ }++ /// `(source id, copy's folder, name)` per copy, sorted.+ fn copied(&self) -> Vec<(String, String, String)> {+ let mut copied = self.copied.lock().unwrap().clone();+ copied.sort();+ copied+ }+}++impl ProjectContentCopier for FakeContents {+ async fn view_receipt(+ &self,+ entity: &Entity<'static>,+ ) -> Result<Option<EntityAccessReceipt<ViewAccessLevel>>, EntityMutationErrorCode> {+ if self.hidden.contains(entity.entity_id.as_ref()) {+ return Ok(None);+ }+ Ok(Some(+ EntityAccessReceipt::dangerously_assert_authenticated_user(+ MacroUserIdStr::try_from(OWNER.to_string()).unwrap(),+ &entity.entity_id,+ entity.entity_type,+ ),+ ))+ }++ async fn can_add_to_project(&self, _project_id: &str) -> Result<bool, EntityMutationErrorCode> {+ Ok(self.can_add_to_parent)+ }++ async fn copy_into_project(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ name: String,+ project_id: &str,+ ) -> Result<Entity<'static>, EntityMutationErrorCode> {+ let source = receipt.entity();+ if self.failing == Some(source.entity_id.as_str()) {+ let waiter = self.first_copy_waiter.lock().unwrap().take();+ if let Some(waiter) = waiter {+ waiter.await.unwrap();+ }+ return Err(EntityMutationErrorCode::internal(rootcause::report!(+ "copy failed".to_string()+ )));+ }+ let copy_id = Uuid::now_v7();+ match source.entity_type {+ EntityType::Document => {+ sqlx::query!(+ r#"INSERT INTO "Document" (id, name, owner, "projectId") VALUES ($1, $2, $3, $4)"#,+ copy_id.to_string(),+ name,+ OWNER,+ project_id,+ )+ .execute(&self.pool)+ .await+ .unwrap();+ }+ _ => {+ sqlx::query!(+ r#"INSERT INTO "Chat" (id, name, "userId", "projectId") VALUES ($1, $2, $3, $4)"#,+ copy_id.to_string(),+ name,+ OWNER,+ project_id,+ )+ .execute(&self.pool)+ .await+ .unwrap();+ }+ }+ sqlx::query!(+ r#"+ INSERT INTO entity (id, entity_type, owner_type, owner_id)+ VALUES ($1, $2, 'user', $3)+ "#,+ copy_id,+ source.entity_type.to_string(),+ OWNER,+ )+ .execute(&self.pool)+ .await+ .unwrap();+ self.copied+ .lock()+ .unwrap()+ .push((source.entity_id.clone(), project_id.to_string(), name));+ let done = self.first_copy_done.lock().unwrap().take();+ if let Some(done) = done {+ let _ = done.send(());+ }+ Ok(source.entity_type.with_entity_string(copy_id.to_string()))+ }+}++async fn duplicate(+ duplicator: &ProjectDuplicator<TestProjects, FakeContents>,+ project_id: &str,+ display_name: Option<&str>,+) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {+ let owner = MacroUserIdStr::try_from(OWNER.to_string()).unwrap();+ duplicator+ .duplicate_entity(+ EntityType::Project.with_entity_string(project_id.to_string()),+ EntityAccessReceipt::dangerously_assert_authenticated_user(+ owner.clone(),+ project_id,+ EntityType::Project,+ ),+ owner,+ display_name.map(str::to_string),+ )+ .await+}++/// The live folders directly inside `parent_id` (or at the top level), as+/// `(id, name, owner)`.+async fn child_folders(pool: &PgPool, parent_id: Option<&str>) -> Vec<(String, String, String)> {+ sqlx::query!(+ r#"+ SELECT id, name, "userId" AS user_id+ FROM "Project"+ WHERE "parentId" IS NOT DISTINCT FROM $1 AND "deletedAt" IS NULL+ ORDER BY name+ "#,+ parent_id,+ )+ .map(|row| (row.id, row.name, row.user_id))+ .fetch_all(pool)+ .await+ .unwrap()+}++fn copy_id(effects: &[EntityMutationEffect]) -> String {+ match effects {+ [EntityMutationEffect::Updated(copy)] if copy.entity_type == EntityType::Project => {+ copy.entity_id.to_string()+ }+ other => panic!("expected one updated project, got {other:?}"),+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn copies_subfolders_documents_and_chats_into_a_new_tree(pool: PgPool) {+ let contents = FakeContents::new(pool.clone());+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ let effects = duplicate(&duplicator, ROOT_ID, None).await.unwrap();++ let copy = copy_id(&effects);+ let top_level = child_folders(&pool, None).await;+ assert!(top_level.contains(&(copy.clone(), "Root copy".to_string(), OWNER.to_string())));+ let first_child = child_folders(&pool, Some(©)).await;+ assert_eq!(first_child.len(), 1);+ assert_eq!(first_child[0].1, "First child");+ assert_eq!(first_child[0].2, OWNER);+ let grandchild = child_folders(&pool, Some(&first_child[0].0)).await;+ assert_eq!(grandchild.len(), 1);+ assert_eq!(grandchild[0].1, "Grandchild");+ assert!(+ child_folders(&pool, Some(&grandchild[0].0))+ .await+ .is_empty()+ );+ assert_eq!(+ contents.copied(),+ vec![+ (+ DOCUMENT_ID.to_string(),+ copy.clone(),+ "Document".to_string()+ ),+ (CHAT_ID.to_string(), copy.clone(), "Chat".to_string()),+ ]+ );+ // The source tree is untouched.+ assert_eq!(child_folders(&pool, Some(ROOT_ID)).await.len(), 1);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn places_the_copy_beside_the_source_only_when_the_user_can_add_there(pool: PgPool) {+ let beside = ProjectDuplicator::new(projects(pool.clone()), FakeContents::new(pool.clone()));+ let effects = duplicate(&beside, FIRST_CHILD_ID, Some("Renamed"))+ .await+ .unwrap();+ let copy = copy_id(&effects);+ let in_root = child_folders(&pool, Some(ROOT_ID)).await;+ assert!(in_root.contains(&(copy.clone(), "Renamed".to_string(), OWNER.to_string())));+ assert_eq!(child_folders(&pool, Some(©)).await[0].1, "Grandchild");++ let mut no_access_to_parent = FakeContents::new(pool.clone());+ no_access_to_parent.can_add_to_parent = false;+ let top_level = ProjectDuplicator::new(projects(pool.clone()), no_access_to_parent);+ let effects = duplicate(&top_level, FIRST_CHILD_ID, None).await.unwrap();+ let copy = copy_id(&effects);+ assert!(child_folders(&pool, None).await.contains(&(+ copy,+ "First child copy".to_string(),+ OWNER.to_string()+ )));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn leaves_email_threads_filed_in_the_source(pool: PgPool) {+ let link_id = Uuid::now_v7();+ let thread_id = Uuid::now_v7();+ sqlx::query!(+ r#"+ INSERT INTO email_links (id, macro_id, fusionauth_user_id, email_address, provider)+ VALUES ($1, $2, 'fusionauth-owner', '[email protected]', 'GMAIL')+ "#,+ link_id,+ OWNER,+ )+ .execute(&pool)+ .await+ .unwrap();+ sqlx::query!(+ r#"INSERT INTO email_threads (id, link_id, project_id) VALUES ($1, $2, $3)"#,+ thread_id,+ link_id,+ ROOT_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ let contents = FakeContents::new(pool.clone());+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ let effects = duplicate(&duplicator, ROOT_ID, None).await.unwrap();++ let copy = copy_id(&effects);+ let thread_folders = sqlx::query_scalar!(+ r#"SELECT project_id FROM email_threads WHERE link_id = $1"#,+ link_id,+ )+ .fetch_all(&pool)+ .await+ .unwrap();+ assert_eq!(thread_folders, vec![Some(ROOT_ID.to_string())]);+ assert!(+ contents+ .copied()+ .iter()+ .all(|(source, folder, _)| *source != thread_id.to_string() && *folder == copy)+ );+ assert_eq!(contents.copied().len(), 2);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn skips_entries_the_user_cannot_view_with_their_contents(pool: PgPool) {+ let mut contents = FakeContents::new(pool.clone());+ contents.hidden = HashSet::from([FIRST_CHILD_ID, DOCUMENT_ID]);+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ let effects = duplicate(&duplicator, ROOT_ID, None).await.unwrap();++ let copy = copy_id(&effects);+ assert!(child_folders(&pool, Some(©)).await.is_empty());+ assert_eq!(+ contents.copied(),+ vec![(CHAT_ID.to_string(), copy, "Chat".to_string())]+ );+ let grandchildren = sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM "Project" WHERE name = 'Grandchild'"#+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(grandchildren, 1);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn refuses_a_tree_over_the_limit_without_creating_anything(pool: PgPool) {+ // Two subfolders, a document, and a chat are already in the tree.+ sqlx::query!(+ r#"+ INSERT INTO "Document" (id, name, owner, "projectId")+ SELECT gen_random_uuid()::text, 'Bulk ' || n, $1, $2+ FROM generate_series(1, 97) AS n+ "#,+ OWNER,+ FIRST_CHILD_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ let projects_before = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM "Project""#)+ .fetch_one(&pool)+ .await+ .unwrap();+ let contents = FakeContents::new(pool.clone());+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ let error = duplicate(&duplicator, ROOT_ID, None).await.unwrap_err();++ assert!(matches!(error, EntityMutationErrorCode::InvalidInput(_)));+ let projects_after = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM "Project""#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(projects_after, projects_before);+ assert!(contents.copied().is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn duplicates_a_tree_at_the_limit(pool: PgPool) {+ sqlx::query!(+ r#"+ INSERT INTO "Document" (id, name, owner, "projectId")+ SELECT gen_random_uuid()::text, 'Bulk ' || n, $1, $2+ FROM generate_series(1, 96) AS n+ "#,+ OWNER,+ FIRST_CHILD_ID,+ )+ .execute(&pool)+ .await+ .unwrap();+ let contents = FakeContents::new(pool.clone());+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ duplicate(&duplicator, ROOT_ID, None).await.unwrap();++ assert_eq!(contents.copied().len(), 98);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn a_failed_copy_discards_everything_already_copied(pool: PgPool) {+ let projects_before = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM "Project""#)+ .fetch_one(&pool)+ .await+ .unwrap();+ let mut contents = FakeContents::new(pool.clone());+ contents.failing = Some(CHAT_ID);+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ let error = duplicate(&duplicator, ROOT_ID, None).await.unwrap_err();++ assert!(matches!(error, EntityMutationErrorCode::Internal(_)));+ // The document copied before the chat failed went with the folder copy.+ let copied = contents.copied();+ assert_eq!(copied.len(), 1);+ assert_eq!(copied[0].0, DOCUMENT_ID);+ let document_copy_rows = sqlx::query_scalar!(+ r#"SELECT COUNT(*) AS "count!" FROM "Document" WHERE name = 'Document'"#+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(document_copy_rows, 1);+ let projects_after = sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM "Project""#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(projects_after, projects_before);+ let copy_entities = sqlx::query_scalar!(+ r#"+ SELECT COUNT(*) AS "count!"+ FROM entity+ WHERE owner_id = $1 AND created_at > NOW() - INTERVAL '1 hour'+ "#,+ OWNER,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(copy_entities, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn refuses_a_deleted_project(pool: PgPool) {+ let contents = FakeContents::new(pool.clone());+ let duplicator = ProjectDuplicator::new(projects(pool.clone()), contents.clone());++ let error = duplicate(&duplicator, "10000000-0000-0000-0000-000000000009", None)+ .await+ .unwrap_err();++ assert!(matches!(error, EntityMutationErrorCode::InvalidInput(_)));+ assert!(contents.copied().is_empty());+}diff --git a/crates/projects/src/domain/models.rs b/crates/projects/src/domain/models.rsindex 15031243a6..c8bca18588 100644--- a/crates/projects/src/domain/models.rs+++ b/crates/projects/src/domain/models.rs@@ -3,6 +3,7 @@use macro_user_id::user_id::MacroUserIdStr;use model::folder::FileSystemNode;use model::project::Project;+use model_entity::{Entity, EntityType};use model_owner::Owner;use models_permissions::share_permission::team_share::AuthorizedTeamShareCommand;use models_permissions::share_permission::{SharePermissionV2, UpdateSharePermissionRequestV2};@@ -108,6 +109,59 @@ pub struct UploadFolderRepoArgs {pub parent_id: Option<String>,}+/// A live folder below the root of a [`ProjectTree`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectTreeFolder {+ /// Folder identifier.+ pub id: String,+ /// Containing folder: the tree's root or another of its folders.+ pub parent_id: String,+ /// Folder name.+ pub name: String,+}++/// The kinds of item a project tree holds besides folders.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ProjectItemKind {+ /// A document, tasks included.+ Document,+ /// A chat.+ Chat,+}++/// A live document or chat filed in a [`ProjectTree`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectTreeItem {+ /// Whether the item is a document or a chat.+ pub kind: ProjectItemKind,+ /// Item identifier.+ pub id: String,+ /// Containing folder: the tree's root or one of its folders.+ pub project_id: String,+ /// Display name.+ pub name: String,+}++impl ProjectTreeItem {+ /// The item as an entity reference.+ pub fn entity(&self) -> Entity<'static> {+ let entity_type = match self.kind {+ ProjectItemKind::Document => EntityType::Document,+ ProjectItemKind::Chat => EntityType::Chat,+ };+ entity_type.with_entity_string(self.id.clone())+ }+}++/// The live folders, documents, and chats below a project.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ProjectTree {+ /// Folders below the root, every parent before its children.+ pub folders: Vec<ProjectTreeFolder>,+ /// Documents and chats filed in the root or one of its folders.+ pub items: Vec<ProjectTreeItem>,+}+/// Result returned by project creation and editing.pub type MutatedProject = Project;diff --git a/crates/projects/src/domain/ports.rs b/crates/projects/src/domain/ports.rsindex d60c566188..dcc8796dd8 100644--- a/crates/projects/src/domain/ports.rs+++ b/crates/projects/src/domain/ports.rs@@ -8,6 +8,7 @@ use std::future::Future;use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,};+use entity_mutation::EntityMutationErrorCode;use macro_user_id::user_id::MacroUserIdStr;use model::document::ContentType;use model::folder::{UploadFolderRequest, UploadFolderResponseData, UploadFolderWithIdsResponse};@@ -18,6 +19,7 @@ use model::project::{BasicProject, PendingProject, Project, ProjectPreview, ProjectPreviewV2,ProjectWithUploadRequest,};+use model_entity::Entity;use model_owner::{CreationPrincipal, Owner};use models_bulk_upload::{BulkUploadRequest, BulkUploadRequestDocuments, UploadExtractFolderRequest,@@ -31,7 +33,7 @@ use uuid::Uuid;use super::models::{CreateProjectArgs, EditProjectArgs, MarkedUploadedTree, MutatedProject, ProjectError,- PurgedProjectTree, RevertDeleteResult, SoftDeleteResult, UploadFolderRepoArgs,+ ProjectTree, PurgedProjectTree, RevertDeleteResult, SoftDeleteResult, UploadFolderRepoArgs,};/// Repository for reading project data from persistent storage.@@ -82,6 +84,16 @@ pub trait ProjectRepo: Send + Sync + 'static {project_id: &str,) -> impl Future<Output = Result<Vec<Item>, Self::Err>> + Send;+ /// Get the live folders below a project and the live documents and chats+ /// filed in it or them. Returns at most `limit` folders and at most+ /// `limit` items, so a caller detects an oversized tree by asking for+ /// one more than it accepts.+ fn get_project_tree(+ &self,+ project_id: &str,+ limit: usize,+ ) -> impl Future<Output = Result<ProjectTree, Self::Err>> + Send;+/// Get the project's share permission configuration.fn get_project_share_permission(&self,@@ -248,6 +260,40 @@ pub trait ProjectSearchIndexer: Send + Sync + 'static {) -> impl Future<Output = anyhow::Result<()>> + Send;}+/// What a folder duplication needs from other domains, acting as the user who+/// duplicates the folder.+///+/// The composition root implements it over `entity_access` and the owning+/// domains' duplicate and move capabilities, so the projects domain never+/// depends on the documents or chat crates.+pub trait ProjectContentCopier: Send + Sync {+ /// The user's view receipt for `entity`, or `None` when they cannot view+ /// it or it no longer exists.+ fn view_receipt(+ &self,+ entity: &Entity<'static>,+ ) -> impl Future<+ Output = Result<Option<EntityAccessReceipt<ViewAccessLevel>>, EntityMutationErrorCode>,+ > + Send;++ /// Whether the user may add items to the project.+ fn can_add_to_project(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<bool, EntityMutationErrorCode>> + Send;++ /// Duplicate the document or chat `receipt` covers, as the user, and file+ /// the copy in `project_id`, returning the copy. `name` is the source's+ /// name, kept on the copy where its domain allows a chosen name. On+ /// failure nothing this call created remains.+ fn copy_into_project(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ name: String,+ project_id: &str,+ ) -> impl Future<Output = Result<Entity<'static>, EntityMutationErrorCode>> + Send;+}+/// Unwired upload-URL port for hosts that expose project operations without/// upload flows (e.g. AI tools). Upload methods fail loudly if reached.#[derive(Clone, Copy, Debug, Default)]@@ -376,6 +422,15 @@ pub trait ProjectService: Send + Sync + 'static {receipt: EntityAccessReceipt<ViewAccessLevel>,) -> impl Future<Output = Result<Vec<ItemWithUserAccessLevel>, ProjectError>> + Send;+ /// Get the live folders, documents, and chats below a project, at most+ /// `limit` folders and `limit` items (see [`ProjectRepo::get_project_tree`]).+ /// The receipt covers the project; callers check each entry themselves.+ fn get_project_tree(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ limit: usize,+ ) -> impl Future<Output = Result<ProjectTree, ProjectError>> + Send;+/// Get project share permissions for an owner.fn get_project_permissions(&self,diff --git a/crates/projects/src/domain/service.rs b/crates/projects/src/domain/service.rsindex 7401ad18f0..0837671fec 100644--- a/crates/projects/src/domain/service.rs+++ b/crates/projects/src/domain/service.rs@@ -36,8 +36,8 @@ use super::events::{ProjectUploadedMetadata,};use super::models::{- CreateProjectArgs, EditProjectArgs, ProjectError, PurgedProjectTree, RevertDeleteResult,- SoftDeleteResult, UploadFolderRepoArgs,+ CreateProjectArgs, EditProjectArgs, ProjectError, ProjectTree, PurgedProjectTree,+ RevertDeleteResult, SoftDeleteResult, UploadFolderRepoArgs,};use super::ports::{BulkUploadRequestPort, ProjectRepo, ProjectSearchIndexer, ProjectService, ProjectUploadUrlPort,@@ -337,6 +337,17 @@ where.collect())}+ async fn get_project_tree(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ limit: usize,+ ) -> Result<ProjectTree, ProjectError> {+ self.repo+ .get_project_tree(&receipt.entity().entity_id, limit)+ .await+ .map_err(|error| internal_error(error, "unable to get project tree"))+ }+async fn get_project_permissions(&self,receipt: EntityAccessReceipt<OwnerAccessLevel>,diff --git a/crates/projects/src/inbound/axum_router/tests.rs b/crates/projects/src/inbound/axum_router/tests.rsindex fee5d05f8e..45ac863679 100644--- a/crates/projects/src/inbound/axum_router/tests.rs+++ b/crates/projects/src/inbound/axum_router/tests.rs@@ -135,6 +135,14 @@ impl ProjectService for FakeProjectService {Ok(Vec::new())}+ async fn get_project_tree(+ &self,+ _receipt: EntityAccessReceipt<entity_access::domain::models::ViewAccessLevel>,+ _limit: usize,+ ) -> Result<crate::domain::models::ProjectTree, ProjectError> {+ unreachable!("no HTTP route loads a project tree")+ }+async fn get_project_permissions(&self,_receipt: EntityAccessReceipt<entity_access::domain::models::OwnerAccessLevel>,diff --git a/crates/projects/src/outbound/pg_project_repo.rs b/crates/projects/src/outbound/pg_project_repo.rsindex 9c89be461f..7482a710c3 100644--- a/crates/projects/src/outbound/pg_project_repo.rs+++ b/crates/projects/src/outbound/pg_project_repo.rs@@ -7,6 +7,7 @@ mod edit;mod revert_delete;mod share;mod team_share;+mod tree;mod upload_folder;#[cfg(test)]@@ -25,8 +26,8 @@ use models_permissions::share_permission::{LinkShare, TeamLinkShareDefault};use sqlx::{PgPool, Postgres, Transaction};use crate::domain::models::{- CreateProjectArgs, EditProjectArgs, MarkedUploadedTree, ProjectError, PurgedProjectTree,- RevertDeleteResult, SoftDeleteResult, UploadFolderRepoArgs,+ CreateProjectArgs, EditProjectArgs, MarkedUploadedTree, ProjectError, ProjectTree,+ PurgedProjectTree, RevertDeleteResult, SoftDeleteResult, UploadFolderRepoArgs,};use crate::domain::ports::ProjectRepo;@@ -309,6 +310,15 @@ impl<B: BotFacts + 'static> ProjectRepo for PgProjectRepo<B> {content::get_project_children(&self.pool, project_id).await}+ #[tracing::instrument(err, skip(self))]+ async fn get_project_tree(+ &self,+ project_id: &str,+ limit: usize,+ ) -> Result<ProjectTree, Self::Err> {+ tree::get_project_tree(&self.pool, project_id, limit).await+ }+#[tracing::instrument(err, skip(self))]async fn get_project_share_permission(&self,diff --git a/crates/projects/src/outbound/pg_project_repo/tests.rs b/crates/projects/src/outbound/pg_project_repo/tests.rsindex 1c450d83ca..4479d8c6c8 100644--- a/crates/projects/src/outbound/pg_project_repo/tests.rs+++ b/crates/projects/src/outbound/pg_project_repo/tests.rs@@ -15,7 +15,10 @@ use models_permissions::share_permission::{use sqlx::{PgPool, Pool, Postgres, Row};use super::PgProjectRepo;-use crate::domain::models::{CreateProjectArgs, EditProjectArgs, UploadFolderRepoArgs};+use crate::domain::models::{+ CreateProjectArgs, EditProjectArgs, ProjectItemKind, ProjectTree, ProjectTreeFolder,+ ProjectTreeItem, UploadFolderRepoArgs,+};use crate::domain::ports::ProjectRepo;#[derive(Clone)]@@ -1116,3 +1119,58 @@ async fn mark_uploaded_is_recursive_and_rejects_missing_root(assert!(matches!(missing_error, sqlx::Error::RowNotFound));Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("projects_test_data"))+)]+async fn project_tree_lists_live_descendants_parents_first(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = test_repo(pool);++ let tree = repo.get_project_tree(ROOT_ID, 10).await?;++ assert_eq!(+ tree.folders,+ vec![+ ProjectTreeFolder {+ id: CHILD_ID.to_string(),+ parent_id: ROOT_ID.to_string(),+ name: "First child".to_string(),+ },+ ProjectTreeFolder {+ id: "10000000-0000-0000-0000-000000000003".to_string(),+ parent_id: CHILD_ID.to_string(),+ name: "Grandchild".to_string(),+ },+ ]+ );+ assert_eq!(+ tree.items,+ vec![+ ProjectTreeItem {+ kind: ProjectItemKind::Document,+ id: DOCUMENT_ID.to_string(),+ project_id: ROOT_ID.to_string(),+ name: "Document".to_string(),+ },+ ProjectTreeItem {+ kind: ProjectItemKind::Chat,+ id: CHAT_ID.to_string(),+ project_id: ROOT_ID.to_string(),+ name: "Chat".to_string(),+ },+ ]+ );++ let capped = repo.get_project_tree(ROOT_ID, 1).await?;+ assert_eq!(capped.folders.len(), 1);+ assert_eq!(capped.items.len(), 2);++ let leaf = repo+ .get_project_tree("10000000-0000-0000-0000-000000000003", 10)+ .await?;+ assert_eq!(leaf, ProjectTree::default());+ Ok(())+}diff --git a/crates/projects/src/outbound/pg_project_repo/tree.rs b/crates/projects/src/outbound/pg_project_repo/tree.rsnew file mode 100644index 0000000000..4fd3619045--- /dev/null+++ b/crates/projects/src/outbound/pg_project_repo/tree.rs@@ -0,0 +1,98 @@+use sqlx::PgPool;++use crate::domain::models::{ProjectItemKind, ProjectTree, ProjectTreeFolder, ProjectTreeItem};++pub(super) async fn get_project_tree(+ pool: &PgPool,+ project_id: &str,+ limit: usize,+) -> Result<ProjectTree, sqlx::Error> {+ let limit = i64::try_from(limit).unwrap_or(i64::MAX);++ // No ORDER BY: Postgres stops expanding the recursive query once `limit`+ // rows are fetched, so an oversized tree is never walked in full.+ let mut folders = sqlx::query!(+ r#"+ WITH RECURSIVE folders AS (+ SELECT child.id, child."parentId" AS parent_id, child.name, 1 AS depth+ FROM "Project" child+ WHERE child."parentId" = $1 AND child."deletedAt" IS NULL+ UNION ALL+ SELECT child.id, child."parentId", child.name, folders.depth + 1+ FROM "Project" child+ JOIN folders ON child."parentId" = folders.id+ WHERE child."deletedAt" IS NULL+ )+ SELECT+ id AS "id!",+ parent_id AS "parent_id!",+ name AS "name!",+ depth AS "depth!"+ FROM folders+ LIMIT $2+ "#,+ project_id,+ limit,+ )+ .fetch_all(pool)+ .await?;+ folders.sort_by_key(|folder| folder.depth);+ let folder_ids = folders+ .iter()+ .map(|folder| folder.id.clone())+ .chain([project_id.to_string()])+ .collect::<Vec<_>>();++ let documents = sqlx::query!(+ r#"+ SELECT id, name, "projectId" AS "project_id!"+ FROM "Document"+ WHERE "projectId" = ANY($1) AND "deletedAt" IS NULL+ LIMIT $2+ "#,+ &folder_ids,+ limit,+ )+ .fetch_all(pool)+ .await?;+ let chats = sqlx::query!(+ r#"+ SELECT id, name, "projectId" AS "project_id!"+ FROM "Chat"+ WHERE "projectId" = ANY($1) AND "deletedAt" IS NULL+ LIMIT $2+ "#,+ &folder_ids,+ limit,+ )+ .fetch_all(pool)+ .await?;++ let items = documents+ .into_iter()+ .map(|row| ProjectTreeItem {+ kind: ProjectItemKind::Document,+ id: row.id,+ project_id: row.project_id,+ name: row.name,+ })+ .chain(chats.into_iter().map(|row| ProjectTreeItem {+ kind: ProjectItemKind::Chat,+ id: row.id,+ project_id: row.project_id,+ name: row.name,+ }))+ .collect();++ Ok(ProjectTree {+ folders: folders+ .into_iter()+ .map(|folder| ProjectTreeFolder {+ id: folder.id,+ parent_id: folder.parent_id,+ name: folder.name,+ })+ .collect(),+ items,+ })+}diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.mdindex fddf40899f..64894eec19 100644--- a/docs/agent-guide/calls.md+++ b/docs/agent-guide/calls.md@@ -105,6 +105,11 @@ If a recording fails to play, reload the page to obtain a fresh recording link,or use **Open or download recording**. The playback warning does not assumethat the failure is caused by an unsupported media format.+Where a call shows the block header's "…" menu (Rename, Delete), that menu+also offers **Download** when the call has a recording. It saves the recording+under the call's name with the recording's extension (`<name>.mp4`), through the+same download flow and confirmations as Drive files.+### Call links and guests — `/app/meet/join/:shareToken`These routes require `enable-quick-calls` for both signed-in users and guests.diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 7295e9d7f3..553abd1aa0 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -730,7 +730,8 @@ import note, and **Download as Excel** writes a macro-free `.xlsx`; an uploadedis rejected here with a hint to upload it instead; uploads convert it (see[Legacy Office uploads](#legacy-office-uploads)).-**Import and export → Download as Excel (.xlsx)** exports every sheet with formulas,+**Import and export → Download as Excel (.xlsx)** (also the header's "…" file+menu **Download** submenu, beside **Download as CSV**) exports every sheet with formulas,current formula result caches, precise numeric values, custom Excel number formats, fonts, borders, and column widths. Named ranges, named constants, and names defined by formulas are retained and calculate. Imported legacy formulas keep Excel's implicit intersection, shown with `@` as current Excel shows it; 3-D references such as `SUM('Jan:Dec'!B2)` are listed sheet by sheet. Imported merged ranges, hidden sheets/rows/columns, row heights, filters, and frozen panes are retained for export. Macro hides imported rows and columns, shows hidden sheets and individual cells of merged ranges; editing a covered merged cell omits that merge during export with a warning so the edit is preserved. Imported charts, images, shapes, text boxes, pivot tables, conditional formatting, validation and notes are written back. Structured table formulas and rich text are not fully supported; review import notes before conversion.CSV imports preserve long identifiers and leading zeros as text and never execute formula-like strings.**Download as CSV** in the same menu exports only the active sheet's current@@ -2874,7 +2875,9 @@ updates live and shows each collaborator's caret with their namemenu (`[data-docx-menu="notes"]`, in the body), `Track changes`, `Hide trackedchanges` / `Show tracked changes`, `Comment on selection`, `Find andreplace` and `Download .docx` (viewers get `Find and replace` and- `Download .docx`).+ `Download .docx`). The header's "…" file menu also has **Download**, which+ saves the same live `.docx`, or the server's export before the editor has+ loaded.While tracking is on (or the caret is on a tracked change) it also shows`Accept change`, `Reject change`, `Accept all changes` and `Reject allchanges`.diff --git a/docs/agent-guide/files.md b/docs/agent-guide/files.mdindex ce4268a60c..b3e5cd2e50 100644--- a/docs/agent-guide/files.md+++ b/docs/agent-guide/files.md@@ -127,8 +127,14 @@ search remains available. Right-click any Drive view, the Drive folder overview,or a folder at any depth for **Open in new split**, **Open in current split**, and**Open fullscreen** (when multiple splits are open). Opening a location in a newsplit clears search and filters in the destination, leaving the original split-unchanged. Folder menus also offer Favorite/Unfavorite, Move to folder, Copy Link,-and owner-only Rename and Delete.+unchanged. Folder menus also offer Favorite/Unfavorite, Snooze notifications…,+Mute/Unmute notifications, Duplicate, Copy Link, Copy ID, Share, and+owner-only Rename, Move to folder, and Delete, matching the folder's row menu in the Drive list.+**Duplicate** on a folder (also in its "…" menu and row menu) makes "<name> copy"+beside it (or at the top level without edit access to its parent), copying its+subfolders, documents, tasks, and chats; email threads filed in it stay with the+original. Folders with more than 100 subfolders, documents, and chats can't be+duplicated, and a failed copy leaves nothing behind.A folder's Share dialog, when the owner belongs to a team, has Team access(None, View, Comment, or Edit) without a Link sharing card or Link tab.Favorites use the same open actions and **Remove from favorites** menu as Tasks.diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex df63b8754f..fbfaa86df9 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -790,8 +790,9 @@ uploading or moving anything.## FavoritesUse an entity's command/context menu to add or remove it from Favorites. Documents, chats,-agent sessions, projects, email threads, channels, calls, CRM companies, and CRM-contacts support toggling. Individual channel messages are not favoritable. A+agent sessions, projects, email threads, channels, calls, CRM companies, CRM contacts,+databases, and forms support toggling; database and form favorites appear in Drive's+sidebar. Individual channel messages and pull requests are not favoritable. Afavorited agent session disappears from the list once the session is deleted.With the GraphQL local cache enabled, cached favorites remain visible when offline@@ -1358,6 +1359,36 @@ by another pane, it focuses that owner without advancing the requesting pane'shistory cursor. Restoring a saved layout preserves existing duplicate panes;search-only updates within those panes do not collapse them.+## Entity menus++List rows (Search, Home, Email, Drive, Tasks, Recent, folders, Agents, Calls)+share one right-click menu, and the mobile long-press drawer shows the same+items. It offers an item only where its action works for the row's type:+Rename for documents, chats, folders, calls, agent sessions, and channels you+take part in (not DMs); Duplicate for+documents, chats, and folders (with GraphQL Soup); Move to folder for documents, chats, folders, and email you own (a folder is+one location shared by everyone, and its sharing passes to what it holds, so+only the owner moves an item; the server enforces the same);+Delete for email and owned documents, chats, folders, calls, agent sessions, and+routines. **Download** saves uploaded files (images, video, code, PowerPoint,+Photoshop, Illustrator, Figma, other uploads) and Word documents as `.docx`;+Markdown documents, canvases, native spreadsheets, and PDFs download from their+open view instead, since their download needs the loaded editor (a PDF's+includes its markup). Tasks add **Set status**, **Set priority**, and **Set assignee**,+which open the property editor like their shortcuts. Agent sessions add+**Archive** / **Unarchive** for their owner. Calls offer **Share**. Pull+requests offer **Open in new split**, **Copy GitHub Link**, **Open on GitHub**,+and **Copy Branch Name** when the head branch is stored. Rows inside a Drive+folder offer **Remove from folder**, as in a folder's own view. Channel message+rows have no **Copy ID**. Email rows and the email "…" menu offer **Sender →+Signal** for a sender in Noise and **Sender → Noise** for one in Signal, read+from the email itself (falling back to the view's tab); when neither says, as+for some Search rows or an email opened directly, both are offered, with+**Block Sender**. **Mark Done** (and `e`) works in Home, the triaged+Email tabs, and Search, where a marked row stays listed as done. On Home,+right-click **Mark Done** moves the preview to the next item, like the `e` key. A detail view's "…" menu also offers+**Snooze notifications…** beside Mute.+## Entity action dialogsRename, Delete, and Move to folder use compact centered dialogs on desktop anddiff --git a/docs/agent-guide/pull-requests.md b/docs/agent-guide/pull-requests.mdindex 50d2f68602..948b1d8da7 100644--- a/docs/agent-guide/pull-requests.md+++ b/docs/agent-guide/pull-requests.md@@ -8,15 +8,27 @@ scope; desktop's default scope remains **Involves me**.Macro-linked GitHub pull requests open inside the Reviews shell, with a Reviewsbreadcrumb, PR title/status, linked GitHub metadata, discussion timeline, and Details/Checks-side panel below the top bar. An open PR that is not a draft, and whose checks-have all finished with a success, skipped, or neutral conclusion, also shows a-**Merge** button in the top bar beside **Changes**. It opens a confirmation with the repository, PR number,-and title, then merges on GitHub as the signed-in user through their linked account.-GitHub's permissions and branch protections decide; a refusal appears as a toast-with GitHub's reason, and a merge refreshes the PR status in place. Without a linked-GitHub account the toast points to Settings. Draft PRs, PRs with no checks, and PRs-whose checks are still running or failing have no Merge button. Merged and closed-PRs have no Merge button. PRs are not tasks and do not appear in the Tasks list.+side panel below the top bar. An open PR has a split button in the top bar+beside **Changes** (`[data-pull-request-primary-action]` names its main action).+For a draft the main action is **Ready for review**; otherwise it is **Merge**,+disabled (with a tooltip) until every check has finished with a success, skipped,+or neutral conclusion, so PRs with no checks or with running or failing checks+cannot merge from it. The chevron beside it (**More pull request actions**) offers+**Convert to draft** (non-drafts) and **Close pull request**; there is no+confirmation for either. **Merge** opens a confirmation with the repository, PR+number, and title, then merges on GitHub as the signed-in user through their+linked account. GitHub's permissions and branch protections decide every change;+a refusal appears as a toast with GitHub's reason, and a change refreshes the PR+status in place. Without a linked GitHub account the toast points to Settings.+Merged and closed PRs have no split button. PRs are not tasks and do not appear+in the Tasks list. PRs cannot be favorited.+The **Share** button has a **Copy Share Link** button beside it, like other+items. The "…" menu beside the PR title (in the Reviews breadcrumb, the standalone+`/app/pr/<id>` page, and PR previews) holds the same changes as the split button,+with **Merge** only once its checks pass, plus **Reopen pull request** for a+closed unmerged PR; then **Copy Link** (the Macro link), **Copy ID**, **Copy+GitHub link**, **Open on GitHub**, and **Copy branch name** when the head branch+is stored.The metadata pills beneath the PR title include linked agent sessions, using theagent sparkle icon. A single session shows its name; several sessions show acount chip opening a session list. Selecting a session opens it, with Shift-clickdiff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.mdindex caa4bc9715..6ee4c11fb4 100644--- a/docs/agent-guide/tasks.md+++ b/docs/agent-guide/tasks.md@@ -311,7 +311,10 @@ outside project boards; project boards always retain the current project.Each pane or project scope and column keeps a separate composer draft. Projectboards hide creation actions when the project is read-only.-Click a card's body or title to open the task. Move at least 10 pixels with the+Click a card's body or title to open the task. Right-click a card, or press+Shift+F10 on its focused title, for the List row's task menu; it acts on that+card alone, since the board has no selection. Right presses never start or+redirect a drag. Move at least 10 pixels with the primarymouse button held to start dragging to another column; holding still does notstart a drag. Property pills remain interactive and do not start a drag.A new destination column highlights once movement slows@@ -508,7 +511,8 @@ none), **Checks failing**, **Conflicts** (GitHub reports the branch conflictingwith its base; read live for the open PRs on the board), **Ready to merge**(every check passed), and **Merged**. Cards show the status icon, priority,title, checks, `owner/repo#N`, author, link pills, labels, and agent sessions;-clicking a card opens the PR. Dragging asks GitHub for the change as you: drop+clicking a card opens the PR. Right-clicking a card, or Shift+F10 on its focused+title, opens the list row's context menu. Dragging asks GitHub for the change as you: dropon **Merged** (from In review or Ready to merge) to merge after the sameconfirmation as the PR's Merge button; drop on **Draft** to convert any open PRto a draft; drop a draft on **In review** to mark it ready for review. Checks@@ -516,12 +520,12 @@ failing, Conflicts, and Ready to merge take no drops, and merged cards cannot bedragged. A refusal shows GitHub's message and the card returns. **Load more pullrequests** fetches the next page.-PR rows can be added to or removed from Favorites through their context menu or-bulk entity actions. When at least one accessible PR is favorited, Reviews shows-a collapsible Favorites section below the views; the section is hidden otherwise.+Pull requests can no longer be favorited. PRs favorited earlier still appear in+a collapsible Favorites section below the views (hidden when there are none).Favorite rows open the PR in Reviews (Shift-click opens another split), and theircontext menu can remove the favorite. PR favorites also open in Reviews from the-global Favorites sidebar or command menu.+global Favorites sidebar or command menu. A PR row's context menu offers **Open+in new split**, **Copy Link**, and **Open on GitHub**.Select a PR to open `/app/reviews/pr/<foreignEntityId>` in the Reviews shell.Opening a PR refreshes it from GitHub in the background for viewers with adiff --git a/packages/sdk-docs/reference/generated/auth/types.gen/README.md b/packages/sdk-docs/reference/generated/auth/types.gen/README.mdindex c0f5719b54..4c7f3ee5f5 100644--- a/packages/sdk-docs/reference/generated/auth/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/auth/types.gen/README.md@@ -308,6 +308,7 @@- [GithubPullRequestRef](type-aliases/GithubPullRequestRef.md)- [GithubPullRequestReview](type-aliases/GithubPullRequestReview.md)- [GithubPullRequestReviewState](type-aliases/GithubPullRequestReviewState.md)+- [GithubPullRequestState](type-aliases/GithubPullRequestState.md)- [GithubPullRequestStatus](type-aliases/GithubPullRequestStatus.md)- [GithubPullRequestUser](type-aliases/GithubPullRequestUser.md)- [GmailLinkStatusResponse](type-aliases/GmailLinkStatusResponse.md)@@ -565,6 +566,13 @@- [SetGithubPullRequestDraftResponse](type-aliases/SetGithubPullRequestDraftResponse.md)- [SetGithubPullRequestDraftResponse2](type-aliases/SetGithubPullRequestDraftResponse2.md)- [SetGithubPullRequestDraftResponses](type-aliases/SetGithubPullRequestDraftResponses.md)+- [SetGithubPullRequestStateData](type-aliases/SetGithubPullRequestStateData.md)+- [SetGithubPullRequestStateError](type-aliases/SetGithubPullRequestStateError.md)+- [SetGithubPullRequestStateErrors](type-aliases/SetGithubPullRequestStateErrors.md)+- [SetGithubPullRequestStateRequest](type-aliases/SetGithubPullRequestStateRequest.md)+- [SetGithubPullRequestStateResponse](type-aliases/SetGithubPullRequestStateResponse.md)+- [SetGithubPullRequestStateResponse2](type-aliases/SetGithubPullRequestStateResponse2.md)+- [SetGithubPullRequestStateResponses](type-aliases/SetGithubPullRequestStateResponses.md)- [SsoLoginData](type-aliases/SsoLoginData.md)- [SsoLoginError](type-aliases/SsoLoginError.md)- [SsoLoginErrors](type-aliases/SsoLoginErrors.md)diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GithubPullRequestState.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GithubPullRequestState.mdnew file mode 100644index 0000000000..88607af5d8--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/GithubPullRequestState.md@@ -0,0 +1,7 @@+# Type Alias: GithubPullRequestState++> **GithubPullRequestState** = `"open"` \| `"closed"`++Whether a pull request is open or closed, as a user sets it. Merging is a+separate action, so unlike `GithubPullRequestStatus` there is no merged+state.diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateData.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateData.mdnew file mode 100644index 0000000000..e535ca73bc--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateData.md@@ -0,0 +1,12 @@+# Type Alias: SetGithubPullRequestStateData++> **SetGithubPullRequestStateData** = \{ `body`: [`SetGithubPullRequestStateRequest`](SetGithubPullRequestStateRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/github_pull_requests/state"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`SetGithubPullRequestStateRequest`](SetGithubPullRequestStateRequest.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/github_pull_requests/state"` |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateError.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateError.mdnew file mode 100644index 0000000000..fd526664c0--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateError.md@@ -0,0 +1,3 @@+# Type Alias: SetGithubPullRequestStateError++> **SetGithubPullRequestStateError** = [`SetGithubPullRequestStateErrors`](SetGithubPullRequestStateErrors.md)\[keyof [`SetGithubPullRequestStateErrors`](SetGithubPullRequestStateErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateErrors.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateErrors.mdnew file mode 100644index 0000000000..51494c6153--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateErrors.md@@ -0,0 +1,14 @@+# Type Alias: SetGithubPullRequestStateErrors++> **SetGithubPullRequestStateErrors** = \{ `401`: [`ErrorResponse`](ErrorResponse.md); `403`: [`ErrorResponse`](ErrorResponse.md); `404`: [`ErrorResponse`](ErrorResponse.md); `422`: [`ErrorResponse`](ErrorResponse.md); `428`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-401"></a> `401` | [`ErrorResponse`](ErrorResponse.md) | - |+| <a id="property-403"></a> `403` | [`ErrorResponse`](ErrorResponse.md) | The user cannot change the pull request |+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) | No GitHub link, or the pull request is not visible to the user |+| <a id="property-422"></a> `422` | [`ErrorResponse`](ErrorResponse.md) | GitHub declined the change |+| <a id="property-428"></a> `428` | [`ErrorResponse`](ErrorResponse.md) | - |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) | - |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateRequest.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateRequest.mdnew file mode 100644index 0000000000..319e00e10b--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateRequest.md@@ -0,0 +1,14 @@+# Type Alias: SetGithubPullRequestStateRequest++> **SetGithubPullRequestStateRequest** = \{ `number`: `number`; `owner`: `string`; `repo`: `string`; `state`: [`GithubPullRequestState`](GithubPullRequestState.md); \}++A request to close one pull request, or reopen it, on the user's behalf.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-number"></a> `number` | `number` | The GitHub pull request number. |+| <a id="property-owner"></a> `owner` | `string` | The GitHub repository owner or organization. |+| <a id="property-repo"></a> `repo` | `string` | The GitHub repository name. |+| <a id="property-state"></a> `state` | [`GithubPullRequestState`](GithubPullRequestState.md) | `closed` closes the pull request; `open` reopens it. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponse.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponse.mdnew file mode 100644index 0000000000..74f153bcc7--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponse.md@@ -0,0 +1,12 @@+# Type Alias: SetGithubPullRequestStateResponse++> **SetGithubPullRequestStateResponse** = \{ `pullRequest?`: `null` \| [`EnrichedGithubPullRequest`](EnrichedGithubPullRequest.md); `state`: [`GithubPullRequestState`](GithubPullRequestState.md); \}++Response body for a pull request that was closed or reopened.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-pullrequest"></a> `pullRequest?` | `null` \| [`EnrichedGithubPullRequest`](EnrichedGithubPullRequest.md) | - |+| <a id="property-state"></a> `state` | [`GithubPullRequestState`](GithubPullRequestState.md) | Whether the pull request is now open or closed. |diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponse2.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponse2.mdnew file mode 100644index 0000000000..d0aa1a0ac5--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponse2.md@@ -0,0 +1,3 @@+# Type Alias: SetGithubPullRequestStateResponse2++> **SetGithubPullRequestStateResponse2** = [`SetGithubPullRequestStateResponses`](SetGithubPullRequestStateResponses.md)\[keyof [`SetGithubPullRequestStateResponses`](SetGithubPullRequestStateResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponses.md b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponses.mdnew file mode 100644index 0000000000..1b6a12e868--- /dev/null+++ b/packages/sdk-docs/reference/generated/auth/types.gen/type-aliases/SetGithubPullRequestStateResponses.md@@ -0,0 +1,9 @@+# Type Alias: SetGithubPullRequestStateResponses++> **SetGithubPullRequestStateResponses** = \{ `200`: [`SetGithubPullRequestStateResponse`](SetGithubPullRequestStateResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`SetGithubPullRequestStateResponse`](SetGithubPullRequestStateResponse.md) |diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.tsindex c9a1fd7e41..0d510d1b7f 100644--- a/packages/sdk/generated/auth/index.ts+++ b/packages/sdk/generated/auth/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';+export type { AbGroup, AgentApiKey, AgentApiKeyProvider, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreatedTeamInviteLinkResponse, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkError, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponse, CreateTeamInviteLinkResponses, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteAgentApiKeyData, DeleteAgentApiKeyError, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponse, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkError, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponse, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmailConnectionProviders, EmailConnectionProvidersData, EmailConnectionProvidersError, EmailConnectionProvidersErrors, EmailConnectionProvidersResponse, EmailConnectionProvidersResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAgentApiKeyData, GetAgentApiKeyError, GetAgentApiKeyErrors, GetAgentApiKeyResponse, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkError, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponse, GetTeamByInviteLinkResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkError, GetTeamInviteLinkErrors, GetTeamInviteLinkResponse, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageError, GetUserLanguageErrors, GetUserLanguageResponse, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkError, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponse, JoinTeamByInviteLinkResponse2, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, Language, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutAgentApiKeyData, PutAgentApiKeyError, PutAgentApiKeyErrors, PutAgentApiKeyRequest, PutAgentApiKeyResponse, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageError, PutUserLanguageErrors, PutUserLanguageResponse, PutUserLanguageResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SavedAgentApiKey, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateError, SetGithubPullRequestStateErrors, SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse, SetGithubPullRequestStateResponse2, SetGithubPullRequestStateResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInviteLinkResponse, TeamInviteLinkTeam, TeamInviteLinkToken, TeamInviteLinkTokenRequest, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLanguage, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex 50d9cb7a59..cfee864f66 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamInviteLinkData, CreateTeamInviteLinkErrors, CreateTeamInviteLinkResponses, CreateTeamResponses, DeleteAgentApiKeyData, DeleteAgentApiKeyErrors, DeleteAgentApiKeyResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamInviteLinkData, DeleteTeamInviteLinkErrors, DeleteTeamInviteLinkResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EmailConnectionProvidersData, EmailConnectionProvidersErrors, EmailConnectionProvidersResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAgentApiKeyData, GetAgentApiKeyErrors, GetAgentApiKeyResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamByInviteLinkData, GetTeamByInviteLinkErrors, GetTeamByInviteLinkResponses, GetTeamData, GetTeamErrors, GetTeamInviteLinkData, GetTeamInviteLinkErrors, GetTeamInviteLinkResponses, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLanguageData, GetUserLanguageErrors, GetUserLanguageResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamByInviteLinkData, JoinTeamByInviteLinkErrors, JoinTeamByInviteLinkResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutAgentApiKeyData, PutAgentApiKeyErrors, PutAgentApiKeyResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserLanguageData, PutUserLanguageErrors, PutUserLanguageResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SetGithubPullRequestStateData, SetGithubPullRequestStateErrors, SetGithubPullRequestStateResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -363,6 +363,21 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Closes a GitHub pull request, or reopens it, as the authenticated user+ * with their own GitHub grant.+ */+ public setGithubPullRequestState<ThrowOnError extends boolean = false>(options: Options<SetGithubPullRequestStateData, ThrowOnError>): RequestResult<SetGithubPullRequestStateResponses, SetGithubPullRequestStateErrors, ThrowOnError> {+ return (options.client ?? this.client).post<SetGithubPullRequestStateResponses, SetGithubPullRequestStateErrors, ThrowOnError>({+ url: '/github_pull_requests/state',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Lists invite links, newest first. Macro staff only.*/diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex f2325cb0c8..36c8db251d 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -923,6 +923,13 @@ export type GithubPullRequestReview = {*/export type GithubPullRequestReviewState = 'approved' | 'changes_requested' | 'commented' | 'dismissed';+/**+ * Whether a pull request is open or closed, as a user sets it. Merging is a+ * separate action, so unlike `GithubPullRequestStatus` there is no merged+ * state.+ */+export type GithubPullRequestState = 'open' | 'closed';+/*** The normalized lifecycle status for a GitHub pull request.*/@@ -1600,6 +1607,39 @@ export type SetGithubPullRequestDraftResponse = {pullRequest?: null | EnrichedGithubPullRequest;};+/**+ * A request to close one pull request, or reopen it, on the user's behalf.+ */+export type SetGithubPullRequestStateRequest = {+ /**+ * The GitHub pull request number.+ */+ number: number;+ /**+ * The GitHub repository owner or organization.+ */+ owner: string;+ /**+ * The GitHub repository name.+ */+ repo: string;+ /**+ * `closed` closes the pull request; `open` reopens it.+ */+ state: GithubPullRequestState;+};++/**+ * Response body for a pull request that was closed or reopened.+ */+export type SetGithubPullRequestStateResponse = {+ pullRequest?: null | EnrichedGithubPullRequest;+ /**+ * Whether the pull request is now open or closed.+ */+ state: GithubPullRequestState;+};+export type SsoRequiredResponse = {/*** The idp_id you need to perform sso login with.@@ -2680,6 +2720,39 @@ export type GetGithubPullRequestMergeabilityResponses = {export type GetGithubPullRequestMergeabilityResponse = GetGithubPullRequestMergeabilityResponses[keyof GetGithubPullRequestMergeabilityResponses];+export type SetGithubPullRequestStateData = {+ body: SetGithubPullRequestStateRequest;+ path?: never;+ query?: never;+ url: '/github_pull_requests/state';+};++export type SetGithubPullRequestStateErrors = {+ 401: ErrorResponse;+ /**+ * The user cannot change the pull request+ */+ 403: ErrorResponse;+ /**+ * No GitHub link, or the pull request is not visible to the user+ */+ 404: ErrorResponse;+ /**+ * GitHub declined the change+ */+ 422: ErrorResponse;+ 428: ErrorResponse;+ 500: ErrorResponse;+};++export type SetGithubPullRequestStateError = SetGithubPullRequestStateErrors[keyof SetGithubPullRequestStateErrors];++export type SetGithubPullRequestStateResponses = {+ 200: SetGithubPullRequestStateResponse;+};++export type SetGithubPullRequestStateResponse2 = SetGithubPullRequestStateResponses[keyof SetGithubPullRequestStateResponses];+export type ListGtmInviteLinksData = {body?: never;path?: never;diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 22c26686a5..53b5a2db7d 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -1374,6 +1374,95 @@}}},+ "/github_pull_requests/state": {+ "post": {+ "tags": ["github_pull_requests"],+ "summary": "Closes a GitHub pull request, or reopens it, as the authenticated user\nwith their own GitHub grant.",+ "operationId": "set_github_pull_request_state",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetGithubPullRequestStateRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetGithubPullRequestStateResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "403": {+ "description": "The user cannot change the pull request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "No GitHub link, or the pull request is not visible to the user",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "422": {+ "description": "GitHub declined the change",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "428": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/gtm-invite/links": {"get": {"tags": ["gtm_invite"],@@ -6898,6 +6987,11 @@"description": "What a reviewer's latest review on a pull request said.","enum": ["approved", "changes_requested", "commented", "dismissed"]},+ "GithubPullRequestState": {+ "type": "string",+ "description": "Whether a pull request is open or closed, as a user sets it. Merging is a\nseparate action, so unlike `GithubPullRequestStatus` there is no merged\nstate.",+ "enum": ["open", "closed"]+ },"GithubPullRequestStatus": {"type": "string","description": "The normalized lifecycle status for a GitHub pull request.",@@ -7817,6 +7911,53 @@}}},+ "SetGithubPullRequestStateRequest": {+ "type": "object",+ "description": "A request to close one pull request, or reopen it, on the user's behalf.",+ "required": ["owner", "repo", "number", "state"],+ "properties": {+ "number": {+ "type": "integer",+ "format": "int64",+ "description": "The GitHub pull request number.",+ "minimum": 0+ },+ "owner": {+ "type": "string",+ "description": "The GitHub repository owner or organization."+ },+ "repo": {+ "type": "string",+ "description": "The GitHub repository name."+ },+ "state": {+ "$ref": "#/components/schemas/GithubPullRequestState",+ "description": "`closed` closes the pull request; `open` reopens it."+ }+ }+ },+ "SetGithubPullRequestStateResponse": {+ "type": "object",+ "description": "Response body for a pull request that was closed or reopened.",+ "required": ["state"],+ "properties": {+ "pullRequest": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/EnrichedGithubPullRequest",+ "description": "The pull request as GitHub reports it after the change, when the\nrefresh succeeded."+ }+ ]+ },+ "state": {+ "$ref": "#/components/schemas/GithubPullRequestState",+ "description": "Whether the pull request is now open or closed."+ }+ }+ },"SsoRequiredResponse": {"type": "object","required": ["idp_id"],diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex c2245403f3..d1d922da0b 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -136,6 +136,7 @@ export const authExcluded = ['sessionCreation','sessionLogin','setGithubPullRequestDraft',+ 'setGithubPullRequestState','ssoLogin','startCodexLogin','toggleTeamAutoJoinDomain',diff --git a/services/authentication_service/src/api/github_pull_requests.rs b/services/authentication_service/src/api/github_pull_requests.rsindex 1e9a717565..11691d7056 100644--- a/services/authentication_service/src/api/github_pull_requests.rs+++ b/services/authentication_service/src/api/github_pull_requests.rs@@ -11,6 +11,7 @@ use github::domain::{GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse,MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse,},ports::GithubLinkService,};@@ -139,6 +140,7 @@ pub fn router() -> Router<ApiContext> {.route("/enrich", post(handler)).route("/merge", post(merge_handler)).route("/draft", post(draft_handler))+ .route("/state", post(state_handler)).route("/mergeability", post(mergeability_handler))}@@ -243,6 +245,39 @@ pub async fn draft_handler(Ok(Json(response))}+/// Closes a GitHub pull request, or reopens it, as the authenticated user+/// with their own GitHub grant.+#[utoipa::path(+ post,+ path = "/github_pull_requests/state",+ operation_id = "set_github_pull_request_state",+ request_body = SetGithubPullRequestStateRequest,+ responses(+ (status = 200, body = SetGithubPullRequestStateResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, description = "The user cannot change the pull request", body = ErrorResponse),+ (status = 404, description = "No GitHub link, or the pull request is not visible to the user", body = ErrorResponse),+ (status = 422, description = "GitHub declined the change", body = ErrorResponse),+ (status = 428, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, authorization, request), fields(user_id = %authorization.authorization.user.macro_user_id), err)]+pub async fn state_handler(+ State(ctx): State<ApiContext>,+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+ extract::Json(request): extract::Json<SetGithubPullRequestStateRequest>,+) -> Result<Json<SetGithubPullRequestStateResponse>, UpdateGithubPullRequestError> {+ tracing::info!("set_github_pull_request_state");++ let response = ctx+ .github_link_service+ .set_pull_request_state(&authorization.authorization.user.macro_user_id, request)+ .await?;++ Ok(Json(response))+}+/// Reads whether each GitHub pull request merges cleanly into its base, as/// the authenticated user sees it. Pull requests the user cannot see are/// left out.diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex 8635659ee1..ab1999398f 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -3,9 +3,10 @@ use github::domain::models::{EnrichedGithubPullRequest, GithubMergeMethod, GithubPullRequestCheckRun,GithubPullRequestComment, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry,GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse,- GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestStatus,+ GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestState, GithubPullRequestStatus,MergeGithubPullRequestRequest, MergeGithubPullRequestResponse,SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse,+ SetGithubPullRequestStateRequest, SetGithubPullRequestStateResponse,};use gtm_invite::inbound::axum_router::dto::{CreateGtmInviteLinkRequest, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus,@@ -125,6 +126,7 @@ use model::user::{github_pull_requests::handler,github_pull_requests::merge_handler,github_pull_requests::draft_handler,+ github_pull_requests::state_handler,github_pull_requests::mergeability_handler,/// /oauth@@ -299,6 +301,9 @@ use model::user::{MergeGithubPullRequestResponse,SetGithubPullRequestDraftRequest,SetGithubPullRequestDraftResponse,+ GithubPullRequestState,+ SetGithubPullRequestStateRequest,+ SetGithubPullRequestStateResponse,GithubPullRequestNumber,GithubPullRequestMergeability,GithubPullRequestMergeabilityEntry,@@ -443,6 +448,26 @@ mod tests {);}+ #[test]+ fn github_pull_requests_openapi_includes_state_path() {+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();+ let operation = &openapi["paths"]["/github_pull_requests/state"]["post"];++ assert_eq!(operation["operationId"], "set_github_pull_request_state");+ assert_eq!(+ operation["requestBody"]["content"]["application/json"]["schema"]["$ref"].as_str(),+ Some("#/components/schemas/SetGithubPullRequestStateRequest")+ );+ assert_eq!(+ operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str(),+ Some("#/components/schemas/SetGithubPullRequestStateResponse")+ );+ assert_eq!(+ openapi["components"]["schemas"]["GithubPullRequestState"]["enum"],+ serde_json::json!(["open", "closed"])+ );+ }+#[test]fn github_link_status_openapi_includes_path_and_schema() {let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();diff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.mdindex b6146dafa6..8e19eb9758 100644--- a/services/document_storage_service/AGENTS.md+++ b/services/document_storage_service/AGENTS.md@@ -35,7 +35,9 @@ threads, pins, recents, notifications, folders, activity.- Guest call chat is mounted outside account auth at `/call/guest-chat/{call_id}`;`call` verifies the RTC session and `messages` owns the shared discussion.- `src/service/entity_mutation.rs`: generic entity-mutation plumbing used- across item types.+ across item types. Folder duplication runs on its own task and copies+ documents and chats through `entity_mutation/project_contents.rs`, the+ projects domain's `ProjectContentCopier` port.- `src/outbound/docx_export.rs`: primary-database parts and immutable DOCX exportobjects keyed by part paths/hashes. The export route maps the documents domain'spending result to 409 with `Retry-After`; never reuse document-id-only archives.diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rsindex 02da5cf4ab..8e83b639f4 100644--- a/services/document_storage_service/src/service/entity_mutation.rs+++ b/services/document_storage_service/src/service/entity_mutation.rs@@ -36,11 +36,16 @@ use entity_mutation::{RestoreEntity, TrashEntity, UpdateEntitySharePolicy, UpdateEntitySharePolicyRequest,capability::MoveEntityRequest as CapabilityMoveEntityRequest,};+use entity_registry::PurgeOwnedEntity;use futures::{StreamExt, stream};use model_entity::{Entity, EntityType};use models_permissions::share_permission::UpdateSharePermissionRequestV2;-use projects_hex::domain::ports::ProjectService;+use projects_hex::domain::{duplicate::ProjectDuplicator, ports::ProjectService};+use tracing::Instrument;+use project_contents::DssProjectContents;++mod project_contents;#[cfg(test)]mod test;@@ -230,7 +235,8 @@ where+ UpdateEntitySharePolicy+ TrashEntity+ RestoreEntity- + DeleteEntityPermanently,+ + DeleteEntityPermanently+ + PurgeOwnedEntity,Databases:DatabasesService + RenameEntity + TrashEntity + RestoreEntity + DeleteEntityPermanently,Forms: RenameEntity@@ -732,6 +738,40 @@ where)}+ /// Duplicate a folder with its subfolders, documents, and chats. The copy+ /// runs on its own task, so a dropped request cannot stop it between+ /// creating the copy and discarding a failed one.+ async fn duplicate_project(+ &self,+ actor: &EntityMutationActor,+ requested: &Entity<'static>,+ display_name: Option<String>,+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {+ let duplicator = ProjectDuplicator::new(+ Arc::clone(&self.projects),+ DssProjectContents {+ documents: Arc::clone(&self.documents),+ chats: Arc::clone(&self.chats),+ access: Arc::clone(&self.access),+ lifecycle: Arc::clone(&self.lifecycle),+ actor: actor.clone(),+ },+ );+ let receipt = self.receipt(actor, requested).await?;+ let requested = requested.clone();+ let user_id = actor.user_id.clone();+ tokio::spawn(+ async move {+ duplicator+ .duplicate_entity(requested, receipt, user_id, display_name)+ .await+ }+ .in_current_span(),+ )+ .await+ .map_err(|error| EntityMutationErrorCode::internal(rootcause::report!(error)))?+ }+#[tracing::instrument(skip_all, fields(entity_type = %request.entity.entity_type, entity_id = %request.entity.entity_id))]async fn duplicate_one(&self,@@ -751,12 +791,15 @@ whereself.duplicate_with(&*self.chats, actor, &requested, display_name).await}+ EntityType::Project => {+ self.duplicate_project(actor, &requested, display_name)+ .await+ }EntityType::User| EntityType::Team| EntityType::Channel| EntityType::ChannelMessage| EntityType::EmailThread- | EntityType::Project| EntityType::Call| EntityType::ForeignEntity| EntityType::StaticFile@@ -807,7 +850,8 @@ where+ UpdateEntitySharePolicy+ TrashEntity+ RestoreEntity- + DeleteEntityPermanently,+ + DeleteEntityPermanently+ + PurgeOwnedEntity,Databases:DatabasesService + RenameEntity + TrashEntity + RestoreEntity + DeleteEntityPermanently,Forms: RenameEntitydiff --git a/services/document_storage_service/src/service/entity_mutation/project_contents.rs b/services/document_storage_service/src/service/entity_mutation/project_contents.rsnew file mode 100644index 0000000000..9d55a22ea4--- /dev/null+++ b/services/document_storage_service/src/service/entity_mutation/project_contents.rs@@ -0,0 +1,267 @@+//! What folder duplication borrows from the router's other domains: access+//! checks through `entity_access`, and copying documents and chats through+//! their own duplicate and move capabilities. The projects domain drives the+//! copy through this port, so it never depends on those domains.++use std::sync::Arc;++use entity_access::domain::{+ models::{+ AccessError, EditAccessLevel, EntityAccessReceipt, RequiredPermission, ViewAccessLevel,+ },+ ports::EntityAccessService,+};+use entity_mutation::{+ DeleteEntityPermanently, DuplicateEntity, EntityMutationActor, EntityMutationEffect,+ EntityMutationErrorCode, MoveEntity, capability::MoveEntityRequest,+};+use model_entity::{Entity, EntityType};+use projects_hex::domain::ports::ProjectContentCopier;++use super::{EntityLifecycleService, access_failure};++#[cfg(test)]+mod test;++/// The router's document, chat, access, and lifecycle services, acting for+/// the user who duplicates a folder.+pub(super) struct DssProjectContents<D, H, A, L> {+ pub(super) documents: Arc<D>,+ pub(super) chats: Arc<H>,+ pub(super) access: Arc<A>,+ pub(super) lifecycle: Arc<L>,+ pub(super) actor: EntityMutationActor,+}++/// A failed copy, carrying the copy when it was created but not filed.+struct CopyFailure {+ error: EntityMutationErrorCode,+ unfiled: Option<Entity<'static>>,+}++impl CopyFailure {+ fn not_created(error: EntityMutationErrorCode) -> Self {+ Self {+ error,+ unfiled: None,+ }+ }+}++/// Whether an access failure only means the user may not act on the entity.+fn denied(error: &AccessError) -> bool {+ match error {+ AccessError::Unauthorized+ | AccessError::UnauthorizedWithMessage(_)+ | AccessError::NotFound(_) => true,+ AccessError::BadRequest(_) | AccessError::Unavailable(_) | AccessError::Internal(_) => {+ false+ }+ }+}++impl<D, H, A, L> DssProjectContents<D, H, A, L>+where+ D: DuplicateEntity + MoveEntity + Send + Sync,+ H: DuplicateEntity + MoveEntity + DeleteEntityPermanently + Send + Sync,+ A: EntityAccessService,+ L: EntityLifecycleService,+{+ async fn receipt<T: RequiredPermission>(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ self.access+ .generate_entity_access_receipt::<T>(+ &self.actor.user_id,+ self.actor.organization_id,+ entity_id,+ entity_type,+ )+ .await+ }++ /// Duplicate through `service`, then move the copy into `project_id`.+ /// Duplication files a copy beside its source or at the root, so the+ /// move is what places it in the folder copy.+ async fn duplicate_into<S: DuplicateEntity + MoveEntity>(+ &self,+ service: &S,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ display_name: Option<String>,+ project_id: &str,+ ) -> Result<Entity<'static>, CopyFailure> {+ let source = receipt.entity().clone();+ let receipt = receipt+ .try_into_requirement::<<S as DuplicateEntity>::Receipt>()+ .map_err(|error| CopyFailure::not_created(access_failure(error)))?;+ let effects = service+ .duplicate_entity(+ source.entity_type.with_entity_string(source.entity_id),+ receipt,+ self.actor.user_id.clone(),+ display_name,+ )+ .await+ .map_err(CopyFailure::not_created)?;+ let copy = effects+ .into_iter()+ .find_map(|effect| match effect {+ EntityMutationEffect::Updated(entity)+ if entity.entity_type == source.entity_type =>+ {+ Some(entity)+ }+ EntityMutationEffect::Updated(_) | EntityMutationEffect::Deleted(_) => None,+ })+ .ok_or_else(|| {+ CopyFailure::not_created(EntityMutationErrorCode::internal(rootcause::report!(+ "duplication reported no copy".to_string()+ )))+ })?;++ let filed = async {+ let receipt = self+ .receipt::<<S as MoveEntity>::Receipt>(©.entity_id, copy.entity_type)+ .await+ .map_err(access_failure)?;+ let project_receipt = self+ .receipt::<EditAccessLevel>(project_id, EntityType::Project)+ .await+ .map_err(access_failure)?;+ service+ .move_entity(MoveEntityRequest::MoveToProject {+ entity: copy.clone(),+ receipt,+ project_id: project_id.to_string(),+ project_receipt,+ })+ .await+ }+ .await;+ match filed {+ Ok(_) => Ok(copy),+ Err(error) => Err(CopyFailure {+ error,+ unfiled: Some(copy),+ }),+ }+ }++ async fn discard_document(&self, copy: &Entity<'static>) {+ let _ = self+ .lifecycle+ .delete_document_permanently(&self.actor, copy)+ .await+ .inspect_err(|error| {+ tracing::error!(error = ?error, entity_id = %copy.entity_id, "unable to discard unfiled document copy");+ });+ }++ async fn discard_chat(&self, copy: &Entity<'static>) {+ let deleted = match self+ .receipt::<<H as DeleteEntityPermanently>::Receipt>(©.entity_id, copy.entity_type)+ .await+ {+ Ok(receipt) => self+ .chats+ .delete_entity_permanently(copy.clone(), receipt)+ .await+ .map(drop),+ Err(error) => Err(access_failure(error)),+ };+ let _ = deleted.inspect_err(|error| {+ tracing::error!(error = ?error, entity_id = %copy.entity_id, "unable to discard unfiled chat copy");+ });+ }+}++impl<D, H, A, L> ProjectContentCopier for DssProjectContents<D, H, A, L>+where+ D: DuplicateEntity + MoveEntity + Send + Sync,+ H: DuplicateEntity + MoveEntity + DeleteEntityPermanently + Send + Sync,+ A: EntityAccessService,+ L: EntityLifecycleService,+{+ async fn view_receipt(+ &self,+ entity: &Entity<'static>,+ ) -> Result<Option<EntityAccessReceipt<ViewAccessLevel>>, EntityMutationErrorCode> {+ match self+ .receipt::<ViewAccessLevel>(&entity.entity_id, entity.entity_type)+ .await+ {+ Ok(receipt) => Ok(Some(receipt)),+ Err(error) if denied(&error) => Ok(None),+ Err(error) => Err(access_failure(error)),+ }+ }++ async fn can_add_to_project(&self, project_id: &str) -> Result<bool, EntityMutationErrorCode> {+ match self+ .receipt::<EditAccessLevel>(project_id, EntityType::Project)+ .await+ {+ Ok(_) => Ok(true),+ Err(error) if denied(&error) => Ok(false),+ Err(error) => Err(access_failure(error)),+ }+ }++ #[tracing::instrument(+ name = "project.duplicate.copy_item",+ skip_all,+ fields(+ entity_type = %receipt.entity().entity_type,+ entity_id = %receipt.entity().entity_id,+ project_id = %project_id,+ copy_id = tracing::field::Empty,+ ),+ err(Debug)+ )]+ async fn copy_into_project(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ name: String,+ project_id: &str,+ ) -> Result<Entity<'static>, EntityMutationErrorCode> {+ let copied = match receipt.entity().entity_type {+ EntityType::Document => {+ let copied = self+ .duplicate_into(&*self.documents, receipt, Some(name), project_id)+ .await;+ if let Err(CopyFailure {+ unfiled: Some(copy),+ ..+ }) = &copied+ {+ self.discard_document(copy).await;+ }+ copied+ }+ // Chat duplication names its copy and accepts no chosen name.+ EntityType::Chat => {+ let copied = self+ .duplicate_into(&*self.chats, receipt, None, project_id)+ .await;+ if let Err(CopyFailure {+ unfiled: Some(copy),+ ..+ }) = &copied+ {+ self.discard_chat(copy).await;+ }+ copied+ }+ entity_type => {+ return Err(EntityMutationErrorCode::unsupported(+ rootcause::report!(entity_type).attach("copy into a project"),+ ));+ }+ };+ let copy = copied.map_err(|failure| failure.error)?;+ tracing::Span::current().record("copy_id", copy.entity_id.as_ref());+ Ok(copy)+ }+}diff --git a/services/document_storage_service/src/service/entity_mutation/project_contents/test.rs b/services/document_storage_service/src/service/entity_mutation/project_contents/test.rsnew file mode 100644index 0000000000..cda9f94922--- /dev/null+++ b/services/document_storage_service/src/service/entity_mutation/project_contents/test.rs@@ -0,0 +1,402 @@+use std::{+ collections::HashSet,+ sync::{Arc, Mutex},+};++use entity_access::domain::{+ models::{+ AccessLevel, BotAccessScope, BotId, CallChannelInfo, Entity as AccessEntity,+ EntityPermission, OwnerAccessLevel, TeamRole, UserTeamInfo,+ },+ ports::NoOpEntityAccessService,+};+use macro_user_id::{+ lowercased::Lowercase,+ user_id::{MacroUserId, MacroUserIdStr},+};+use uuid::Uuid;++use super::*;+use crate::service::entity_mutation::LifecycleError;++const USER: &str = "macro|[email protected]";+const FOLDER_COPY: &str = "10000000-0000-0000-0000-00000000000c";++/// Grants owner access to everything except `denied`, and fails outright on+/// `unavailable`.+#[derive(Clone, Default)]+struct FakeAccess {+ denied: HashSet<&'static str>,+ unavailable: HashSet<&'static str>,+}++impl EntityAccessService for FakeAccess {+ async fn generate_entity_access_receipt<T: RequiredPermission>(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ if self.denied.contains(entity_id) {+ return Err(AccessError::Unauthorized);+ }+ if self.unavailable.contains(entity_id) {+ return Err(AccessError::internal("access store unavailable"));+ }+ EntityAccessReceipt::try_new_authenticated_user(+ MacroUserIdStr::try_from(USER.to_string()).unwrap(),+ AccessEntity {+ entity_id: entity_id.to_string(),+ entity_type,+ },+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ },+ )+ }++ async fn generate_bot_entity_access_receipt<T: RequiredPermission>(+ &self,+ bot_id: BotId,+ scope: BotAccessScope,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<EntityAccessReceipt<T>, AccessError> {+ NoOpEntityAccessService+ .generate_bot_entity_access_receipt(bot_id, scope, entity_id, entity_type)+ .await+ }++ async fn get_access_level(+ &self,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ NoOpEntityAccessService+ .get_access_level(user_id, entity_id, entity_type)+ .await+ }++ async fn check_access(+ &self,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ entity_id: &str,+ entity_type: EntityType,+ required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ NoOpEntityAccessService+ .check_access(user_id, entity_id, entity_type, required_level)+ .await+ }++ async fn check_public_access(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ NoOpEntityAccessService+ .check_public_access(entity_id, entity_type, required_level)+ .await+ }++ async fn get_entity_permission(+ &self,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ entity_id: &str,+ entity_type: EntityType,+ user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ NoOpEntityAccessService+ .get_entity_permission(user_id, entity_id, entity_type, user_org_id)+ .await+ }++ async fn get_crm_entity_permission_with_team(+ &self,+ user_id: Option<&MacroUserId<Lowercase<'_>>>,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<(EntityPermission, Uuid, TeamRole), AccessError> {+ NoOpEntityAccessService+ .get_crm_entity_permission_with_team(user_id, entity_id, entity_type)+ .await+ }++ async fn get_users_by_entity(+ &self,+ entity_id: &str,+ entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ NoOpEntityAccessService+ .get_users_by_entity(entity_id, entity_type)+ .await+ }++ async fn get_call_channel(+ &self,+ call_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ NoOpEntityAccessService.get_call_channel(call_id).await+ }++ async fn get_call_channel_by_channel_id(+ &self,+ channel_id: &Uuid,+ ) -> Result<Option<CallChannelInfo>, AccessError> {+ NoOpEntityAccessService+ .get_call_channel_by_channel_id(channel_id)+ .await+ }++ async fn get_user_team(+ &self,+ user_id: &MacroUserId<Lowercase<'_>>,+ ) -> Result<Option<UserTeamInfo>, AccessError> {+ NoOpEntityAccessService.get_user_team(user_id).await+ }+}++/// Duplicates into `<source>-copy`, records moves and deletions, and fails+/// every move when `moves_fail` is set.+#[derive(Default)]+struct FakeDomain {+ moves_fail: bool,+ moved: Mutex<Vec<(String, String)>>,+ deleted: Mutex<Vec<String>>,+}++impl DuplicateEntity for FakeDomain {+ type Receipt = ViewAccessLevel;++ async fn duplicate_entity(+ &self,+ entity: Entity<'static>,+ _receipt: EntityAccessReceipt<Self::Receipt>,+ _user_id: MacroUserIdStr<'static>,+ _display_name: Option<String>,+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {+ Ok(vec![EntityMutationEffect::updated(+ entity+ .entity_type+ .with_entity_string(format!("{}-copy", entity.entity_id)),+ )])+ }+}++impl MoveEntity for FakeDomain {+ type Receipt = OwnerAccessLevel;++ async fn move_entity(+ &self,+ request: MoveEntityRequest<Self::Receipt>,+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {+ let MoveEntityRequest::MoveToProject {+ entity, project_id, ..+ } = request+ else {+ panic!("copies are only moved into a project");+ };+ if self.moves_fail {+ return Err(EntityMutationErrorCode::internal(rootcause::report!(+ "move failed".to_string()+ )));+ }+ self.moved+ .lock()+ .unwrap()+ .push((entity.entity_id.to_string(), project_id));+ Ok(vec![EntityMutationEffect::updated(entity)])+ }+}++impl DeleteEntityPermanently for FakeDomain {+ type Receipt = OwnerAccessLevel;++ async fn delete_entity_permanently(+ &self,+ entity: Entity<'static>,+ _receipt: EntityAccessReceipt<Self::Receipt>,+ ) -> Result<Vec<EntityMutationEffect>, EntityMutationErrorCode> {+ self.deleted+ .lock()+ .unwrap()+ .push(entity.entity_id.to_string());+ Ok(vec![EntityMutationEffect::deleted(entity)])+ }+}++/// Records the documents deleted through the lifecycle port.+#[derive(Default)]+struct FakeLifecycle {+ deleted: Mutex<Vec<String>>,+}++impl EntityLifecycleService for FakeLifecycle {+ async fn update_thread_share_policy(+ &self,+ _actor: &EntityMutationActor,+ _entity: &Entity<'static>,+ _policy: models_permissions::share_permission::UpdateSharePermissionRequestV2,+ ) -> Result<Vec<Entity<'static>>, LifecycleError> {+ unreachable!("folder duplication never shares threads")+ }++ async fn restore_document(+ &self,+ _actor: &EntityMutationActor,+ _entity: &Entity<'static>,+ ) -> Result<Vec<Entity<'static>>, LifecycleError> {+ unreachable!("folder duplication never restores documents")+ }++ async fn delete_document_permanently(+ &self,+ _actor: &EntityMutationActor,+ entity: &Entity<'static>,+ ) -> Result<Vec<Entity<'static>>, LifecycleError> {+ self.deleted+ .lock()+ .unwrap()+ .push(entity.entity_id.to_string());+ Ok(Vec::new())+ }+}++type TestContents = DssProjectContents<FakeDomain, FakeDomain, FakeAccess, FakeLifecycle>;++fn contents(moves_fail: bool, access: FakeAccess) -> TestContents {+ DssProjectContents {+ documents: Arc::new(FakeDomain {+ moves_fail,+ ..FakeDomain::default()+ }),+ chats: Arc::new(FakeDomain {+ moves_fail,+ ..FakeDomain::default()+ }),+ access: Arc::new(access),+ lifecycle: Arc::new(FakeLifecycle::default()),+ actor: EntityMutationActor {+ user_id: MacroUserIdStr::try_from(USER.to_string()).unwrap(),+ organization_id: None,+ },+ }+}++fn view_receipt(entity_id: &str, entity_type: EntityType) -> EntityAccessReceipt<ViewAccessLevel> {+ EntityAccessReceipt::dangerously_assert_authenticated_user(+ MacroUserIdStr::try_from(USER.to_string()).unwrap(),+ entity_id,+ entity_type,+ )+}++#[tokio::test]+async fn files_each_copy_in_the_folder_copy() {+ let contents = contents(false, FakeAccess::default());++ let document = contents+ .copy_into_project(+ view_receipt("document-1", EntityType::Document),+ "Plan".to_string(),+ FOLDER_COPY,+ )+ .await+ .unwrap();+ let chat = contents+ .copy_into_project(+ view_receipt("chat-1", EntityType::Chat),+ "Thread".to_string(),+ FOLDER_COPY,+ )+ .await+ .unwrap();++ assert_eq!(+ document,+ EntityType::Document.with_entity_string("document-1-copy".to_string())+ );+ assert_eq!(+ chat,+ EntityType::Chat.with_entity_string("chat-1-copy".to_string())+ );+ assert_eq!(+ *contents.documents.moved.lock().unwrap(),+ vec![("document-1-copy".to_string(), FOLDER_COPY.to_string())]+ );+ assert_eq!(+ *contents.chats.moved.lock().unwrap(),+ vec![("chat-1-copy".to_string(), FOLDER_COPY.to_string())]+ );+ assert!(contents.lifecycle.deleted.lock().unwrap().is_empty());+ assert!(contents.chats.deleted.lock().unwrap().is_empty());+}++#[tokio::test]+async fn deletes_a_copy_that_cannot_be_filed() {+ let contents = contents(true, FakeAccess::default());++ let document = contents+ .copy_into_project(+ view_receipt("document-1", EntityType::Document),+ "Plan".to_string(),+ FOLDER_COPY,+ )+ .await;+ let chat = contents+ .copy_into_project(+ view_receipt("chat-1", EntityType::Chat),+ "Thread".to_string(),+ FOLDER_COPY,+ )+ .await;++ assert!(matches!(+ document,+ Err(EntityMutationErrorCode::Internal(_))+ ));+ assert!(matches!(chat, Err(EntityMutationErrorCode::Internal(_))));+ assert_eq!(+ *contents.lifecycle.deleted.lock().unwrap(),+ vec!["document-1-copy".to_string()]+ );+ assert_eq!(+ *contents.chats.deleted.lock().unwrap(),+ vec!["chat-1-copy".to_string()]+ );+}++#[tokio::test]+async fn denied_access_skips_but_an_access_outage_fails() {+ let contents = contents(+ false,+ FakeAccess {+ denied: HashSet::from(["hidden", "locked-parent"]),+ unavailable: HashSet::from(["unreachable"]),+ },+ );++ let hidden = contents+ .view_receipt(&EntityType::Document.with_entity_string("hidden".to_string()))+ .await+ .unwrap();+ let visible = contents+ .view_receipt(&EntityType::Document.with_entity_string("visible".to_string()))+ .await+ .unwrap();+ let unreachable = contents+ .view_receipt(&EntityType::Document.with_entity_string("unreachable".to_string()))+ .await;++ assert!(hidden.is_none());+ assert!(visible.is_some());+ assert!(matches!(+ unreachable,+ Err(EntityMutationErrorCode::Internal(_))+ ));+ assert!(!contents.can_add_to_project("locked-parent").await.unwrap());+ assert!(contents.can_add_to_project(FOLDER_COPY).await.unwrap());+}