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
Seanaye/feat/properties mutation (#4740)
Sean Aye779f32935852
diff --git a/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json b/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.jsonnew file mode 100644index 0000000000..d4a1902ef1--- /dev/null+++ b/.sqlx/query-31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61.json@@ -0,0 +1,87 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n created_at,\n updated_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type: EntityType",+ "type_info": {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK"+ ]+ }+ }+ },+ "Uuid",+ "Jsonb"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "31ac47cc5a518a93cceebbf65878f54f571c2cb9c8376918a6c20bae6c190c61"+}diff --git a/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.json b/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.jsondeleted file mode 100644index a33e79f60e..0000000000--- a/.sqlx/query-7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (entity_id, entity_type, property_definition_id) \n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- },- "Uuid",- "Jsonb"- ]- },- "nullable": []- },- "hash": "7ae5368ee01e670dcc9804096f3d3e9dcab6dcebcb601bfb1ed190dbda0ff37f"-}diff --git a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.jsonnew file mode 100644index 0000000000..5cb39eefda--- /dev/null+++ b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json@@ -0,0 +1,88 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = EXCLUDED.values,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n created_at,\n updated_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type: EntityType",+ "type_info": {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK"+ ]+ }+ }+ },+ "Uuid",+ "Jsonb"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0"+}diff --git a/.sqlx/query-bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0.json b/.sqlx/query-bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0.jsondeleted file mode 100644index 2c1ef9427c..0000000000--- a/.sqlx/query-bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0.json+++ /dev/null@@ -1,33 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK"- ]- }- }- },- "Uuid",- "Jsonb"- ]- },- "nullable": []- },- "hash": "bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0"-}diff --git a/Cargo.lock b/Cargo.lockindex 197f4ba5e8..458a71448d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -5949,9 +5949,9 @@ name = "graphql_notification"version = "0.1.0"dependencies = ["async-graphql",- "async-trait","graphql_common","macro_user_id",+ "model-entity","notification","rootcause","serde_json",@@ -5964,17 +5964,20 @@ name = "graphql_properties"version = "0.1.0"dependencies = ["async-graphql",- "async-trait",+ "chrono",+ "entity_access","filter_ast","graphql_common","item_filters","macro_user_id",+ "model-entity","models_properties","models_soup","properties","rootcause","tokio","tracing",+ "uuid","workspace-hack",]diff --git a/apps/web/src/features/companies/crm/deal-stages.ts b/apps/web/src/features/companies/crm/deal-stages.tsindex 5a6adccb4a..b54e6ce857 100644--- a/apps/web/src/features/companies/crm/deal-stages.ts+++ b/apps/web/src/features/companies/crm/deal-stages.ts@@ -156,6 +156,7 @@ function buildStagePropertyStub(if (!definition) {// System default — same stub the CRM list/kanban always used.return soupPropertyToProperty({+ id: SYSTEM_PROPERTY_IDS.STAGE,definition: {id: SYSTEM_PROPERTY_IDS.STAGE,display_name: 'Stage',@@ -171,6 +172,7 @@ function buildStagePropertyStub(});}const property = soupPropertyToProperty({+ id: definition.definition.id,definition: {id: definition.definition.id,display_name: definition.definition.display_name,diff --git a/apps/web/src/features/entity/extractors-property/property-helpers.ts b/apps/web/src/features/entity/extractors-property/property-helpers.tsindex 406710a8f6..f2a4f7f855 100644--- a/apps/web/src/features/entity/extractors-property/property-helpers.ts+++ b/apps/web/src/features/entity/extractors-property/property-helpers.ts@@ -5,7 +5,6 @@ import {} from '@property/constants';import type { Property, PropertyOption, ValueType } from '@property/types';import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';-import { nanoid } from 'nanoid';import {COMPANY_STAGE_OPTIONS,TASK_STATUS_OPTIONS,@@ -152,7 +151,7 @@ export function soupPropertyToProperty(soupProperty: SoupProperty): Property {const options = getSystemPropertyOptions(definition.id);const baseProperty = {- propertyId: nanoid(8), // SoupProperty doesn't have a property ID, generate one+ propertyId: soupProperty.id,propertyDefinitionId: definition.id,displayName: definition.display_name,isMultiSelect: definition.is_multi_select,@@ -314,6 +313,7 @@ const COMPANY_DEFAULT_PROPERTY_DEFS = [export function buildCompanyDefaultProperties(): Property[] {return COMPANY_DEFAULT_PROPERTY_DEFS.map((def) =>soupPropertyToProperty({+ id: def.id,definition: {id: def.id,display_name: def.displayName,diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex dec0339079..8c78c17551 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -68,6 +68,7 @@ import type {import type { SoupParams } from '@queries/soup/items';import { useSoupAstItemsQuery } from '@queries/soup/items';import { soupKeys } from '@queries/soup/keys';+import { useReactiveSoupAstItemsQuery } from '@queries/soup/reactive-items';import { mapApiSoupItemToEntity } from '@queries/soup/transform-utils';import type { SoupApiItem, SoupPage } from '@service-storage/generated/schemas';import type { InfiniteData } from '@tanstack/solid-query';@@ -246,6 +247,10 @@ export const SoupViewContextProvider: FlowComponent<const trimToFirstPage = () => {const groupBy = serverGroupByField();+ // Reactive urql path keeps its own page list (no-op when inactive or+ // already on one page). Defined below; only invoked at runtime.+ reactiveItemsQuery.trimToFirstPage();+queryClient.setQueryData(soupKeys.astItems({params: soupParams(),@@ -560,6 +565,25 @@ export const SoupViewContextProvider: FlowComponent<);};+ // Reactive urql path (same `enable-graphql-soup` flag as the transport):+ // the flat soup list subscribes to the GraphQL query directly, so+ // normalized-cache pushes (optimistic property writes, sibling writes,+ // other tabs) re-render without a TanStack invalidation round-trip.+ // Grouped views and ASTs without a GraphQL translation stay on TanStack.+ const reactiveEligible = () =>+ useGraphqlSoupFF().enabled && !serverGroupByField();++ const reactiveItemsQuery = useReactiveSoupAstItemsQuery(+ () => ({ params: soupParams(), body: soupBody() }),+ () => ({+ enabled: enabled() && !search.isSearching() && reactiveEligible(),+ showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,+ })+ );++ const reactiveActive = () =>+ reactiveEligible() && reactiveItemsQuery.isSupported();+const itemsQuery = useSoupAstItemsQuery(() => {const groupBy = serverGroupByField();@@ -573,7 +597,7 @@ export const SoupViewContextProvider: FlowComponent<() => {const view = activeListView();return {- enabled: enabled() && !search.isSearching(),+ enabled: enabled() && !search.isSearching() && !reactiveActive(),showSupportedForeignEntities: showSupportedForeignEntitiesFF().enabled,meta: {itemFilter: (item) => soupItemMatchesActiveFilters(item, view),@@ -582,12 +606,49 @@ export const SoupViewContextProvider: FlowComponent<});+ /**+ * Unified soup items surface: the reactive urql query when active, the+ * TanStack infinite query otherwise. Grouped data (`groups`/`itemsById`)+ * only ever comes from the TanStack side — grouping is never reactive.+ */+ const itemsSource = {+ data: () =>+ reactiveActive() ? reactiveItemsQuery.data() : itemsQuery.data,+ isLoading: () =>+ reactiveActive() ? reactiveItemsQuery.isLoading() : itemsQuery.isLoading,+ isFetching: () =>+ reactiveActive()+ ? reactiveItemsQuery.isFetching()+ : itemsQuery.isFetching,+ isPlaceholderData: () =>+ reactiveActive() ? false : itemsQuery.isPlaceholderData,+ isFetchingNextPage: () =>+ reactiveActive()+ ? reactiveItemsQuery.isFetchingNextPage()+ : itemsQuery.isFetchingNextPage,+ isEnabled: () =>+ reactiveActive()+ ? enabled() && !search.isSearching()+ : itemsQuery.isEnabled,+ hasNextPage: () =>+ reactiveActive()+ ? reactiveItemsQuery.hasNextPage()+ : itemsQuery.hasNextPage,+ fetchNextPage: () => {+ if (reactiveActive()) {+ reactiveItemsQuery.fetchNextPage();+ } else {+ itemsQuery.fetchNextPage();+ }+ },+ };+const items = createMemo<SoupEntity[]>((prev) => {const searching = search.isSearching();if (!searching) {- const data = itemsQuery.data;+ const data = itemsSource.data();if (!data || data.groups) return prev;@@ -781,7 +842,7 @@ export const SoupViewContextProvider: FlowComponent<const rows = createMemo((): SoupRow[] => {const field = groupByField();- const groups = itemsQuery.data?.groups;+ const groups = itemsSource.data()?.groups;// Client-side property grouping (Customers view): bucket the flat// (paginated) list by property value; option order comes from the@@ -987,25 +1048,25 @@ export const SoupViewContextProvider: FlowComponent<initialize,source: {data: entities,- isLoading: () => itemsQuery.isLoading,- isFetching: () => itemsQuery.isFetching || searchQuery.isFetching,+ isLoading: () => itemsSource.isLoading(),+ isFetching: () => itemsSource.isFetching() || searchQuery.isFetching,isPlaceholderData: () =>- itemsQuery.isPlaceholderData && !search.isSearching(),+ itemsSource.isPlaceholderData() && !search.isSearching(),isFetchingNextPage: () =>- itemsQuery.isFetchingNextPage || searchQuery.isFetchingNextPage,+ itemsSource.isFetchingNextPage() || searchQuery.isFetchingNextPage,hasNextPage: () => {if (!enabled()) return false;return (- (itemsQuery.isEnabled && itemsQuery.hasNextPage) ||+ (itemsSource.isEnabled() && itemsSource.hasNextPage()) ||(searchQuery.isEnabled && searchQuery.hasNextPage));},fetchNextPage: () => {if (!enabled()) return;- if (itemsQuery.isEnabled) {- itemsQuery.fetchNextPage();+ if (itemsSource.isEnabled()) {+ itemsSource.fetchNextPage();}if (searchQuery.isEnabled) {searchQuery.fetchNextPage();@@ -1023,6 +1084,9 @@ export const SoupViewContextProvider: FlowComponent<// instead of retracting as if the refresh succeeded.{ throwOnError: true }),+ // The reactive urql page refetches from the network directly;+ // it is outside the TanStack cache the invalidation reaches.+ reactiveActive() ? reactiveItemsQuery.refresh() : Promise.resolve(),invalidateUserNotifications(),]);},diff --git a/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx b/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsxindex 6fc71c4406..e37bfa9af3 100644--- a/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx+++ b/apps/web/src/features/next-soup/soup-view/views/tasks/task-grid-layout.tsx@@ -47,6 +47,7 @@ const EPOCH = new Date(0).toISOString();*/function buildStubProperty(col: TaskGridColumn): Property {const stubSoup: SoupProperty = {+ id: col.defId,definition: {id: col.defId,display_name: col.label,diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.tsindex 7db424ca42..506333c2cc 100644--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts@@ -1,5 +1,6 @@import {type Client,+ CombinedError,gql,makeOperation,type Operation,@@ -8,7 +9,11 @@ import {import { beforeEach, describe, expect, it, vi } from 'vitest';import { makeSubject, map, pipe, type Source, subscribe } from 'wonka';import type { CacheHost } from '../host/types';-import type { ReadResult, WriteResult } from '../protocol';+import type {+ OptimisticWriteResult,+ ReadResult,+ WriteResult,+} from '../protocol';import { normalizedCacheExchange } from './normalized-cache-exchange';const QUERY = gql`@@ -20,9 +25,20 @@ const QUERY = gql`}`;+const MUTATION = gql`+ mutation SetEntityProperty($input: SetEntityPropertyInput!) {+ setEntityProperty(input: $input) {+ id+ }+ }+`;+type FakeHost = CacheHost & {reads: Array<{ opKey?: number; query: string; variables?: object }>;writes: Array<{ opKey?: number; data: unknown; identity?: string }>;+ begins: Array<{ query: string; data: unknown }>;+ commits: Array<{ transactionId: string; query: string; data: unknown }>;+ rollbacks: string[];teardowns: number[];scriptRead: (result: ReadResult) => void;pushAffected: (opKeys: number[]) => void;@@ -35,6 +51,9 @@ function makeFakeHost(): FakeHost {clientId: 'test-client',reads: [],writes: [],+ begins: [],+ commits: [],+ rollbacks: [],teardowns: [],scriptRead: (r) => {readResult = r;@@ -58,6 +77,23 @@ function makeFakeHost(): FakeHost {});return { changed: [], affectedOps: [], reset: false };},+ async beginOptimisticWrite(args): Promise<OptimisticWriteResult> {+ host.begins.push({ query: args.query, data: args.data });+ return {+ transactionId: `txn-${host.begins.length}`,+ changed: [],+ affectedOps: [],+ reset: false,+ };+ },+ async commitOptimisticWrite(transactionId, args): Promise<WriteResult> {+ host.commits.push({ transactionId, query: args.query, data: args.data });+ return { changed: [], affectedOps: [], reset: false };+ },+ async rollbackOptimisticWrite(transactionId): Promise<WriteResult> {+ host.rollbacks.push(transactionId);+ return { changed: [], affectedOps: [], reset: false };+ },async invalidate() {return [];},@@ -93,8 +129,30 @@ function teardownOf(op: Operation): Operation {return makeOperation('teardown', op, op.context);}+/**+ * Builds a mutation operation, optionally carrying the optimistic response+ * in the private context slot `executeOptimisticMutation` uses.+ */+function makeMutationOp(key: number, optimisticResponse?: unknown): Operation {+ return makeOperation(+ 'mutation',+ { key, query: MUTATION, variables: { input: {} } },+ {+ requestPolicy: 'cache-first',+ url: 'http://test',+ suspense: false,+ ...(optimisticResponse === undefined+ ? {}+ : { normalizedCacheOptimistic: { optimisticResponse } }),+ } as never+ );+}+/** Runs the exchange over a manual operation stream. */-function harness(host: CacheHost) {+function harness(+ host: CacheHost,+ resultFor?: (op: Operation) => Partial<OperationResult>+) {const client = { reexecuteOperation: vi.fn() } as unknown as Client;const ops = makeSubject<Operation>();const forwarded: Operation[] = [];@@ -105,11 +163,15 @@ function harness(host: CacheHost) {forwarded.push(op);return {operation: op,- data: op.kind === 'query' ? { from: 'network' } : undefined,+ data:+ op.kind === 'query' || op.kind === 'mutation'+ ? { from: 'network' }+ : undefined,error: undefined,extensions: undefined,stale: false,hasNext: false,+ ...resultFor?.(op),};}));@@ -328,4 +390,127 @@ describe('normalizedCacheExchange', () => {host.pushAffected([7]);expect(vi.mocked(client.reexecuteOperation)).not.toHaveBeenCalled();});++ describe('mutations', () => {+ const optimistic = { setEntityProperty: { id: 'prop-1' } };++ it('installs the optimistic layer before forwarding to the network', async () => {+ const { ops, results, forwarded } = harness(host);+ const begin = host.beginOptimisticWrite.bind(host);+ host.beginOptimisticWrite = async (args) => {+ // The mutation must not have hit the network yet.+ expect(forwarded).toHaveLength(0);+ return begin(args);+ };+ ops.next(makeMutationOp(1, optimistic));+ await tick();++ expect(host.begins).toHaveLength(1);+ expect(host.begins[0]?.data).toEqual(optimistic);+ expect(forwarded.map((op) => op.kind)).toEqual(['mutation']);+ expect(results).toHaveLength(1);+ expect(results[0]?.data).toEqual({ from: 'network' });+ });++ it('commits with the network result on success and never emits a synthetic result', async () => {+ const { ops, results } = harness(host);+ ops.next(makeMutationOp(1, optimistic));+ await tick();++ expect(host.commits).toHaveLength(1);+ expect(host.commits[0]?.transactionId).toBe('txn-1');+ expect(host.commits[0]?.data).toEqual({ from: 'network' });+ expect(host.rollbacks).toHaveLength(0);+ // Only the real network result reaches the caller.+ expect(results).toHaveLength(1);+ expect(results[0]?.data).toEqual({ from: 'network' });+ // The optimistic path never uses the plain write-through.+ expect(host.writes).toHaveLength(0);+ });++ it('rolls back on a GraphQL error result', async () => {+ const error = new CombinedError({ graphQLErrors: ['nope'] });+ const { ops, results } = harness(host, (op) =>+ op.kind === 'mutation' ? { error } : {}+ );+ ops.next(makeMutationOp(1, optimistic));+ await tick();++ expect(host.rollbacks).toEqual(['txn-1']);+ expect(host.commits).toHaveLength(0);+ expect(results[0]?.error).toBe(error);+ });++ it('rolls back on a network error result', async () => {+ const error = new CombinedError({+ networkError: new Error('offline'),+ });+ const { ops } = harness(host, (op) =>+ op.kind === 'mutation' ? { error, data: undefined } : {}+ );+ ops.next(makeMutationOp(1, optimistic));+ await tick();++ expect(host.rollbacks).toEqual(['txn-1']);+ expect(host.commits).toHaveLength(0);+ });++ it('writes non-optimistic mutation responses through the standard path', async () => {+ const { ops, results, forwarded } = harness(host);+ ops.next(makeMutationOp(1));+ await tick();++ expect(host.begins).toHaveLength(0);+ expect(host.commits).toHaveLength(0);+ expect(forwarded.map((op) => op.kind)).toEqual(['mutation']);+ expect(host.writes).toHaveLength(1);+ expect(host.writes[0]?.data).toEqual({ from: 'network' });+ expect(results).toHaveLength(1);+ });++ it('degrades to a plain network mutation when the optimistic setup fails', async () => {+ host.beginOptimisticWrite = async () => {+ throw new Error('idb exploded');+ };+ const onCacheError = vi.fn();+ const client = { reexecuteOperation: vi.fn() } as unknown as Client;+ const ops = makeSubject<Operation>();+ const results: OperationResult[] = [];+ const forwarded: Operation[] = [];+ const forward = (ops$: Source<Operation>): Source<OperationResult> =>+ pipe(+ ops$,+ map((op) => {+ forwarded.push(op);+ return {+ operation: op,+ data: { from: 'network' },+ error: undefined,+ extensions: undefined,+ stale: false,+ hasNext: false,+ };+ })+ );+ pipe(+ normalizedCacheExchange(host, { onCacheError })({+ forward,+ client,+ dispatchDebug: () => undefined,+ })(ops.source),+ subscribe((r) => results.push(r))+ );+ ops.next(makeMutationOp(1, optimistic));+ await tick();++ expect(onCacheError).toHaveBeenCalledOnce();+ expect(forwarded.map((op) => op.kind)).toEqual(['mutation']);+ expect(results[0]?.data).toEqual({ from: 'network' });+ // No transaction was installed → nothing to commit or roll back, and+ // the response still write-throughs as a plain mutation.+ expect(host.commits).toHaveLength(0);+ expect(host.rollbacks).toHaveLength(0);+ expect(host.writes).toHaveLength(1);+ });+ });});diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.tsindex 7e4acd7b6a..d72d604395 100644--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts@@ -17,6 +17,16 @@* - `network-only`: skip read; response still written to cache.* - `cache-only`: hit → emit; miss → emit `data: undefined`, no network.*+ * Mutations:+ * - With an optimistic response (see `executeOptimisticMutation`): an+ * in-memory optimistic layer is installed *before* the mutation is+ * forwarded; dependent queries re-execute immediately. The layer commits+ * with the real response on success and rolls back on error. No synthetic+ * result is emitted — the caller's mutation promise resolves only with+ * the network result.+ * - Without one: forwarded normally; successful responses are normalized+ * through the standard write path so dependent cached queries update.+ ** Cache failures are never fatal: any host error degrades to the network.*/@@ -42,6 +52,15 @@ import {tap,} from 'wonka';import type { CacheHost } from '../host/types';+import { optimisticContextOf } from './optimistic';++/**+ * Private operation-context field carrying the optimistic transaction id+ * from forward time to result time. Lives on the operation (not keyed by+ * urql operation key): identical concurrent mutations share a key but each+ * carries its own transaction.+ */+const TRANSACTION_CONTEXT_KEY = 'normalizedCacheTransaction';const queryTextCache = new WeakMap<object, string>();@@ -158,6 +177,36 @@ export function normalizedCacheExchange(return undefined;}+ /**+ * Installs the optimistic layer (when the mutation carries one) and+ * only then releases the mutation to the network. Cache failures+ * degrade to a plain, non-optimistic network mutation.+ */+ async function prepareMutation(op: Operation): Promise<void> {+ const optimistic = optimisticContextOf(op);+ if (!optimistic) {+ enqueueForward(op);+ return;+ }+ try {+ const begin = await host.beginOptimisticWrite({+ query: queryText(op),+ operationName: operationName(op),+ variables: op.variables as Record<string, unknown> | undefined,+ data: optimistic.optimisticResponse,+ });+ enqueueForward(+ makeOperation(op.kind, op, {+ ...op.context,+ [TRANSACTION_CONTEXT_KEY]: begin.transactionId,+ })+ );+ } catch (error) {+ options.onCacheError?.(error, op);+ enqueueForward(op);+ }+ }+async function writeThrough(result: OperationResult): Promise<OperationResult> {@@ -175,6 +224,38 @@ export function normalizedCacheExchange(} catch (error) {options.onCacheError?.(error, op);}+ } else if (op.kind === 'mutation') {+ const transactionId: unknown = op.context[TRANSACTION_CONTEXT_KEY];+ try {+ if (typeof transactionId === 'string') {+ if (result.error || result.data == null) {+ await host.rollbackOptimisticWrite(transactionId);+ } else {+ // Atomic replace: dependents move straight from the+ // optimistic data to the real response, never flickering+ // back to the pre-mutation state.+ await host.commitOptimisticWrite(transactionId, {+ query: queryText(op),+ operationName: operationName(op),+ variables: op.variables as+ | Record<string, unknown>+ | undefined,+ data: result.data,+ });+ }+ } else if (result.data != null && !result.error) {+ // Plain mutation write-through: normalized entities update+ // dependent cached queries.+ await host.writeQuery({+ query: queryText(op),+ operationName: operationName(op),+ variables: op.variables as Record<string, unknown> | undefined,+ data: result.data,+ });+ }+ } catch (error) {+ options.onCacheError?.(error, op);+ }}return result;}@@ -193,9 +274,23 @@ export function normalizedCacheExchange(}));+ // Mutations are held until their optimistic layer (if any) is+ // installed, then re-injected through the forward queue. Emits+ // nothing itself — the network result is the only mutation emission.+ const mutationPrep$ = pipe(+ shared,+ filter((op) => op.kind === 'mutation'),+ mergeMap((op) =>+ pipe(+ fromPromise(prepareMutation(op)),+ mergeMap(() => empty as Source<OperationResult>)+ )+ )+ );+const passthrough$ = pipe(shared,- filter((op) => op.kind !== 'query'),+ filter((op) => op.kind !== 'query' && op.kind !== 'mutation'),tap((op) => {if (op.kind === 'teardown') {activeOps.delete(op.key);@@ -211,7 +306,7 @@ export function normalizedCacheExchange();void unsubscribePush;- return merge([cacheResults$, forwarded$]);+ return merge([cacheResults$, mutationPrep$, forwarded$]);};};}diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic.tsnew file mode 100644index 0000000000..65da90d878--- /dev/null+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts@@ -0,0 +1,71 @@+/**+ * Typed entry point for optimistic GraphQL mutations through the+ * normalized cache exchange.+ *+ * The optimistic response rides in a private urql operation-context slot;+ * the exchange installs it as an in-memory cache layer before the mutation+ * is forwarded to the network, commits the layer with the real response on+ * success, and rolls it back on error. Construction is strongly typed+ * against the generated operation (`TData` must exactly match the mutation+ * selection), while the exchange boundary reads the slot as `unknown`.+ */++import type { TypedDocumentNode } from '@graphql-typed-document-node/core';+import type {+ AnyVariables,+ Client,+ Operation,+ OperationResult,+ OperationResultSource,+} from '@urql/core';++/** Private operation-context field carrying the optimistic response. */+const OPTIMISTIC_MUTATION_CONTEXT_KEY = 'normalizedCacheOptimistic';++export type OptimisticMutationContext<TData = unknown> = {+ optimisticResponse: TData;+};++/**+ * Executes `document` as a mutation whose `optimisticData` is applied to+ * the normalized cache immediately. Dependent cached queries update right+ * away; the returned source still resolves only with the real network+ * result (never the optimistic one).+ *+ * On clients without the normalized cache exchange the context slot is+ * ignored and this behaves exactly like `client.mutation`.+ */+export function executeOptimisticMutation<+ TData,+ TVariables extends AnyVariables,+>(+ client: Client,+ document: TypedDocumentNode<TData, TVariables>,+ variables: TVariables,+ optimisticData: TData+): OperationResultSource<OperationResult<TData, TVariables>> {+ const context: OptimisticMutationContext<TData> = {+ optimisticResponse: optimisticData,+ };+ return client.mutation(document, variables, {+ [OPTIMISTIC_MUTATION_CONTEXT_KEY]: context,+ });+}++/**+ * Reads the optimistic context off an operation at the exchange boundary,+ * where the payload is necessarily `unknown`.+ */+export function optimisticContextOf(+ op: Operation+): OptimisticMutationContext | undefined {+ const value: unknown = op.context[OPTIMISTIC_MUTATION_CONTEXT_KEY];+ if (+ value !== null &&+ typeof value === 'object' &&+ 'optimisticResponse' in value+ ) {+ return value as OptimisticMutationContext;+ }+ return undefined;+}diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.tsindex 3fc7fc248a..627e1df72b 100644--- a/apps/web/src/lib/graphql-cache/host/types.ts+++ b/apps/web/src/lib/graphql-cache/host/types.ts@@ -5,7 +5,11 @@* - tauri-host.ts (Phase 3b): Tauri IPC to the native engine*/-import type { ReadResult, WriteResult } from '../protocol';+import type {+ OptimisticWriteResult,+ ReadResult,+ WriteResult,+} from '../protocol';export interface CacheReadArgs {/** urql operation key; registers the op for re-execution when set. */@@ -27,6 +31,23 @@ export interface CacheHost {readQuery(args: CacheReadArgs): Promise<ReadResult>;writeQuery(args: CacheWriteArgs): Promise<WriteResult>;+ /**+ * Installs an in-memory optimistic layer from a mutation's optimistic+ * response (`args.data`). Persists nothing; the returned transaction id+ * must be settled with `commitOptimisticWrite` or+ * `rollbackOptimisticWrite`.+ */+ beginOptimisticWrite(args: CacheWriteArgs): Promise<OptimisticWriteResult>;+ /**+ * Replaces a pending optimistic layer with the real network response+ * (`args.data`) atomically and flushes settled layers durably.+ */+ commitOptimisticWrite(+ transactionId: string,+ args: CacheWriteArgs+ ): Promise<WriteResult>;+ /** Drops a pending optimistic layer's contribution (mutation failed). */+ rollbackOptimisticWrite(transactionId: string): Promise<WriteResult>;/** Evict records by entity key (external/push updates); returns affected local op ids. */invalidate(keys: string[]): Promise<string[]>;/** urql teardown for an operation key. */diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.tsindex 5bf1cb9185..8f6a1ea9e7 100644--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts@@ -9,6 +9,7 @@ import {type CacheNotice,type CacheRequest,isCachePush,+ type OptimisticWriteResult,type ReadResult,type WorkerMessage,type WriteResult,@@ -161,6 +162,43 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {})) as WriteResult;},+ async beginOptimisticWrite(+ args: CacheWriteArgs+ ): Promise<OptimisticWriteResult> {+ await ready;+ return (await request({+ kind: 'begin-optimistic-write',+ originOpId: args.opKey === undefined ? undefined : opId(args.opKey),+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ data: args.data,+ })) as OptimisticWriteResult;+ },++ async commitOptimisticWrite(+ transactionId: string,+ args: CacheWriteArgs+ ): Promise<WriteResult> {+ await ready;+ return (await request({+ kind: 'commit-optimistic-write',+ transactionId,+ query: args.query,+ operationName: args.operationName,+ variables: args.variables,+ data: args.data,+ })) as WriteResult;+ },++ async rollbackOptimisticWrite(transactionId: string): Promise<WriteResult> {+ await ready;+ return (await request({+ kind: 'rollback-optimistic-write',+ transactionId,+ })) as WriteResult;+ },+async invalidate(keys: string[]): Promise<string[]> {await ready;return (await request({ kind: 'invalidate', keys })) as string[];diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.tsindex 76ae3d6c92..3f7da95a48 100644--- a/apps/web/src/lib/graphql-cache/index.ts+++ b/apps/web/src/lib/graphql-cache/index.ts@@ -3,6 +3,10 @@* Design doc: apps/web/docs/graphql-normalized-cache-plan.md*/+export {+ executeOptimisticMutation,+ type OptimisticMutationContext,+} from './exchange/optimistic';export type {CacheHost,CacheReadArgs,@@ -14,6 +18,7 @@ export type {CachePush,CacheRequest,CacheResponse,+ OptimisticWriteResult,ReadResult,WriteResult,} from './protocol';diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.tsindex 66a71eb55f..603d06292d 100644--- a/apps/web/src/lib/graphql-cache/protocol.ts+++ b/apps/web/src/lib/graphql-cache/protocol.ts@@ -29,6 +29,16 @@ export type WriteResult = {reset: boolean;};+/**+ * Result of installing an optimistic layer. `changed`/`affectedOps` reflect+ * *visible* (composed-view) changes — nothing is durable until the+ * transaction commits.+ */+export type OptimisticWriteResult = WriteResult & {+ /** Engine-assigned id; settle with commit/rollback-optimistic-write. */+ transactionId: string;+};+export type CacheRequest = { id: number } & (| { kind: 'init'; scope: string; hotCapacity?: number }| {@@ -52,6 +62,32 @@ export type CacheRequest = { id: number } & (*/identity?: string;}+ /**+ * Install an in-memory optimistic layer from a mutation's optimistic+ * response. Persists nothing; settle with commit/rollback.+ */+ | {+ kind: 'begin-optimistic-write';+ originOpId?: string;+ query: string;+ operationName?: string;+ variables?: Record<string, unknown>;+ data: unknown;+ }+ /**+ * Atomically replace a pending layer with the real network response and+ * flush contiguous settled layers durably.+ */+ | {+ kind: 'commit-optimistic-write';+ transactionId: string;+ query: string;+ operationName?: string;+ variables?: Record<string, unknown>;+ data: unknown;+ }+ /** Drop a pending layer's contribution (mutation failed). */+ | { kind: 'rollback-optimistic-write'; transactionId: string }| { kind: 'teardown'; opId: string }/** External invalidation (e.g. websocket push): evict + report ops. */| { kind: 'invalidate'; keys: string[] }diff --git a/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.ts b/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.tsnew file mode 100644index 0000000000..9078465289--- /dev/null+++ b/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.ts@@ -0,0 +1,118 @@+import type { Client, OperationResult } from '@urql/core';+import { createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it } from 'vitest';+import { makeSubject } from 'wonka';+import { createQuerySignal, type QuerySignal } from './create-query-signal';++type FakeResult = Partial<OperationResult>;++/**+ * Fake urql client: each `query()` call returns a fresh subject the test+ * pushes results into, mimicking the long-lived sources the normalized+ * cache exchange re-emits on.+ */+function makeFakeClient() {+ const executions: Array<{+ variables: unknown;+ next: (result: FakeResult) => void;+ }> = [];+ const client = {+ query: (_document: unknown, variables: unknown) => {+ const subject = makeSubject<FakeResult>();+ executions.push({ variables, next: subject.next });+ return subject.source;+ },+ } as unknown as Client;+ return { client, executions };+}++const DOCUMENT = {} as never;++type Variables = { cursor: string | null };++// Note: signal writes and result pushes must happen OUTSIDE the createRoot+// body — solid batches the body, deferring effect re-runs until it returns.+function setup() {+ const { client, executions } = makeFakeClient();+ let query!: QuerySignal<unknown>;+ let setVariables!: (v: Variables | undefined) => void;+ const dispose = createRoot((dispose) => {+ const [variables, setVars] = createSignal<Variables | undefined>({+ cursor: null,+ });+ setVariables = setVars;+ query = createQuerySignal({+ client: () => client,+ document: DOCUMENT,+ variables,+ });+ return dispose;+ });+ return { executions, query, setVariables, dispose };+}++let dispose: (() => void) | undefined;+afterEach(() => {+ dispose?.();+ dispose = undefined;+});++describe('createQuerySignal', () => {+ it('tracks results pushed over the operation lifetime', () => {+ const harness = setup();+ dispose = harness.dispose;+ const { query, executions } = harness;++ expect(query.fetching()).toBe(true);+ expect(query.data()).toBeUndefined();+ expect(executions).toHaveLength(1);++ // Stale cache hit first…+ executions[0]?.next({ data: { from: 'cache' }, stale: true });+ expect(query.data()).toEqual({ from: 'cache' });+ expect(query.stale()).toBe(true);+ expect(query.fetching()).toBe(false);++ // …then the network result, then a cache-pushed re-execution.+ executions[0]?.next({ data: { from: 'network' }, stale: false });+ expect(query.data()).toEqual({ from: 'network' });+ executions[0]?.next({ data: { from: 'optimistic' }, stale: false });+ expect(query.data()).toEqual({ from: 'optimistic' });+ });++ it('resubscribes when variables change and ignores the old source', () => {+ const harness = setup();+ dispose = harness.dispose;+ const { query, executions, setVariables } = harness;++ executions[0]?.next({ data: { page: 1 } });+ expect(query.data()).toEqual({ page: 1 });++ setVariables({ cursor: 'next' });+ expect(query.fetching()).toBe(true);+ expect(executions).toHaveLength(2);+ expect(executions[1]?.variables).toEqual({ cursor: 'next' });++ // The unsubscribed first execution must not clobber the signal.+ executions[0]?.next({ data: { page: 'stale-old' } });+ expect(query.data()).toEqual({ page: 1 });+ executions[1]?.next({ data: { page: 2 } });+ expect(query.data()).toEqual({ page: 2 });+ });++ it('pauses on undefined variables, keeping the last data', () => {+ const harness = setup();+ dispose = harness.dispose;+ const { query, executions, setVariables } = harness;++ executions[0]?.next({ data: { page: 1 } });+ setVariables(undefined);+ expect(query.fetching()).toBe(false);+ expect(query.data()).toEqual({ page: 1 });+ expect(executions).toHaveLength(1);++ // Old subscription is torn down: late results are ignored.+ executions[0]?.next({ data: { page: 'late' } });+ expect(query.data()).toEqual({ page: 1 });+ });+});diff --git a/apps/web/src/lib/graphql-cache/solid/create-query-signal.ts b/apps/web/src/lib/graphql-cache/solid/create-query-signal.tsnew file mode 100644index 0000000000..4a4f815490--- /dev/null+++ b/apps/web/src/lib/graphql-cache/solid/create-query-signal.ts@@ -0,0 +1,90 @@+/**+ * Minimal Solid binding over a urql query: signals that track the latest+ * operation result for as long as the owner scope lives.+ *+ * Unlike an imperative `.toPromise()` call, the underlying source stays+ * subscribed, so results *pushed* by the normalized cache exchange+ * (optimistic mutations, sibling writes, other tabs) re-render consumers+ * immediately — this is the primitive that lets UI flow through urql+ * instead of TanStack invalidation.+ *+ * Deliberately kept out of `@graphql-cache/index`: it depends on solid-js,+ * which the transport-level consumers of that barrel must not pull in.+ */++import type { TypedDocumentNode } from '@graphql-typed-document-node/core';+import type {+ AnyVariables,+ Client,+ CombinedError,+ RequestPolicy,+} from '@urql/core';+import {+ type Accessor,+ batch,+ createRenderEffect,+ createSignal,+ onCleanup,+ untrack,+} from 'solid-js';+import { pipe, subscribe } from 'wonka';++export type QuerySignal<TData> = {+ /** Latest result data; retains the previous value across re-executions. */+ data: Accessor<TData | undefined>;+ error: Accessor<CombinedError | undefined>;+ /** True from (re)subscription until the first result arrives. */+ fetching: Accessor<boolean>;+ /** True while the emitted result is a stale cache hit being revalidated. */+ stale: Accessor<boolean>;+};++export type CreateQuerySignalOptions<TData, TVariables extends AnyVariables> = {+ client: Accessor<Client>;+ document: TypedDocumentNode<TData, TVariables>;+ /**+ * Reactive variables; `undefined` pauses the query (unsubscribes and+ * reports `fetching: false` while keeping the last data).+ */+ variables: Accessor<TVariables | undefined>;+ requestPolicy?: RequestPolicy;+};++export function createQuerySignal<TData, TVariables extends AnyVariables>(+ options: CreateQuerySignalOptions<TData, TVariables>+): QuerySignal<TData> {+ const [data, setData] = createSignal<TData | undefined>(undefined);+ const [error, setError] = createSignal<CombinedError | undefined>(undefined);+ const [fetching, setFetching] = createSignal(false);+ const [stale, setStale] = createSignal(false);++ // Render effect: subscribes synchronously so consumers created in the+ // same reactive scope observe `fetching` immediately.+ createRenderEffect(() => {+ const variables = options.variables();+ if (variables === undefined) {+ setFetching(false);+ return;+ }+ const client = options.client();+ setFetching(true);+ const subscription = untrack(() =>+ pipe(+ client.query(options.document, variables, {+ requestPolicy: options.requestPolicy,+ }),+ subscribe((result) => {+ batch(() => {+ setData(() => result.data);+ setError(result.error);+ setStale(result.stale);+ setFetching(false);+ });+ })+ )+ );+ onCleanup(subscription.unsubscribe);+ });++ return { data, error, fetching, stale };+}diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.tsindex 5e5396e2e4..54633c40a9 100644--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts@@ -8,7 +8,11 @@* src/lib/graphql-cache/wasm/ (gitignored).*/-import type { ReadResult, WriteResult } from '../protocol';+import type {+ OptimisticWriteResult,+ ReadResult,+ WriteResult,+} from '../protocol';export interface CacheEngine {readQuery(@@ -25,6 +29,21 @@ export interface CacheEngine {data: unknown,identity: string | undefined): Promise<WriteResult>;+ beginOptimisticWrite(+ originOpId: string | undefined,+ query: string,+ operationName: string | undefined,+ variables: Record<string, unknown> | undefined,+ data: unknown+ ): Promise<OptimisticWriteResult>;+ commitOptimisticWrite(+ transactionId: string,+ query: string,+ operationName: string | undefined,+ variables: Record<string, unknown> | undefined,+ data: unknown+ ): Promise<WriteResult>;+ rollbackOptimisticWrite(transactionId: string): Promise<WriteResult>;invalidateKeys(keys: string[]): Promise<string[]>;externalReset(): Promise<string[]>;teardownOperation(opId: string): Promise<void>;diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.tsindex 9910680a70..14ff9bed16 100644--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts@@ -13,6 +13,7 @@ import {type CachePush,type CacheRequest,type CacheResponse,+ type OptimisticWriteResult,type ReadResult,type WriteResult,writeLockName,@@ -89,19 +90,58 @@ export class CacheWorkerCore {}case 'write': {const engine = this.requireEngine();- const write = async (): Promise<WriteResult> =>- await engine.writeQuery(- request.originOpId,- request.query,- request.operationName,- request.variables,- request.data,- request.identity- );- const result =- this.options.multiEngine && this.scope- ? await navigator.locks.request(writeLockName(this.scope), write)- : await write();+ const result = await this.durableWrite(+ async () =>+ await engine.writeQuery(+ request.originOpId,+ request.query,+ request.operationName,+ request.variables,+ request.data,+ request.identity+ )+ );+ this.fanOut(result);+ return result;+ }+ case 'begin-optimistic-write': {+ const engine = this.requireEngine();+ // Memory-only: no write lock needed, and never broadcast — the+ // layer is local to this engine (per tab in the fallback topology;+ // shared by all attached clients under a SharedWorker).+ const result: OptimisticWriteResult = await engine.beginOptimisticWrite(+ request.originOpId,+ request.query,+ request.operationName,+ request.variables,+ request.data+ );+ this.fanOut(result, { broadcast: false });+ return result;+ }+ case 'commit-optimistic-write': {+ const engine = this.requireEngine();+ // Committing can flush settled layers into durable storage.+ const result = await this.durableWrite(+ async () =>+ await engine.commitOptimisticWrite(+ request.transactionId,+ request.query,+ request.operationName,+ request.variables,+ request.data+ )+ );+ this.fanOut(result);+ return result;+ }+ case 'rollback-optimistic-write': {+ const engine = this.requireEngine();+ // Rolling back can unblock a settled suffix and flush it durably.+ const result = await this.durableWrite(+ async () =>+ await engine.rollbackOptimisticWrite(request.transactionId)+ );this.fanOut(result);return result;}@@ -169,9 +209,22 @@ export class CacheWorkerCore {this.push({ kind: 'ops-affected', opIds: affectedOps, keys: msg.keys });}- /** After a local change: notify connected clients + other tabs. */- private fanOut(result: WriteResult): void {- if (result.changed.length === 0 && !result.reset) return;+ /**+ * Runs a durable engine write, serialized via Web Locks in the+ * multi-engine (dedicated worker per tab) topology.+ */+ private async durableWrite<T>(write: () => Promise<T>): Promise<T> {+ return this.options.multiEngine && this.scope+ ? await navigator.locks.request(writeLockName(this.scope), write)+ : await write();+ }++ /**+ * After a local change: notify connected clients + other tabs. Optimistic+ * begins pass `broadcast: false` — their changes are visible only through+ * this engine, so other instances must not be told to invalidate.+ */+ private fanOut(result: WriteResult, opts?: { broadcast?: boolean }): void {if (result.affectedOps.length > 0) {this.push({kind: 'ops-affected',@@ -179,7 +232,12 @@ export class CacheWorkerCore {keys: result.changed,});}- if (this.options.multiEngine && this.broadcast) {+ if (+ opts?.broadcast !== false &&+ this.options.multiEngine &&+ this.broadcast &&+ (result.changed.length > 0 || result.reset)+ ) {const msg: CacheBroadcast = result.reset? { kind: 'reset', source: this.workerId }: { kind: 'changed', keys: result.changed, source: this.workerId };diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.tsindex 5bc4d64dbc..348b6862f5 100644--- a/apps/web/src/lib/queries/properties/entity.ts+++ b/apps/web/src/lib/queries/properties/entity.ts@@ -18,6 +18,7 @@ import { propertiesServiceClient } from '../../service-clients/service-propertieimport type { EntityType } from '../../service-clients/service-properties/generated/schemas/entityType';import type { SoupProperty } from '../../service-clients/service-storage/generated/schemas/soupProperty';import type { SoupPropertyValue } from '../../service-clients/service-storage/generated/schemas/soupPropertyValue';+import { setEntityProperty } from '../../service-clients/service-storage/graphql-properties';import { queryClient } from '../client';import {getSoupEntityById,@@ -26,6 +27,7 @@ import {type SoupTransaction,} from '../soup/cache';import { type MutationCallbacks, withCallbacks } from '../utils';+import { buildOptimisticSetEntityProperty } from './graphql-optimistic';import { propertiesKeys } from './keys';export function useEntityPropertiesQuery(@@ -152,6 +154,7 @@ function buildSoupProperty(const now = new Date().toISOString();const instantiated = isInstantiatedProperty(property);return {+ id: instantiated ? property.propertyId : property.id,definition: {id: getPropertyDefinitionId(property),display_name: property.displayName,@@ -261,17 +264,14 @@ export function useAddEntityPropertyMutation() {return useMutation(() => ({mutationFn: async (vars: AddEntityPropertyParams) => {- await throwOnErr(- async () =>- await propertiesServiceClient.setEntityProperty({- entity_type: vars.entityType,- entity_id: vars.entityId,- property_id: vars.propertyDefinitionId,- body: {- value: null,- },- })- );+ // New attachments have no assignment id until the server responds, so+ // this write is never optimistic; onSettled invalidation refetches.+ await setEntityProperty({+ entityType: vars.entityType,+ entityId: vars.entityId,+ propertyDefinitionId: vars.propertyDefinitionId,+ value: null,+ });},...withCallbacks<void, Error, AddEntityPropertyParams>({@@ -493,17 +493,20 @@ export function useBulkSaveEntityPropertiesMutation(item.property.isMultiSelect);- return throwOnErr(- async () =>- await propertiesServiceClient.setEntityProperty({- entity_type: item.entityType,- entity_id: item.entityId,- property_id: getPropertyDefinitionId(item.property),- body: {- value: propertyValue,- },- })- );+ return setEntityProperty({+ entityType: item.entityType,+ entityId: item.entityId,+ propertyDefinitionId: getPropertyDefinitionId(item.property),+ value: propertyValue,+ // GraphQL path only: updates the normalized property record+ // referenced by soup query results. The TanStack optimistic+ // transaction below stays until soup consumers move to+ // reactive urql queries.+ optimisticProperty: buildOptimisticSetEntityProperty(+ item.property,+ item.apiValues+ ),+ });}));},diff --git a/apps/web/src/lib/queries/properties/graphql-optimistic.test.ts b/apps/web/src/lib/queries/properties/graphql-optimistic.test.tsnew file mode 100644index 0000000000..3a60951a9b--- /dev/null+++ b/apps/web/src/lib/queries/properties/graphql-optimistic.test.ts@@ -0,0 +1,182 @@+import type {+ Property,+ PropertyApiValues,+ PropertyDefinitionDomain,+} from '@property/types';+import { describe, expect, it } from 'vitest';+import {+ apiValuesToGraphqlPropertyValue,+ buildOptimisticSetEntityProperty,+} from './graphql-optimistic';++const emptyLists = {+ boolValue: null,+ numberValue: null,+ stringValue: null,+ dateValue: null,+ selectOptionIds: [],+ entityReferences: [],+ links: [],+};++describe('apiValuesToGraphqlPropertyValue', () => {+ it('converts each populated variant', () => {+ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'STRING', value: 'hi' })+ ).toEqual({ ...emptyLists, kind: 'String', stringValue: 'hi' });++ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'NUMBER', value: 3 })+ ).toEqual({ ...emptyLists, kind: 'Number', numberValue: 3 });++ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'BOOLEAN', value: false })+ ).toEqual({ ...emptyLists, kind: 'Boolean', boolValue: false });++ expect(+ apiValuesToGraphqlPropertyValue({+ valueType: 'DATE',+ value: new Date('2026-07-10T00:00:00.000Z'),+ })+ ).toEqual({+ ...emptyLists,+ kind: 'Date',+ dateValue: '2026-07-10T00:00:00.000Z',+ });++ // Single- and multi-select share the SelectOption shape.+ expect(+ apiValuesToGraphqlPropertyValue({+ valueType: 'SELECT_STRING',+ values: ['opt-1'],+ })+ ).toEqual({+ ...emptyLists,+ kind: 'SelectOption',+ selectOptionIds: ['opt-1'],+ });+ expect(+ apiValuesToGraphqlPropertyValue({+ valueType: 'SELECT_NUMBER',+ values: ['opt-1', 'opt-2'],+ })+ ).toEqual({+ ...emptyLists,+ kind: 'SelectOption',+ selectOptionIds: ['opt-1', 'opt-2'],+ });++ expect(+ apiValuesToGraphqlPropertyValue({+ valueType: 'ENTITY',+ refs: [+ {+ entity_id: 'doc-1',+ entity_type: 'DOCUMENT',+ specific_message_id: 'msg-1',+ },+ { entity_id: 'user-1', entity_type: 'USER' },+ ],+ })+ ).toEqual({+ ...emptyLists,+ kind: 'EntityReference',+ entityReferences: [+ {+ entityId: 'doc-1',+ entityType: 'DOCUMENT',+ specificMessageId: 'msg-1',+ },+ { entityId: 'user-1', entityType: 'USER', specificMessageId: null },+ ],+ });++ expect(+ apiValuesToGraphqlPropertyValue({+ valueType: 'LINK',+ values: ['https://a'],+ })+ ).toEqual({ ...emptyLists, kind: 'Link', links: ['https://a'] });+ });++ it('maps empty variants to null (clearing the value)', () => {+ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'STRING', value: null })+ ).toBeNull();+ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'DATE', value: null })+ ).toBeNull();+ expect(+ apiValuesToGraphqlPropertyValue({+ valueType: 'SELECT_STRING',+ values: [],+ })+ ).toBeNull();+ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'ENTITY', refs: null })+ ).toBeNull();+ expect(+ apiValuesToGraphqlPropertyValue({ valueType: 'LINK', values: null })+ ).toBeNull();+ });+});++describe('buildOptimisticSetEntityProperty', () => {+ const instantiated: Property = {+ propertyId: 'prop-1',+ propertyDefinitionId: 'def-1',+ displayName: 'Status',+ isMultiSelect: false,+ isMetadata: false,+ isSystemProperty: true,+ owner: { scope: 'system' } as never,+ specificEntityType: 'DOCUMENT',+ createdAt: '' as never,+ updatedAt: '' as never,+ valueType: 'SELECT_STRING',+ value: null,+ };++ const definitionOnly: PropertyDefinitionDomain = {+ id: 'def-1',+ displayName: 'Status',+ valueType: 'SELECT_STRING',+ isMultiSelect: false,+ isMetadata: false,+ isSystem: true,+ owner: { scope: 'system' } as never,+ createdAt: '' as never,+ updatedAt: '' as never,+ };++ it('builds a complete payload for an existing assignment', () => {+ const apiValues: PropertyApiValues = {+ valueType: 'SELECT_STRING',+ values: ['opt-done'],+ };+ expect(buildOptimisticSetEntityProperty(instantiated, apiValues)).toEqual({+ id: 'prop-1',+ propertyDefinitionId: 'def-1',+ displayName: 'Status',+ dataType: 'SELECT_STRING',+ isMultiSelect: false,+ specificEntityType: 'DOCUMENT',+ isSystem: true,+ isMetadata: false,+ value: {+ ...emptyLists,+ kind: 'SelectOption',+ selectOptionIds: ['opt-done'],+ },+ });+ });++ it('skips optimism for uninstantiated definitions (no stable id)', () => {+ expect(+ buildOptimisticSetEntityProperty(definitionOnly, {+ valueType: 'SELECT_STRING',+ values: ['opt-done'],+ })+ ).toBeUndefined();+ });+});diff --git a/apps/web/src/lib/queries/properties/graphql-optimistic.ts b/apps/web/src/lib/queries/properties/graphql-optimistic.tsnew file mode 100644index 0000000000..bbb666050f--- /dev/null+++ b/apps/web/src/lib/queries/properties/graphql-optimistic.ts@@ -0,0 +1,127 @@+/**+ * Builders for optimistic `setEntityProperty` GraphQL responses. The+ * optimistic payload must exactly match the mutation selection+ * (`SoupPropertyFields`) so the normalized cache can apply it to the same+ * property record referenced by soup query results.+ */++import type {+ Property,+ PropertyApiValues,+ PropertyDefinitionDomain,+} from '@property/types';+// The concrete module (not the `@property/utils` barrel): the barrel pulls+// in UI/side-effect imports that break in non-browser test environments.+import { isInstantiatedProperty } from '@property/utils/typeGuards';+import type { SoupPropertyFieldsFragment } from '../../service-clients/service-storage/graphql/generated/graphql';++type GraphqlPropertyValue = NonNullable<SoupPropertyFieldsFragment['value']>;++/**+ * The GraphQL value object has non-null list fields and nullable scalars;+ * every variant starts from this empty shape and fills in its own field.+ */+const EMPTY_VALUE_FIELDS: Omit<GraphqlPropertyValue, 'kind'> = {+ boolValue: null,+ numberValue: null,+ stringValue: null,+ dateValue: null,+ selectOptionIds: [],+ entityReferences: [],+ links: [],+};++/**+ * `PropertyApiValues` → the GraphQL property value as the server would+ * return it. `null` mirrors the REST behavior of clearing the value when+ * the variant carries nothing.+ */+export function apiValuesToGraphqlPropertyValue(+ apiValues: PropertyApiValues+): GraphqlPropertyValue | null {+ switch (apiValues.valueType) {+ case 'STRING':+ return apiValues.value != null+ ? {+ ...EMPTY_VALUE_FIELDS,+ kind: 'String',+ stringValue: apiValues.value,+ }+ : null;+ case 'NUMBER':+ return apiValues.value != null+ ? {+ ...EMPTY_VALUE_FIELDS,+ kind: 'Number',+ numberValue: apiValues.value,+ }+ : null;+ case 'BOOLEAN':+ return apiValues.value != null+ ? { ...EMPTY_VALUE_FIELDS, kind: 'Boolean', boolValue: apiValues.value }+ : null;+ case 'DATE':+ return apiValues.value != null+ ? {+ ...EMPTY_VALUE_FIELDS,+ kind: 'Date',+ dateValue: apiValues.value.toISOString(),+ }+ : null;+ case 'SELECT_STRING':+ case 'SELECT_NUMBER':+ return apiValues.values != null && apiValues.values.length > 0+ ? {+ ...EMPTY_VALUE_FIELDS,+ kind: 'SelectOption',+ selectOptionIds: apiValues.values,+ }+ : null;+ case 'ENTITY':+ return apiValues.refs != null && apiValues.refs.length > 0+ ? {+ ...EMPTY_VALUE_FIELDS,+ kind: 'EntityReference',+ entityReferences: apiValues.refs.map((ref) => ({+ entityId: ref.entity_id,+ entityType: ref.entity_type,+ specificMessageId: ref.specific_message_id ?? null,+ })),+ }+ : null;+ case 'LINK':+ return apiValues.values != null && apiValues.values.length > 0+ ? { ...EMPTY_VALUE_FIELDS, kind: 'Link', links: apiValues.values }+ : null;+ default: {+ const exhaustiveCheck: never = apiValues;+ throw new Error(+ `Unsupported value type: ${(exhaustiveCheck as { valueType: string }).valueType}`+ );+ }+ }+}++/**+ * Complete optimistic mutation payload for an existing property+ * assignment, or `undefined` when none can be built safely:+ * uninstantiated definitions have no assignment id until the server+ * responds, and inventing one would corrupt the normalized cache.+ */+export function buildOptimisticSetEntityProperty(+ property: Property | PropertyDefinitionDomain,+ apiValues: PropertyApiValues+): SoupPropertyFieldsFragment | undefined {+ if (!isInstantiatedProperty(property)) return undefined;+ return {+ id: property.propertyId,+ propertyDefinitionId: property.propertyDefinitionId,+ displayName: property.displayName,+ dataType: property.valueType,+ isMultiSelect: property.isMultiSelect,+ specificEntityType: property.specificEntityType ?? null,+ isSystem: property.isSystemProperty ?? false,+ isMetadata: property.isMetadata ?? false,+ value: apiValuesToGraphqlPropertyValue(apiValues),+ };+}diff --git a/apps/web/src/lib/queries/soup/graphql-ast.test.ts b/apps/web/src/lib/queries/soup/graphql-ast.test.tsindex 96c7cef67a..76ad4ed55c 100644--- a/apps/web/src/lib/queries/soup/graphql-ast.test.ts+++ b/apps/web/src/lib/queries/soup/graphql-ast.test.ts@@ -65,6 +65,17 @@ describe('makeGraphqlSoupInput', () => {});});+ it('maps channel thread participant filters', () => {+ const input = makeGraphqlSoupInput({+ params: { limit: 100, sort_method: 'updated_at' },+ body: { cthf: { l: { Participant: 'user-1' } } } as never,+ });++ expect(input.filters?.channelThreadFilter).toEqual({+ literal: { participant: 'user-1' },+ });+ });+it('throws for REST-only file association literals so callers can fall back', () => {expect(() =>makeInput({diff --git a/apps/web/src/lib/queries/soup/graphql-ast.ts b/apps/web/src/lib/queries/soup/graphql-ast.tsindex 245767b733..84bf5f18d7 100644--- a/apps/web/src/lib/queries/soup/graphql-ast.ts+++ b/apps/web/src/lib/queries/soup/graphql-ast.ts@@ -15,6 +15,7 @@ import type {GraphqlPropertiesLiteral as GraphqlPropertiesLiteralInput,SoupInput as GraphqlSoupInput,} from '@service-storage/graphql/generated/graphql';+import { match } from 'ts-pattern';type GraphqlExprInput<TLiteral> =| {@@ -324,25 +325,57 @@ function mapChannelLiteral(literal: unknown): GraphqlChannelLiteralInput {}}+type ChannelThreadLiteralField =+ | 'ThreadId'+ | 'ChannelId'+ | 'RootSender'+ | 'Sender'+ | 'Participant'+ | 'NotificationDone'+ | 'NotificationSeen';++const CHANNEL_THREAD_LITERAL_FIELDS = [+ 'ThreadId',+ 'ChannelId',+ 'RootSender',+ 'Sender',+ 'Participant',+ 'NotificationDone',+ 'NotificationSeen',+] as const satisfies readonly ChannelThreadLiteralField[];++function isChannelThreadLiteralField(+ field: string+): field is ChannelThreadLiteralField {+ return CHANNEL_THREAD_LITERAL_FIELDS.includes(+ field as ChannelThreadLiteralField+ );+}+function mapChannelThreadLiteral(literal: unknown): GraphqlChannelThreadLiteralInput {const [field, value] = singleLiteralField(literal);- switch (field) {- case 'ThreadId':- return { threadId: mapString(value, 'threadId') };- case 'ChannelId':- return { channelId: mapString(value, 'channelId') };- case 'RootSender':- case 'Sender':- return { rootSender: mapString(value, 'rootSender') };- case 'NotificationDone':- return { notificationDone: mapBoolean(value, 'notificationDone') };- case 'NotificationSeen':- return { notificationSeen: mapBoolean(value, 'notificationSeen') };- default:- unsupported(`channel thread literal ${field}`);+ if (!isChannelThreadLiteralField(field)) {+ unsupported(`channel thread literal ${field}`);}++ return match(field)+ .with('ThreadId', () => ({ threadId: mapString(value, 'threadId') }))+ .with('ChannelId', () => ({ channelId: mapString(value, 'channelId') }))+ .with('RootSender', 'Sender', () => ({+ rootSender: mapString(value, 'rootSender'),+ }))+ .with('Participant', () => ({+ participant: mapString(value, 'participant'),+ }))+ .with('NotificationDone', () => ({+ notificationDone: mapBoolean(value, 'notificationDone'),+ }))+ .with('NotificationSeen', () => ({+ notificationSeen: mapBoolean(value, 'notificationSeen'),+ }))+ .exhaustive();}function mapCallLiteral(literal: unknown): GraphqlCallLiteralInput {diff --git a/apps/web/src/lib/queries/soup/reactive-items.ts b/apps/web/src/lib/queries/soup/reactive-items.tsnew file mode 100644index 0000000000..12f486e67f--- /dev/null+++ b/apps/web/src/lib/queries/soup/reactive-items.ts@@ -0,0 +1,167 @@+/**+ * Reactive urql-backed soup items: the flagged alternative to the TanStack+ * `useSoupAstItemsQuery` path. Each page holds a live subscription to the+ * GraphQL Soup query, so results pushed by the normalized cache exchange+ * (optimistic property mutations, sibling writes, other tabs) re-render+ * the soup list directly — no TanStack invalidation round-trip.+ *+ * Scope matches the GraphQL transport: flat (non-grouped) views whose+ * filter AST has a GraphQL translation. Consumers check `isSupported`+ * and fall back to the TanStack path otherwise.+ */++import { createQuerySignal } from '@graphql-cache/solid/create-query-signal';+import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';+import {+ SoupDocument,+ type SoupQuery,+ type SoupQueryVariables,+} from '@service-storage/graphql/generated/graphql';+import type { GraphqlSoupInput } from '@service-storage/graphql-soup';+import {+ getGraphqlSoupClient,+ mapGraphqlSoupPage,+} from '@service-storage/graphql-soup';+import {+ type Accessor,+ createComputed,+ createMemo,+ createSignal,+ mapArray,+ on,+} from 'solid-js';+import { makeGraphqlSoupInput } from './graphql-ast';+import type { SoupAstBody, SoupAstItemsData, SoupAstParams } from './items';+import { mapSoupPageToEntityList } from './transform-utils';++export type ReactiveSoupAstItemsQueryArgs = {+ params: SoupAstParams;+ body: SoupAstBody;+};++export type ReactiveSoupAstItemsQueryOptions = {+ enabled: boolean;+ showSupportedForeignEntities?: boolean;+};++export type ReactiveSoupAstItemsQuery = {+ data: Accessor<SoupAstItemsData | undefined>;+ /** False when the filter AST has no GraphQL translation. */+ isSupported: Accessor<boolean>;+ isLoading: Accessor<boolean>;+ isFetching: Accessor<boolean>;+ isFetchingNextPage: Accessor<boolean>;+ hasNextPage: Accessor<boolean>;+ fetchNextPage: () => void;+ /** Drops all but the first page (filter changes, pull-to-refresh). */+ trimToFirstPage: () => void;+ /** Trims to the first page and refetches it from the network. */+ refresh: () => Promise<void>;+};++export function useReactiveSoupAstItemsQuery(+ args: Accessor<ReactiveSoupAstItemsQueryArgs>,+ options: Accessor<ReactiveSoupAstItemsQueryOptions>+): ReactiveSoupAstItemsQuery {+ const instructionsIdQuery = useInstructionsMdIdQuery();++ const inputForCursor = (+ cursor: string | null+ ): GraphqlSoupInput | undefined => {+ const { params, body } = args();+ try {+ return makeGraphqlSoupInput({ params, body, cursor });+ } catch {+ // Unsupported GraphQL Soup AST — consumers fall back to TanStack.+ return undefined;+ }+ };++ const firstPageInput = createMemo(() => inputForCursor(null));+ const isSupported = () => firstPageInput() !== undefined;++ // Cursors of the pages currently shown. Structural key: the input memo+ // yields a fresh object per read, so compare serialized form to avoid+ // resetting pagination on every unrelated reactive tick.+ const inputKey = createMemo(() => {+ const input = firstPageInput();+ return input === undefined ? undefined : JSON.stringify(input);+ });+ const [cursors, setCursors] = createSignal<(string | null)[]>([null]);+ createComputed(on(inputKey, () => setCursors([null]), { defer: true }));++ const pages = mapArray(cursors, (cursor) => {+ const query = createQuerySignal<SoupQuery, SoupQueryVariables>({+ client: getGraphqlSoupClient,+ document: SoupDocument,+ // Serve the cached page instantly, revalidate over the network, and+ // keep receiving cache-pushed re-executions for the page's lifetime.+ requestPolicy: 'cache-and-network',+ variables: () => {+ if (!options().enabled) return undefined;+ const input = inputForCursor(cursor);+ return input === undefined ? undefined : { input };+ },+ });+ const page = createMemo(() => {+ const data = query.data();+ return data === undefined ? undefined : mapGraphqlSoupPage(data);+ });+ return { query, page };+ });++ const lastPage = () => pages().at(-1);++ const data = createMemo<SoupAstItemsData | undefined>(() => {+ const list = pages();+ if (list[0]?.page() === undefined) return undefined;+ const entities = list.flatMap((entry) => {+ const page = entry.page();+ if (!page) return [];+ return mapSoupPageToEntityList(page, {+ instructionsIdQuery,+ showSupportedForeignEntities: options().showSupportedForeignEntities,+ });+ });+ return { entities, groups: undefined };+ });++ const isFetching = () =>+ pages().some((entry) => entry.query.fetching() || entry.query.stale());++ return {+ data,+ isSupported,+ isLoading: () => data() === undefined && isFetching(),+ isFetching,+ isFetchingNextPage: () => {+ const last = lastPage();+ return (+ cursors().length > 1 &&+ last !== undefined &&+ last.page() === undefined &&+ last.query.fetching()+ );+ },+ hasNextPage: () => lastPage()?.page()?.next_cursor != null,+ fetchNextPage: () => {+ const next = lastPage()?.page()?.next_cursor;+ if (next == null || cursors().includes(next)) return;+ setCursors((prev) => [...prev, next]);+ },+ trimToFirstPage: () => {+ setCursors((prev) => (prev.length > 1 ? [prev[0] ?? null] : prev));+ },+ refresh: async () => {+ setCursors((prev) => (prev.length > 1 ? [prev[0] ?? null] : prev));+ const input = firstPageInput();+ if (input === undefined) return;+ // Shares the operation key with the page subscription: the fresh+ // network result is broadcast to it, updating the UI.+ const result = await getGraphqlSoupClient()+ .query(SoupDocument, { input }, { requestPolicy: 'network-only' })+ .toPromise();+ if (result.error) throw result.error;+ },+ };+}diff --git a/apps/web/src/lib/service-clients/service-properties/client.ts b/apps/web/src/lib/service-clients/service-properties/client.tsindex 9de9b4ec05..cdf3e71ce0 100644--- a/apps/web/src/lib/service-clients/service-properties/client.ts+++ b/apps/web/src/lib/service-clients/service-properties/client.ts@@ -63,10 +63,6 @@ type DeletePropertyOptionArgs = {definition_id: string;option_id: string;};-type SetPropertyStatusCompleteArgs = {- entity_type: PropertiesEntityType;- entity_id: string;-};type GetBulkEntityPropertiesArgs = {body: BulkEntityPropertiesRequest;};@@ -221,14 +217,6 @@ export const propertiesServiceClient = {return result.map(() => ({ success: true }));},- setPropertyStatusComplete: async (args: SetPropertyStatusCompleteArgs) => {- const url = `/properties/entities/${args.entity_type}/${args.entity_id}/status/complete`;- const result = await propertiesFetch<{}>(url, {- method: 'PATCH',- });- return result.map(() => ({ success: true }));- },-getBulkEntityProperties: async (args: GetBulkEntityPropertiesArgs) => {return await propertiesFetch<GetBulkEntityProperties200>(`/properties/entities/bulk`,diff --git a/apps/web/src/lib/service-clients/service-search/generated/models/soupProperty.ts b/apps/web/src/lib/service-clients/service-search/generated/models/soupProperty.tsindex 6e2037755b..3e54631e39 100644--- a/apps/web/src/lib/service-clients/service-search/generated/models/soupProperty.ts+++ b/apps/web/src/lib/service-clients/service-search/generated/models/soupProperty.ts@@ -16,5 +16,7 @@ omitting the entity property assignment metadata and options.export interface SoupProperty {/** The property definition */definition: PropertyDefinition;+ /** Globally unique id of the assignment attaching this property to an entity. */+ id: string;value?: SoupPropertyValue;}diff --git a/apps/web/src/lib/service-clients/service-search/openapi.json b/apps/web/src/lib/service-clients/service-search/openapi.jsonindex a0b727e20a..6403abe0c6 100644--- a/apps/web/src/lib/service-clients/service-search/openapi.json+++ b/apps/web/src/lib/service-clients/service-search/openapi.json@@ -3709,12 +3709,17 @@"SoupProperty": {"type": "object","description": "A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.",- "required": ["definition"],+ "required": ["id", "definition"],"properties": {"definition": {"$ref": "#/components/schemas/PropertyDefinition","description": "The property definition"},+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Globally unique id of the assignment attaching this property to an entity."+ },"value": {"oneOf": [{diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupProperty.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupProperty.tsindex 91a24f27c3..8e0ec41565 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupProperty.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupProperty.ts@@ -16,5 +16,7 @@ omitting the entity property assignment metadata and options.export interface SoupProperty {/** The property definition */definition: PropertyDefinition;+ /** Globally unique id of the assignment attaching this property to an entity. */+ id: string;value?: SoupPropertyValue;}diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 7718dc353c..30622f8954 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -6821,6 +6821,11 @@ export const getItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -7103,6 +7108,11 @@ export const getItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -7348,6 +7358,11 @@ export const getItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -7744,6 +7759,11 @@ export const getItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -8447,6 +8467,11 @@ export const getItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -9387,6 +9412,11 @@ export const postItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -9669,6 +9699,11 @@ export const postItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -9914,6 +9949,11 @@ export const postItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -10310,6 +10350,11 @@ export const postItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -11013,6 +11058,11 @@ export const postItemsSoupResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -11479,6 +11529,11 @@ export const postItemsSoupAstResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -11761,6 +11816,11 @@ export const postItemsSoupAstResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -12006,6 +12066,11 @@ export const postItemsSoupAstResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -12402,6 +12467,11 @@ export const postItemsSoupAstResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -13107,6 +13177,11 @@ export const postItemsSoupAstResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -13829,6 +13904,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -14115,6 +14195,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -14360,6 +14445,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -14777,6 +14867,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -15523,6 +15618,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -15925,6 +16025,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -16211,6 +16316,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -16456,6 +16566,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -16873,6 +16988,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),@@ -17619,6 +17739,11 @@ export const postItemsSoupAstGroupedResponse = zod.describe('Property definition model (service representation).'),+ id: zod+ .uuid()+ .describe(+ 'Globally unique id of the assignment attaching this property to an entity.'+ ),value: zod.union([zod.null(),diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.tsnew file mode 100644index 0000000000..48c6b7e42e--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts@@ -0,0 +1,200 @@+import { ENABLE_GRAPHQL_SOUP } from '@core/constant/featureFlags';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { propertiesServiceClient } from '../service-properties/client';+import type { SetPropertyValue } from '../service-properties/generated/schemas/setPropertyValue';+import type { SoupPropertyFieldsFragment } from './graphql/generated/graphql';+import {+ setEntityProperty,+ toGraphqlPropertyEntityType,+ toGraphqlSetPropertyValue,+} from './graphql-properties';+import { getGraphqlSoupClient } from './graphql-soup';++vi.mock('@core/constant/featureFlags', () => ({+ ENABLE_GRAPHQL_SOUP: vi.fn(() => false),+}));++vi.mock('../service-properties/client', () => ({+ propertiesServiceClient: {+ setEntityProperty: vi.fn(),+ },+}));++vi.mock('./graphql-soup', () => ({+ getGraphqlSoupClient: vi.fn(),+}));++const restSetEntityProperty = vi.mocked(+ propertiesServiceClient.setEntityProperty+);+const flag = vi.mocked(ENABLE_GRAPHQL_SOUP);++type MutationResult = { data?: unknown; error?: unknown };++function mockGraphqlClient(result: MutationResult) {+ const mutation = vi.fn(() => ({+ toPromise: async () => result,+ }));+ vi.mocked(getGraphqlSoupClient).mockReturnValue({ mutation } as never);+ return mutation;+}++const okRestResult = { isErr: () => false, value: { success: true } } as never;++describe('toGraphqlSetPropertyValue', () => {+ it('converts every REST variant to the one-of input', () => {+ const cases: Array<[SetPropertyValue | null, unknown]> = [+ [null, null],+ [{ type: 'boolean', value: true }, { boolean: true }],+ [{ type: 'date', value: '2026-07-10' }, { date: '2026-07-10' }],+ [{ type: 'number', value: 4.5 }, { number: 4.5 }],+ [{ type: 'string', value: 'hi' }, { string: 'hi' }],+ [+ { type: 'select_option', option_id: 'opt-1' },+ { selectOption: 'opt-1' },+ ],+ [+ { type: 'multi_select_option', option_ids: ['a', 'b'] },+ { multiSelectOption: ['a', 'b'] },+ ],+ [+ {+ type: 'entity_reference',+ reference: {+ entity_id: 'doc-1',+ entity_type: 'DOCUMENT',+ specific_message_id: 'msg-1',+ },+ },+ {+ entityReference: {+ entityId: 'doc-1',+ entityType: 'DOCUMENT',+ specificMessageId: 'msg-1',+ },+ },+ ],+ [+ {+ type: 'multi_entity_reference',+ references: [{ entity_id: 'u-1', entity_type: 'USER' }],+ },+ {+ multiEntityReference: [+ { entityId: 'u-1', entityType: 'USER', specificMessageId: null },+ ],+ },+ ],+ [{ type: 'link', url: 'https://a' }, { link: 'https://a' }],+ [+ { type: 'multi_link', urls: ['https://a', 'https://b'] },+ { multiLink: ['https://a', 'https://b'] },+ ],+ ];+ for (const [input, expected] of cases) {+ expect(toGraphqlSetPropertyValue(input)).toEqual(expected);+ }+ });+});++describe('toGraphqlPropertyEntityType', () => {+ it('maps every REST entity type', () => {+ expect(toGraphqlPropertyEntityType('DOCUMENT')).toBe('DOCUMENT');+ expect(toGraphqlPropertyEntityType('TASK')).toBe('TASK');+ expect(toGraphqlPropertyEntityType('COMPANY')).toBe('COMPANY');+ });+});++describe('setEntityProperty', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ flag.mockReturnValue(false);+ });++ const args = {+ entityType: 'DOCUMENT' as const,+ entityId: 'doc-1',+ propertyDefinitionId: 'def-1',+ value: { type: 'string', value: 'hi' } satisfies SetPropertyValue,+ };++ it('uses the REST PUT when the flag is disabled', async () => {+ restSetEntityProperty.mockResolvedValue(okRestResult);+ const mutation = mockGraphqlClient({ data: undefined });++ await setEntityProperty(args);++ expect(restSetEntityProperty).toHaveBeenCalledWith({+ entity_type: 'DOCUMENT',+ entity_id: 'doc-1',+ property_id: 'def-1',+ body: { value: { type: 'string', value: 'hi' } },+ });+ expect(mutation).not.toHaveBeenCalled();+ });++ it('propagates REST errors as throws', async () => {+ restSetEntityProperty.mockResolvedValue({+ isErr: () => true,+ error: [{ code: 'boom', message: 'boom' }],+ } as never);++ await expect(setEntityProperty(args)).rejects.toThrow();+ });++ it('executes the GraphQL mutation when the flag is enabled', async () => {+ flag.mockReturnValue(true);+ const property = { id: 'prop-1' } as SoupPropertyFieldsFragment;+ const mutation = mockGraphqlClient({+ data: { setEntityProperty: property },+ });++ const result = await setEntityProperty(args);++ expect(restSetEntityProperty).not.toHaveBeenCalled();+ expect(mutation).toHaveBeenCalledOnce();+ const [, variables, context] = mutation.mock.calls[0] as unknown as [+ unknown,+ unknown,+ unknown,+ ];+ expect(variables).toEqual({+ input: {+ entityType: 'DOCUMENT',+ entityId: 'doc-1',+ propertyDefinitionId: 'def-1',+ value: { string: 'hi' },+ },+ });+ expect(context).toBeUndefined();+ expect(result).toBe(property);+ });++ it('attaches the optimistic response to the mutation context', async () => {+ flag.mockReturnValue(true);+ const optimistic = { id: 'prop-1' } as SoupPropertyFieldsFragment;+ const mutation = mockGraphqlClient({+ data: { setEntityProperty: optimistic },+ });++ await setEntityProperty({ ...args, optimisticProperty: optimistic });++ const [, , context] = mutation.mock.calls[0] as unknown as [+ unknown,+ unknown,+ Record<string, unknown>,+ ];+ expect(context).toEqual({+ normalizedCacheOptimistic: {+ optimisticResponse: { setEntityProperty: optimistic },+ },+ });+ });++ it('throws on GraphQL errors', async () => {+ flag.mockReturnValue(true);+ mockGraphqlClient({ error: new Error('mutation failed') });++ await expect(setEntityProperty(args)).rejects.toThrow('mutation failed');+ });+});diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.tsnew file mode 100644index 0000000000..15caf05aec--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts@@ -0,0 +1,182 @@+/**+ * Property-write transport: routes `setEntityProperty` through the GraphQL+ * mutation (normalized-cache-aware) when `ENABLE_GRAPHQL_SOUP` is on, and+ * through the existing REST PUT otherwise. Callers keep REST-shaped inputs;+ * conversion to the GraphQL input types happens here, strongly typed+ * against the generated operation.+ *+ * The atomic tag-option add/remove endpoints intentionally stay on REST:+ * they are server-side deltas, and replacing them with full-value writes+ * would regress concurrent updates.+ */++import { ENABLE_GRAPHQL_SOUP } from '@core/constant/featureFlags';+import { throwOnErr } from '@core/util/result';+import { executeOptimisticMutation } from '@graphql-cache/index';+import { match } from 'ts-pattern';+import { propertiesServiceClient } from '../service-properties/client';+import type { EntityReference } from '../service-properties/generated/schemas/entityReference';+import type { EntityType } from '../service-properties/generated/schemas/entityType';+import type { SetPropertyValue } from '../service-properties/generated/schemas/setPropertyValue';+import {+ type GraphqlEntityReferenceInput,+ type GraphqlPropertyEntityType,+ type GraphqlSetPropertyValue,+ SetEntityPropertyDocument,+ type SetEntityPropertyMutation,+ type SetEntityPropertyMutationVariables,+ type SoupPropertyFieldsFragment,+} from './graphql/generated/graphql';+import { getGraphqlSoupClient } from './graphql-soup';++/**+ * REST entity type → GraphQL enum. The unions are currently identical, but+ * the explicit table keeps divergence a compile error instead of a silent+ * bad request.+ */+const ENTITY_TYPE_TO_GRAPHQL: Record<EntityType, GraphqlPropertyEntityType> = {+ CHANNEL: 'CHANNEL',+ CHAT: 'CHAT',+ COMPANY: 'COMPANY',+ DOCUMENT: 'DOCUMENT',+ PROJECT: 'PROJECT',+ TASK: 'TASK',+ THREAD: 'THREAD',+ USER: 'USER',+};++export function toGraphqlPropertyEntityType(+ entityType: EntityType+): GraphqlPropertyEntityType {+ return ENTITY_TYPE_TO_GRAPHQL[entityType];+}++function toGraphqlEntityReference(+ reference: EntityReference+): GraphqlEntityReferenceInput {+ return {+ entityId: reference.entity_id,+ entityType: toGraphqlPropertyEntityType(reference.entity_type),+ specificMessageId: reference.specific_message_id ?? null,+ };+}++/** REST `SetPropertyValue` → the GraphQL one-of input. */+export function toGraphqlSetPropertyValue(+ value: SetPropertyValue | null+): GraphqlSetPropertyValue | null {+ if (value === null) return null;+ return match(value)+ .with(+ { type: 'boolean' },+ (v): GraphqlSetPropertyValue => ({+ boolean: v.value,+ })+ )+ .with({ type: 'date' }, (v): GraphqlSetPropertyValue => ({ date: v.value }))+ .with(+ { type: 'number' },+ (v): GraphqlSetPropertyValue => ({+ number: v.value,+ })+ )+ .with(+ { type: 'string' },+ (v): GraphqlSetPropertyValue => ({+ string: v.value,+ })+ )+ .with(+ { type: 'select_option' },+ (v): GraphqlSetPropertyValue => ({+ selectOption: v.option_id,+ })+ )+ .with(+ { type: 'multi_select_option' },+ (v): GraphqlSetPropertyValue => ({+ multiSelectOption: v.option_ids,+ })+ )+ .with(+ { type: 'entity_reference' },+ (v): GraphqlSetPropertyValue => ({+ entityReference: toGraphqlEntityReference(v.reference),+ })+ )+ .with(+ { type: 'multi_entity_reference' },+ (v): GraphqlSetPropertyValue => ({+ multiEntityReference: v.references.map(toGraphqlEntityReference),+ })+ )+ .with({ type: 'link' }, (v): GraphqlSetPropertyValue => ({ link: v.url }))+ .with(+ { type: 'multi_link' },+ (v): GraphqlSetPropertyValue => ({+ multiLink: v.urls,+ })+ )+ .exhaustive();+}++export type SetEntityPropertyArgs = {+ entityType: EntityType;+ entityId: string;+ propertyDefinitionId: string;+ /** REST-shaped value; `null` attaches the property without a value. */+ value: SetPropertyValue | null;+ /**+ * Complete optimistic mutation payload for an *existing* assignment+ * (its stable id updates the normalized record soup queries reference).+ * Omit for new attachments — no assignment id exists until the server+ * responds, so those run without optimism and rely on invalidation.+ */+ optimisticProperty?: SoupPropertyFieldsFragment | undefined;+};++/**+ * Sets or attaches one property on an entity. Rejects on transport or+ * GraphQL errors, matching the REST path's throw-on-error behavior+ * expected by the TanStack mutation hooks.+ */+export async function setEntityProperty(+ args: SetEntityPropertyArgs+): Promise<SoupPropertyFieldsFragment | void> {+ if (!ENABLE_GRAPHQL_SOUP()) {+ await throwOnErr(+ async () =>+ await propertiesServiceClient.setEntityProperty({+ entity_type: args.entityType,+ entity_id: args.entityId,+ property_id: args.propertyDefinitionId,+ body: { value: args.value },+ })+ );+ return;+ }++ const client = getGraphqlSoupClient();+ const variables: SetEntityPropertyMutationVariables = {+ input: {+ entityType: toGraphqlPropertyEntityType(args.entityType),+ entityId: args.entityId,+ propertyDefinitionId: args.propertyDefinitionId,+ value: toGraphqlSetPropertyValue(args.value),+ },+ };+ const result = args.optimisticProperty+ ? await executeOptimisticMutation(+ client,+ SetEntityPropertyDocument,+ variables,+ {+ setEntityProperty: args.optimisticProperty,+ } satisfies SetEntityPropertyMutation+ ).toPromise()+ : await client.mutation(SetEntityPropertyDocument, variables).toPromise();+ if (result.error) {+ throw result.error;+ }+ return result.data?.setEntityProperty;+}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.tsindex 0bc31c18ab..61bc5dc6ef 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts@@ -82,7 +82,7 @@ let cachedClient: Client | undefined;* different user wipes and rebinds the cache). See @graphql-cache/scope.* Any failure falls back to the plain fetch client for the session.*/-function getGraphqlSoupClient(): Client {+export function getGraphqlSoupClient(): Client {if (!graphqlCacheEnabled()) return graphqlSoupClient;cachedClient ??= (() => {try {@@ -190,6 +190,7 @@ function mapGraphqlPropertyValue(function mapGraphqlProperties(properties: GraphqlSoupProperty[]) {return properties.map((property) => ({+ id: property.id,definition: {id: property.propertyDefinitionId,display_name: property.displayName,@@ -506,6 +507,18 @@ function mapGraphqlSoupItem(item: GraphqlSoupItem): SoupApiItem {.exhaustive();}+/**+ * Maps a GraphQL soup response to the REST `SoupPage` shape consumed by+ * the existing soup pipeline (both the imperative fetch below and the+ * reactive urql subscriptions).+ */+export function mapGraphqlSoupPage(data: SoupQuery): SoupPage {+ return {+ items: data.user.soup.items.map(mapGraphqlSoupItem),+ next_cursor: data.user.soup.nextCursor ?? undefined,+ };+}+export async function fetchGraphqlSoup(input: GraphqlSoupInput): Promise<SoupPage> {@@ -535,10 +548,7 @@ export async function fetchGraphqlSoup().toPromise();if (cached.data) {- return {- items: cached.data.user.soup.items.map(mapGraphqlSoupItem),- next_cursor: cached.data.user.soup.nextCursor ?? undefined,- };+ return mapGraphqlSoupPage(cached.data);}}throw result.error;@@ -549,8 +559,5 @@ export async function fetchGraphqlSoup(throw new Error('GraphQL Soup query returned no data');}- return {- items: data.user.soup.items.map(mapGraphqlSoupItem),- next_cursor: data.user.soup.nextCursor ?? undefined,- };+ return mapGraphqlSoupPage(data);}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex d807028ffb..1de8d93ce6 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -216,6 +216,12 @@ export type GraphqlEntityFilterAst = {propertiesFilter?: GraphqlPropertiesExpr | null | undefined;};+export type GraphqlEntityReferenceInput = {+ entityId: string;+ entityType: GraphqlPropertyEntityType;+ specificMessageId?: string | number | null | undefined;+};+export type GraphqlForeignEntityBinaryExpr = {left: GraphqlForeignEntityExpr;right: GraphqlForeignEntityExpr;@@ -267,25 +273,53 @@ export type GraphqlPropertiesExpr =| { and?: never; literal?: never; not: GraphqlPropertiesExpr; or?: never; }| { and?: never; literal?: never; not?: never; or: GraphqlPropertiesBinaryExpr; };+/** GraphQL input for matching a property value on an entity. */export type GraphqlPropertiesLiteral = {+ /** Optional entity type scope for the property match. */entityType?: GraphqlPropertyEntityType | null | undefined;+ /** Property definition id to match. */propertyDefinitionId: string | number;+ /** Value to compare against the property. */value: GraphqlPropertyMatchValue;};+/** GraphQL entity type supported by property filters. */export type GraphqlPropertyEntityType =+ /** Channel entity. */| 'CHANNEL'+ /** Chat entity. */| 'CHAT'+ /** Company entity. */| 'COMPANY'+ /** Document entity. */| 'DOCUMENT'+ /** Project entity. */| 'PROJECT'+ /** Task entity. */| 'TASK'+ /** Thread entity. */| 'THREAD'+ /** User entity. */| 'USER';+/** GraphQL input value used when matching a property. */export type GraphqlPropertyMatchValue =- { entityRef: string; selectOption?: never; }- | { entityRef?: never; selectOption: string | number; };+ { /** Entity reference id to match. */+ entityRef: string; selectOption?: never; }+ | { entityRef?: never; /** Select option id to match. */+ selectOption: string | number; };++export type GraphqlSetPropertyValue =+ { boolean: boolean; date?: never; entityReference?: never; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date: string; entityReference?: never; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference: GraphqlEntityReferenceInput; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link: string; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link?: never; multiEntityReference: Array<GraphqlEntityReferenceInput>; multiLink?: never; multiSelectOption?: never; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link?: never; multiEntityReference?: never; multiLink: Array<string>; multiSelectOption?: never; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption: Array<string | number>; number?: never; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number: number; selectOption?: never; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number?: never; selectOption: string | number; string?: never; }+ | { boolean?: never; date?: never; entityReference?: never; link?: never; multiEntityReference?: never; multiLink?: never; multiSelectOption?: never; number?: never; selectOption?: never; string: string; };export type GraphqlSharedEmailFilter =| 'EXCLUDE'@@ -303,6 +337,7 @@ export type GraphqlSimpleSortMethod =/** Sort by viewed timestamp, falling back to updated timestamp. */| 'VIEWED_UPDATED';+/** GraphQL representation of supported Soup property data types. */export type GraphqlSoupDataType =/** Boolean true/false values. */| 'BOOLEAN'@@ -335,7 +370,7 @@ export type GraphqlSoupEntityType =| 'CHAT'/** CRM company entity. */| 'CRM_COMPANY'- /** crm contact */+ /** CRM contact entity. */| 'CRM_CONTACT'/** Document entity. */| 'DOCUMENT'@@ -345,23 +380,40 @@ export type GraphqlSoupEntityType =| 'FOREIGN_ENTITY'/** Project entity. */| 'PROJECT'- /** Static File */+ /** Static file entity. */| 'STATIC_FILE'- /** Team entity */+ /** Team entity. */| 'TEAM'- /** User entity */+ /** User entity. */| 'USER';+/** GraphQL entity type supported by Soup properties. */export type GraphqlSoupPropertyEntityType =+ /** Channel entity. */| 'CHANNEL'+ /** Chat entity. */| 'CHAT'+ /** Company entity. */| 'COMPANY'+ /** Document entity. */| 'DOCUMENT'+ /** Project entity. */| 'PROJECT'+ /** Task entity. */| 'TASK'+ /** Thread entity. */| 'THREAD'+ /** User entity. */| 'USER';+export type SetEntityPropertyInput = {+ entityId: string;+ entityType: GraphqlPropertyEntityType;+ propertyDefinitionId: string | number;+ /** Omit or pass null to attach the property without a value. */+ value?: GraphqlSetPropertyValue | null | undefined;+};+/** Input for `Query.soup`. */export type SoupInput = {/** Opaque cursor returned by a previous GraphQL Soup response. */@@ -381,6 +433,13 @@ export type SoupInput = {sortMethod?: GraphqlSimpleSortMethod | null | undefined;};+export type SetEntityPropertyMutationVariables = Exact<{+ input: SetEntityPropertyInput;+}>;+++export type SetEntityPropertyMutation = { setEntityProperty: { id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null } };+export type SoupQueryVariables = Exact<{input: SoupInput;}>;@@ -390,18 +449,19 @@ export type SoupQuery = { user: { id: string, soup: { nextCursor: string | null,| { __typename: 'GraphqlSoupCall', id: string, channelId: string, channelName: string | null, createdBy: string, customName: string | null, summary: string | null, startedAt: string, endedAt: string | null, durationMs: number | null, isActive: boolean, status: string, attended: boolean, participants: Array<{ userId: string, joinedAt: string, leftAt: string | null }> }| { __typename: 'GraphqlSoupChannel', id: string, channelType: string, ownerId: string, organizationId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, interactedAt: string | null, channelName: string | null, channelTeamId: string | null, participants: Array<{ channelId: string, userId: string, role: string, joinedAt: string, leftAt: string | null }>, latestMessage: { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> } | null, latestNonThreadMessage: { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> } | null }| { __typename: 'GraphqlSoupChannelThread', id: string, channelId: string, senderId: string, content: string, createdAt: string, updatedAt: string, effectiveUpdatedAt: string, replyCount: number }- | { __typename: 'GraphqlSoupChat', id: string, ownerId: string, projectId: string | null, isPersistent: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, chatName: string, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }- | { __typename: 'GraphqlSoupCrmCompany', id: string, description: string | null, emailSync: boolean, hidden: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, domains: Array<string>, crmTeamId: string, crmCompanyName: string | null, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }- | { __typename: 'GraphqlSoupDocument', id: string, ownerId: string, fileType: string | null, projectId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, documentName: string, subType: { kind: string, isCompleted: boolean | null } | null, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }- | { __typename: 'GraphqlSoupEmailThread', id: string, providerId: string | null, ownerId: string, inboxVisible: boolean, linkId: string | null, snippet: string | null, senderEmail: string | null, senderName: string | null, senderPhotoUrl: string | null, isRead: boolean, isDraft: boolean, isImportant: boolean, projectId: string | null, sortTs: string, createdAt: string, updatedAt: string, viewedAt: string | null, emailName: string | null, participants: Array<{ id: string, linkId: string, name: string | null, email: string | null, sfsPhotoUrl: string | null }>, attachments: Array<{ id: string, messageId: string, providerAttachmentId: string | null, filename: string | null, mimeType: string | null, sizeBytes: number | null, contentId: string | null, createdAt: string }>, labels: Array<{ id: string, linkId: string, providerLabelId: string, name: string, createdAt: string, messageListVisibility: string, labelListVisibility: string, type: string }>, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupChat', id: string, ownerId: string, projectId: string | null, isPersistent: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, chatName: string, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupCrmCompany', id: string, description: string | null, emailSync: boolean, hidden: boolean, createdAt: string, updatedAt: string, viewedAt: string | null, domains: Array<string>, crmTeamId: string, crmCompanyName: string | null, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupDocument', id: string, ownerId: string, fileType: string | null, projectId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, documentName: string, subType: { kind: string, isCompleted: boolean | null } | null, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupEmailThread', id: string, providerId: string | null, ownerId: string, inboxVisible: boolean, linkId: string | null, snippet: string | null, senderEmail: string | null, senderName: string | null, senderPhotoUrl: string | null, isRead: boolean, isDraft: boolean, isImportant: boolean, projectId: string | null, sortTs: string, createdAt: string, updatedAt: string, viewedAt: string | null, emailName: string | null, participants: Array<{ id: string, linkId: string, name: string | null, email: string | null, sfsPhotoUrl: string | null }>, attachments: Array<{ id: string, messageId: string, providerAttachmentId: string | null, filename: string | null, mimeType: string | null, sizeBytes: number | null, contentId: string | null, createdAt: string }>, labels: Array<{ id: string, linkId: string, providerLabelId: string, name: string, createdAt: string, messageListVisibility: string, labelListVisibility: string, type: string }>, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }| { __typename: 'GraphqlSoupForeignEntity', id: string, foreignEntityId: string, foreignEntitySource: string, storedForId: string, storedForAuthEntity: string, metadata: unknown, createdAt: string, updatedAt: string }- | { __typename: 'GraphqlSoupProject', id: string, ownerId: string, parentId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, projectName: string, properties: Array<{ propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }+ | { __typename: 'GraphqlSoupProject', id: string, ownerId: string, parentId: string | null, createdAt: string, updatedAt: string, viewedAt: string | null, deletedAt: string | null, projectName: string, properties: Array<{ id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null }> }}> } } };-export type SoupPropertyFieldsFragment = { propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null };+export type SoupPropertyFieldsFragment = { id: string, propertyDefinitionId: string, displayName: string, dataType: GraphqlSoupDataType, isMultiSelect: boolean, specificEntityType: GraphqlSoupPropertyEntityType | null, isSystem: boolean, isMetadata: boolean, value: { kind: string, boolValue: boolean | null, numberValue: number | null, stringValue: string | null, dateValue: string | null, selectOptionIds: Array<string>, links: Array<string>, entityReferences: Array<{ entityId: string, entityType: GraphqlSoupPropertyEntityType, specificMessageId: string | null }> } | null };export type SoupChannelMessageFieldsFragment = { id: string, threadId: string | null, senderId: string, content: string, createdAt: string, updatedAt: string, deletedAt: string | null, mentions: Array<string> };-export const SoupPropertyFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}}]} as unknown as DocumentNode<SoupPropertyFieldsFragment, unknown>;+export const SoupPropertyFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}}]} as unknown as DocumentNode<SoupPropertyFieldsFragment, unknown>;export const SoupChannelMessageFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupChannelMessageFieldsFragment, unknown>;-export const SoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Soup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasMore"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupQuery, SoupQueryVariables>;\ No newline at end of file+export const SetEntityPropertyDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SetEntityProperty"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SetEntityPropertyInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"setEntityProperty"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}}]} as unknown as DocumentNode<SetEntityPropertyMutation, SetEntityPropertyMutationVariables>;+export const SoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Soup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasMore"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"boolValue"}},{"kind":"Field","name":{"kind":"Name","value":"numberValue"}},{"kind":"Field","name":{"kind":"Name","value":"stringValue"}},{"kind":"Field","name":{"kind":"Name","value":"dateValue"}},{"kind":"Field","name":{"kind":"Name","value":"selectOptionIds"}},{"kind":"Field","name":{"kind":"Name","value":"entityReferences"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}},{"kind":"Field","name":{"kind":"Name","value":"links"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupQuery, SoupQueryVariables>;diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/set-entity-property.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/set-entity-property.graphqlnew file mode 100644index 0000000000..3d0285ad8f--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/graphql/set-entity-property.graphql@@ -0,0 +1,5 @@+mutation SetEntityProperty($input: SetEntityPropertyInput!) {+ setEntityProperty(input: $input) {+ ...SoupPropertyFields+ }+}diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/soup.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/soup.graphqlindex 6a125a47d8..07f5eaa840 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/soup.graphql+++ b/apps/web/src/lib/service-clients/service-storage/graphql/soup.graphql@@ -191,6 +191,7 @@ query Soup($input: SoupInput!) {}fragment SoupPropertyFields on GraphqlSoupProperty {+ idpropertyDefinitionIddisplayNamedataTypediff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex cac2302cdd..35761582bd 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -19244,12 +19244,17 @@"SoupProperty": {"type": "object","description": "A property attached to a Soup item.\n\nThis is a simplified representation that includes only the definition and value,\nomitting the entity property assignment metadata and options.",- "required": ["definition"],+ "required": ["id", "definition"],"properties": {"definition": {"$ref": "#/components/schemas/PropertyDefinition","description": "The property definition"},+ "id": {+ "type": "string",+ "format": "uuid",+ "description": "Globally unique id of the assignment attaching this property to an entity."+ },"value": {"oneOf": [{diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.tsindex cb5fdd9050..2ae0dae64e 100644--- a/apps/web/vitest.config.ts+++ b/apps/web/vitest.config.ts@@ -49,8 +49,16 @@ export default defineConfig({},},{- plugins: [tsconfigPaths()],+ // Resolve solid-js to its reactive browser build (the default+ // server-side build is inert), needed by the solid/ bindings.+ plugins: [tsconfigPaths(), solidPlugin()],+ ssr: {+ resolve: {+ conditions: ['browser', 'development'],+ },+ },test: {+ environment: 'jsdom',include: ['src/lib/graphql-cache/**/*.{test,spec}.{ts,tsx}'],name: 'graphql-cache',},diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex 18fef7c9b9..a9793ac07d 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -244,6 +244,7 @@ pub async fn build_tool_service_context_from_env(let task_properties_service = crate::tool_context::build_task_properties_adapter(pool.clone(),properties_service.clone(),+ entity_access_service.clone(),);let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(macro_event_broker::KafkaEventPublisher::new(env.kafka_brokers.as_ref())@@ -275,8 +276,10 @@ pub async fn build_tool_service_context_from_env(env.document_permission_jwt.to_string(),);- let properties_tool_context =- crate::tool_context::build_properties_tool_context(properties_service);+ let properties_tool_context = crate::tool_context::build_properties_tool_context(+ properties_service,+ entity_access_service.clone(),+ );let email_tool_context = email::inbound::toolset::EmailToolContext::new(Arc::new(EmailServiceImpl::new(diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 099fa752f6..de86fcddf0 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -20,6 +20,8 @@ use documents::{domain::ports::TaskPropertiesPort, inbound::toolset::DocumentToouse email::{domain::service::EmailServiceImpl, inbound::toolset::EmailToolContext, outbound::EmailPgRepo,};+use entity_access::domain::models::EditAccessLevel;+use entity_access::domain::ports::EntityAccessService as _;use foreign_entity::{domain::service::ForeignEntityServiceImpl,outbound::pg_foreign_entity_repo::PgForeignEntityRepo,@@ -200,6 +202,8 @@ pub struct TaskPropertiesAdapter {pub system_properties: Arc<ToolSystemPropertiesService>,/// Properties service used to assign concrete task property values.pub properties: Arc<ToolPropertiesService>,+ /// Canonical entity access service used to authorize task property writes.+ pub entity_access_service: Arc<ToolEntityAccessService>,}impl TaskPropertiesPort for TaskPropertiesAdapter {@@ -230,15 +234,24 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {use properties::PropertiesService as _;let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;-- let access = self- .properties- .mint_edit_receipt(&user_id, entity_id, models_properties::EntityType::Task)+ let entity_access_receipt = self+ .entity_access_service+ .generate_entity_access_receipt::<EditAccessLevel>(+ &user_id,+ None,+ entity_id,+ properties::access_entity_type(models_properties::EntityType::Task),+ ).await?;+ let access = properties::PropertiesAccessReceipt::try_from_entity_access_receipt(+ entity_access_receipt,+ models_properties::EntityType::Task,+ )?;self.properties.set_entity_property(&access, property_definition_id, value).await+ .map(|_| ()).map_err(Into::into)}@@ -547,7 +560,8 @@ pub type ToolPropertiesService = properties::PropertiesServiceImpl<>;/// Type alias for the properties tool context-pub type ToolPropertiesToolContext = PropertiesToolContext<ToolPropertiesService>;+pub type ToolPropertiesToolContext =+ PropertiesToolContext<ToolPropertiesService, ToolEntityAccessService>;/// Build the properties service shared by the properties tools and task adapter.pub fn build_properties_service(@@ -568,21 +582,25 @@ pub fn build_properties_service(pub fn build_task_properties_adapter(pool: sqlx::PgPool,properties: Arc<ToolPropertiesService>,+ entity_access_service: Arc<ToolEntityAccessService>,) -> TaskPropertiesAdapter {TaskPropertiesAdapter {system_properties: Arc::new(SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(pool),)),properties,+ entity_access_service,}}-/// Build a properties tool context from a shared properties service.+/// Build a properties tool context from shared domain and access services.pub fn build_properties_tool_context(properties: Arc<ToolPropertiesService>,+ entity_access_service: Arc<ToolEntityAccessService>,) -> ToolPropertiesToolContext {PropertiesToolContext {service: properties,+ entity_access_service,}}diff --git a/crates/client/cache-core/build.rs b/crates/client/cache-core/build.rsindex d15f70a54b..1330615e46 100644--- a/crates/client/cache-core/build.rs+++ b/crates/client/cache-core/build.rs@@ -42,6 +42,11 @@ fn main() {.expect("schema has no query root").name.to_string();+ let mutation_root = schema+ .schema_definition+ .mutation+ .as_ref()+ .map(|m| m.name.to_string());// The schema hash namespaces persisted caches; key policy is derived// from the schema, so hashing the schema covers it.@@ -72,8 +77,9 @@ fn main() {}match ty {ExtendedType::Object(obj) => {+ let is_operation_root = name == query_root || Some(&name) == mutation_root.as_ref();let key_literal =- key_literal(&name, name == query_root, obj.fields.iter(), &mut errors);+ key_literal(&name, is_operation_root, obj.fields.iter(), &mut errors);let fields = fields_literal(&schema, obj.fields.iter(), &mut errors);entries.push((name.clone(),@@ -117,6 +123,14 @@ fn main() {let mut out = String::new();writeln!(out, "// @generated by cache-core/build.rs — do not edit.").unwrap();writeln!(out, "pub static QUERY_ROOT_TYPE: &str = {query_root:?};").unwrap();+ match &mutation_root {+ Some(name) => writeln!(+ out,+ "pub static MUTATION_ROOT_TYPE: Option<&str> = Some({name:?});"+ )+ .unwrap(),+ None => writeln!(out, "pub static MUTATION_ROOT_TYPE: Option<&str> = None;").unwrap(),+ }writeln!(out, "pub static SCHEMA_HASH: &str = {schema_hash:?};").unwrap();writeln!(out, "pub static TYPES: &[TypeMeta] = &[").unwrap();for (_, literal) in &entries {@@ -132,7 +146,7 @@ fn main() {/// field must be a non-null, non-list `ID`. Types without `id` are embedded.fn key_literal<'a>(name: &str,- is_query_root: bool,+ is_operation_root: bool,fields: impl Iterator<Item = (&'a apollo_compiler::Name,@@ -145,8 +159,10 @@ fn key_literal<'a>(let Some((_, fdef)) = id_field else {return "None".into();};- if is_query_root {- errors.push(format!("query root `{name}` must not expose an `id` field"));+ if is_operation_root {+ errors.push(format!(+ "operation root `{name}` must not expose an `id` field"+ ));return "None".into();}match flatten_type(&fdef.ty) {diff --git a/crates/client/cache-core/src/document.rs b/crates/client/cache-core/src/document.rsindex 7ed2241e77..44a47f10d4 100644--- a/crates/client/cache-core/src/document.rs+++ b/crates/client/cache-core/src/document.rs@@ -20,7 +20,7 @@ pub enum DocumentError {NoOperation,#[error("operation `{0}` not found")]UnknownOperation(String),- #[error("only queries are supported (got {0})")]+ #[error("only queries and mutations are supported (got {0})")]UnsupportedOperationType(String),#[error("fragment `{0}` is not defined")]UnknownFragment(String),@@ -59,9 +59,17 @@ pub enum Selection {},}+/// Kind of an executable operation. Subscriptions are rejected at parse.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OperationKind {+ Query,+ Mutation,+}+#[derive(Debug)]pub struct Operation {pub name: Option<String>,+ pub kind: OperationKind,pub selection_set: Vec<Selection>,}@@ -113,13 +121,17 @@ impl Document {let mut operations = Vec::new();for op in operations_cst {- if let Some(ty) = op.operation_type() {- // Queries only for now; mutations/subscriptions are Phase 5+.- if ty.query_token().is_none() {+ // Shorthand (no operation type keyword) is a query.+ let kind = match op.operation_type() {+ None => OperationKind::Query,+ Some(ty) if ty.query_token().is_some() => OperationKind::Query,+ Some(ty) if ty.mutation_token().is_some() => OperationKind::Mutation,+ // Subscriptions are not cacheable.+ Some(ty) => {let label = ty.syntax().text().to_string();return Err(DocumentError::UnsupportedOperationType(label));}- }+ };let selection_set = convert_selection_set(op.selection_set().ok_or(DocumentError::Malformed("operation without selection set"))?,@@ -128,6 +140,7 @@ impl Document {)?;operations.push(Operation {name: op.name().map(|n| n.text().to_string()),+ kind,selection_set,});}@@ -426,8 +439,27 @@ mod tests {}#[test]- fn rejects_mutations() {- let err = Document::parse("mutation M { doThing }").unwrap_err();+ fn parses_operation_kinds() {+ let doc = Document::parse(DOC).unwrap();+ assert_eq!(+ doc.operation(Some("Soup")).unwrap().kind,+ OperationKind::Query+ );++ let doc = Document::parse("mutation M { doThing }").unwrap();+ assert_eq!(+ doc.operation(Some("M")).unwrap().kind,+ OperationKind::Mutation+ );++ // Shorthand operations are queries.+ let doc = Document::parse("{ user { id } }").unwrap();+ assert_eq!(doc.operation(None).unwrap().kind, OperationKind::Query);+ }++ #[test]+ fn rejects_subscriptions() {+ let err = Document::parse("subscription S { doThing }").unwrap_err();assert!(matches!(err, DocumentError::UnsupportedOperationType(_)));}diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rsindex 428b20614a..cee1bcd6ae 100644--- a/crates/client/cache-core/src/engine.rs+++ b/crates/client/cache-core/src/engine.rs@@ -4,13 +4,13 @@use crate::denormalize::{DenormalizeError, ReadOutcome, RecordSource, denormalize};use crate::deps::{DepIndex, OpId};-use crate::document::{Document, DocumentError};-use crate::normalize::{NormalizeError, normalize};+use crate::document::{Document, DocumentError, OperationKind};+use crate::normalize::{NormalizeError, RecordUpdates, normalize};use crate::store::Storage;use crate::value::{EntityKey, Record};use lru::LruCache;use serde_json::Value as Json;-use std::collections::{BTreeSet, HashMap};+use std::collections::{BTreeMap, BTreeSet, HashMap};use std::num::NonZeroUsize;use thiserror::Error;@@ -22,6 +22,8 @@ pub enum EngineError<S: std::error::Error + 'static> {Normalize(#[from] NormalizeError),#[error(transparent)]Denormalize(#[from] DenormalizeError),+ #[error("unknown or already-settled optimistic transaction {0}")]+ UnknownTransaction(OptimisticTransactionId),#[error("storage: {0}")]Storage(#[source] S),}@@ -51,6 +53,51 @@ pub struct WriteResult {pub reset: bool,}+/// Engine-assigned id of one optimistic mutation transaction. Never reuse+/// host operation keys: identical concurrent mutations share an urql key,+/// but each needs its own layer.+pub type OptimisticTransactionId = u64;++/// One optimistic mutation's contribution to the cache view. Layers are+/// ordered by creation; later layers override earlier ones field-by-field,+/// all of them override the durable base. Nothing in a layer is persisted+/// until the layer settles *and* every earlier layer has settled too+/// (contiguous-prefix flushing keeps out-of-order settlement correct).+struct OptimisticLayer {+ id: OptimisticTransactionId,+ state: OptimisticLayerState,+}++enum OptimisticLayerState {+ /// Awaiting the network result; `updates` normalized from the+ /// optimistic response.+ Pending { updates: RecordUpdates },+ /// Network result arrived; `updates` replaced by the real response.+ /// Held in-memory until the layer reaches the settled prefix.+ Succeeded { updates: RecordUpdates },+ /// Rolled back. Kept as an ordered tombstone (contributing nothing)+ /// until earlier layers settle, then dropped by the prefix flush.+ Failed,+}++impl OptimisticLayer {+ /// The record updates this layer currently contributes to reads.+ fn updates(&self) -> Option<&RecordUpdates> {+ match &self.state {+ OptimisticLayerState::Pending { updates }+ | OptimisticLayerState::Succeeded { updates } => Some(updates),+ OptimisticLayerState::Failed => None,+ }+ }++ fn settled(&self) -> bool {+ matches!(+ self.state,+ OptimisticLayerState::Succeeded { .. } | OptimisticLayerState::Failed+ )+ }+}+/// Reserved storage key holding the identity bound to this cache. The/// `__meta:` prefix can never collide with entity keys (typenames can't/// contain `:`).@@ -79,6 +126,10 @@ pub struct Engine<S: Storage> {docs: HashMap<String, Document>,deps: DepIndex,identity: IdentityState,+ /// Ordered optimistic mutation layers (memory-only; see+ /// [`OptimisticLayer`]).+ optimistic: Vec<OptimisticLayer>,+ next_transaction: OptimisticTransactionId,}impl<S: Storage> Engine<S> {@@ -93,6 +144,8 @@ impl<S: Storage> Engine<S> {docs: HashMap::new(),deps: DepIndex::new(),identity: IdentityState::NotHydrated,+ optimistic: Vec::new(),+ next_transaction: 0,}}@@ -146,8 +199,29 @@ impl<S: Storage> Engine<S> {) -> Result<ReadResult, EngineError<S::Error>> {let doc = Self::document(&mut self.docs, query)?;let op = doc.operation(operation_name)?;+ if op.kind != OperationKind::Query {+ return Err(EngineError::Document(+ DocumentError::UnsupportedOperationType("mutation (reads are query-only)".into()),+ ));+ }- let mut overlay: HashMap<EntityKey, Record> = HashMap::new();+ // Effective read view = durable base + optimistic layers, composed+ // per key. `composed` holds the merged records for optimistically+ // touched keys and is never promoted into the hot tier — the durable+ // LRU base must stay free of optimistic values.+ let optimistic = merged_optimistic(&self.optimistic);+ let mut composed: HashMap<EntityKey, Record> = HashMap::new();+ for (key, update) in &optimistic {+ if let Some(base) = self.hot.peek(key) {+ let mut merged = base.clone();+ merged.merge(update.clone());+ composed.insert(key.clone(), merged);+ }+ }++ // Durable records fetched from storage this read (pre-merge — safe+ // to promote into the hot tier afterwards).+ let mut fetched_base: HashMap<EntityKey, Record> = HashMap::new();let mut known_absent: BTreeSet<EntityKey> = BTreeSet::new();let mut deps = BTreeSet::new();@@ -155,7 +229,8 @@ impl<S: Storage> Engine<S> {deps.clear();let source = EngineSource {hot: &self.hot,- overlay: &overlay,+ fetched: &fetched_base,+ composed: &composed,};match denormalize(op, variables, &source, &mut deps)? {ReadOutcome::Complete(data) => break ReadResult::Hit { data },@@ -163,7 +238,11 @@ impl<S: Storage> Engine<S> {ReadOutcome::NeedRecords(missing) => {let to_fetch: Vec<EntityKey> = missing.into_iter()- .filter(|k| !known_absent.contains(k) && !overlay.contains_key(k))+ .filter(|k| {+ !known_absent.contains(k)+ && !fetched_base.contains_key(k)+ && !composed.contains_key(k)+ }).collect();if to_fetch.is_empty() {// Everything missing is genuinely absent → miss.@@ -177,10 +256,20 @@ impl<S: Storage> Engine<S> {for (key, record) in to_fetch.into_iter().zip(fetched) {match record {Some(r) => {- overlay.insert(key, r);+ if let Some(update) = optimistic.get(&key) {+ let mut merged = r.clone();+ merged.merge(update.clone());+ composed.insert(key.clone(), merged);+ }+ fetched_base.insert(key, r);}None => {- known_absent.insert(key);+ if let Some(update) = optimistic.get(&key) {+ // Entity exists only optimistically.+ composed.insert(key, update.clone());+ } else {+ known_absent.insert(key);+ }}}}@@ -188,9 +277,9 @@ impl<S: Storage> Engine<S> {}};- // Promote overlay records into the hot tier and refresh recency of+ // Promote durable records into the hot tier and refresh recency of// everything this operation touched.- for (key, record) in overlay {+ for (key, record) in fetched_base {self.hot.put(key, record);}for key in &deps {@@ -231,6 +320,9 @@ impl<S: Storage> Engine<S> {IdentityState::Bound(bound) if bound == observed => {}IdentityState::Bound(_) => {self.hot.clear();+ // A different user's session: in-flight optimistic+ // mutations belong to the old identity — discard them.+ self.optimistic.clear();self.storage.clear().await.map_err(EngineError::Storage)?;self.bind_identity(observed).await?;reset = true;@@ -238,6 +330,30 @@ impl<S: Storage> Engine<S> {}}+ let changed = self.persist_updates(updates).await?;++ let mut affected_ops = if reset {+ // Everything anyone had cached is gone: re-execute all ops.+ self.deps.all_ops()+ } else {+ self.deps.ops_for_keys(changed.iter())+ };+ if let Some(origin) = origin_op {+ affected_ops.remove(&origin);+ }+ Ok(WriteResult {+ changed,+ affected_ops,+ reset,+ })+ }++ /// Merges normalized updates into the hot tier and storage. Returns the+ /// keys whose durable contents actually changed.+ async fn persist_updates(+ &mut self,+ updates: RecordUpdates,+ ) -> Result<BTreeSet<EntityKey>, EngineError<S::Error>> {// Load current values (hot tier, then storage) so merges detect real// changes. Merges are staged in a plain map, NOT the LRU: a batch// larger than the hot capacity would otherwise evict its own@@ -293,29 +409,207 @@ impl<S: Storage> Engine<S> {.put_batch(to_persist).await.map_err(EngineError::Storage)?;+ Ok(changed)+ }- let mut affected_ops = if reset {- // Everything anyone had cached is gone: re-execute all ops.- self.deps.all_ops()- } else {- self.deps.ops_for_keys(changed.iter())- };+ /// Installs a new optimistic layer from a mutation's optimistic+ /// response. Persists nothing. Returns the transaction id plus a+ /// [`WriteResult`] whose `changed` keys are the entities whose+ /// *effective visible* data changed (`affected_ops` excludes+ /// `origin_op`). The layer stays in memory until+ /// [`commit_optimistic_write`](Self::commit_optimistic_write) or+ /// [`rollback_optimistic_write`](Self::rollback_optimistic_write).+ pub async fn begin_optimistic_write(+ &mut self,+ origin_op: Option<OpId>,+ query: &str,+ operation_name: Option<&str>,+ variables: &serde_json::Map<String, Json>,+ data: &Json,+ ) -> Result<(OptimisticTransactionId, WriteResult), EngineError<S::Error>> {+ let doc = Self::document(&mut self.docs, query)?;+ let op = doc.operation(operation_name)?;+ let updates = normalize(op, variables, data)?;++ let candidates: BTreeSet<EntityKey> = updates.keys().cloned().collect();+ let bases = self.load_bases(&candidates).await?;+ let before = effective_records(&bases, &self.optimistic, &candidates);++ self.next_transaction += 1;+ let id = self.next_transaction;+ self.optimistic.push(OptimisticLayer {+ id,+ state: OptimisticLayerState::Pending { updates },+ });++ let after = effective_records(&bases, &self.optimistic, &candidates);+ let changed: BTreeSet<EntityKey> = candidates+ .into_iter()+ .filter(|k| before.get(k) != after.get(k))+ .collect();+ let mut affected_ops = self.deps.ops_for_keys(changed.iter());if let Some(origin) = origin_op {affected_ops.remove(&origin);}+ Ok((+ id,+ WriteResult {+ changed,+ affected_ops,+ reset: false,+ },+ ))+ }++ /// Replaces a pending layer's optimistic updates with the normalized+ /// real network response and marks it succeeded — atomically, so+ /// dependents never flicker back to pre-optimistic data. Flushes the+ /// contiguous settled prefix of layers into durable storage.+ ///+ /// The returned `changed` keys are the *durably* changed records (for+ /// cross-instance broadcast); `affected_ops` are the operations whose+ /// effective visible data changed (for local re-execution).+ pub async fn commit_optimistic_write(+ &mut self,+ transaction: OptimisticTransactionId,+ query: &str,+ operation_name: Option<&str>,+ variables: &serde_json::Map<String, Json>,+ data: &Json,+ ) -> Result<WriteResult, EngineError<S::Error>> {+ let doc = Self::document(&mut self.docs, query)?;+ let op = doc.operation(operation_name)?;+ let updates = normalize(op, variables, data)?;+ self.settle_layer(transaction, OptimisticLayerState::Succeeded { updates })+ .await+ }++ /// Marks a pending layer failed, removing its contribution from the+ /// effective view, and flushes any now-contiguous settled prefix. The+ /// failed layer remains an ordered tombstone until all earlier layers+ /// settle. Result semantics match+ /// [`commit_optimistic_write`](Self::commit_optimistic_write).+ pub async fn rollback_optimistic_write(+ &mut self,+ transaction: OptimisticTransactionId,+ ) -> Result<WriteResult, EngineError<S::Error>> {+ self.settle_layer(transaction, OptimisticLayerState::Failed)+ .await+ }++ async fn settle_layer(+ &mut self,+ transaction: OptimisticTransactionId,+ new_state: OptimisticLayerState,+ ) -> Result<WriteResult, EngineError<S::Error>> {+ let index = self+ .optimistic+ .iter()+ .position(|l| l.id == transaction && !l.settled())+ .ok_or(EngineError::UnknownTransaction(transaction))?;++ // Keys whose effective value may change: everything the old+ // (optimistic) or new (real) updates touch.+ let mut candidates: BTreeSet<EntityKey> = self.optimistic[index]+ .updates()+ .map(|u| u.keys().cloned().collect())+ .unwrap_or_default();+ if let OptimisticLayerState::Succeeded { updates } = &new_state {+ candidates.extend(updates.keys().cloned());+ }++ let bases = self.load_bases(&candidates).await?;+ let before = effective_records(&bases, &self.optimistic, &candidates);+ self.optimistic[index].state = new_state;+ let after = effective_records(&bases, &self.optimistic, &candidates);+ let visible_changed: BTreeSet<EntityKey> = candidates+ .into_iter()+ .filter(|k| before.get(k) != after.get(k))+ .collect();++ // Flush the contiguous settled prefix into durable storage. The+ // flushed data was already visible through the layers, so this does+ // not change the effective view and adds no local notifications;+ // the durably changed keys it returns drive cross-instance+ // broadcasts.+ let durable_changed = self.flush_settled_prefix().await?;++ let affected_ops = self.deps.ops_for_keys(visible_changed.iter());Ok(WriteResult {- changed,+ changed: durable_changed,affected_ops,- reset,+ reset: false,})}+ /// Persists and drops the leading run of settled layers. Succeeded+ /// layers' updates merge into durable storage (in layer order); failed+ /// layers are dropped. Later pending layers keep overriding the newly+ /// committed base, preserving order under out-of-order settlement.+ async fn flush_settled_prefix(&mut self) -> Result<BTreeSet<EntityKey>, EngineError<S::Error>> {+ let mut merged = RecordUpdates::new();+ let mut count = 0;+ for layer in &self.optimistic {+ if !layer.settled() {+ break;+ }+ if let Some(updates) = layer.updates() {+ for (key, record) in updates {+ merged.entry(key.clone()).or_default().merge(record.clone());+ }+ }+ count += 1;+ }+ if count == 0 {+ return Ok(BTreeSet::new());+ }+ self.optimistic.drain(..count);+ if merged.is_empty() {+ // Prefix was all tombstones.+ return Ok(BTreeSet::new());+ }+ self.persist_updates(merged).await+ }++ /// Loads current durable records (hot tier, then storage) for `keys`+ /// without touching LRU recency or persisting anything.+ async fn load_bases(+ &mut self,+ keys: &BTreeSet<EntityKey>,+ ) -> Result<HashMap<EntityKey, Record>, EngineError<S::Error>> {+ let mut out = HashMap::new();+ let mut missing: Vec<EntityKey> = Vec::new();+ for key in keys {+ match self.hot.peek(key) {+ Some(record) => {+ out.insert(key.clone(), record.clone());+ }+ None => missing.push(key.clone()),+ }+ }+ if !missing.is_empty() {+ let fetched = self+ .storage+ .get_batch(&missing)+ .await+ .map_err(EngineError::Storage)?;+ for (key, record) in missing.into_iter().zip(fetched) {+ if let Some(r) = record {+ out.insert(key, r);+ }+ }+ }+ Ok(out)+ }+/// Reacts to a reset performed by *another* engine instance sharing the/// same storage (cross-tab broadcast): drops all local in-memory state/// and returns every local active operation for re-execution.pub fn external_reset(&mut self) -> BTreeSet<OpId> {self.hot.clear();self.docs.clear();+ // Optimistic layers were normalized against the wiped base.+ self.optimistic.clear();// Another engine may have rebound the shared storage → re-hydrate.self.identity = IdentityState::NotHydrated;self.deps.all_ops()@@ -342,9 +636,11 @@ impl<S: Storage> Engine<S> {affected}- /// Drops all cached state (logout, schema-hash mismatch).+ /// Drops all cached state (logout, schema-hash mismatch), including any+ /// pending optimistic layers.pub async fn clear(&mut self) -> Result<(), EngineError<S::Error>> {self.hot.clear();+ self.optimistic.clear();self.deps = DepIndex::new();// The wipe below removes the binding record too.self.identity = IdentityState::Missing;@@ -375,15 +671,59 @@ impl<S: Storage> Engine<S> {}}-/// Read view over hot tier + per-read overlay. Uses `peek` (no recency-/// mutation) — recency is refreshed once per read from the dep set.+/// Read view over the durable tiers plus the optimistic composition. Uses+/// `peek` (no recency mutation) — recency is refreshed once per read from+/// the dep set.struct EngineSource<'a> {hot: &'a LruCache<EntityKey, Record>,- overlay: &'a HashMap<EntityKey, Record>,+ /// Durable records batch-fetched from storage during this read.+ fetched: &'a HashMap<EntityKey, Record>,+ /// Optimistically touched keys: durable base + layers, pre-merged.+ /// Takes precedence over both durable tiers.+ composed: &'a HashMap<EntityKey, Record>,}impl RecordSource for EngineSource<'_> {fn get(&self, key: &EntityKey) -> Option<&Record> {- self.overlay.get(key).or_else(|| self.hot.peek(key))+ self.composed+ .get(key)+ .or_else(|| self.fetched.get(key))+ .or_else(|| self.hot.peek(key))}}++/// All active optimistic layers' updates merged in creation order (later+/// layers override earlier ones field-by-field).+fn merged_optimistic(layers: &[OptimisticLayer]) -> BTreeMap<EntityKey, Record> {+ let mut out: BTreeMap<EntityKey, Record> = BTreeMap::new();+ for layer in layers {+ if let Some(updates) = layer.updates() {+ for (key, record) in updates {+ out.entry(key.clone()).or_default().merge(record.clone());+ }+ }+ }+ out+}++/// Effective visible records for `keys`: durable base + every active layer+/// merged in order. `None` when the key exists nowhere.+fn effective_records(+ bases: &HashMap<EntityKey, Record>,+ layers: &[OptimisticLayer],+ keys: &BTreeSet<EntityKey>,+) -> HashMap<EntityKey, Option<Record>> {+ keys.iter()+ .map(|key| {+ let mut record: Option<Record> = bases.get(key).cloned();+ for layer in layers {+ if let Some(update) = layer.updates().and_then(|u| u.get(key)) {+ record+ .get_or_insert_with(Record::default)+ .merge(update.clone());+ }+ }+ (key.clone(), record)+ })+ .collect()+}diff --git a/crates/client/cache-core/src/meta.rs b/crates/client/cache-core/src/meta.rsindex 428ebcabe6..20c16291b0 100644--- a/crates/client/cache-core/src/meta.rs+++ b/crates/client/cache-core/src/meta.rs@@ -101,6 +101,15 @@ mod tests {assert!(user.fields.iter().any(|f| f.name == "soup"));}+ #[test]+ fn mutation_root_is_present() {+ let name = MUTATION_ROOT_TYPE.expect("schema has a mutation root");+ let root = type_meta(name).expect("mutation root type");+ assert_eq!(root.kind, TypeKind::Object);+ assert!(root.key_fields.is_none());+ assert!(root.fields.iter().any(|f| f.name == "setEntityProperty"));+ }+#[test]fn union_possible_types() {let entity = type_meta("GraphqlSoupEntity").expect("entity union");@@ -123,9 +132,12 @@ mod tests {type_meta("GraphqlSoupChannelMessage").unwrap().key_fields,Some(&["id"][..]));- // Property values are per-entity; the schema exposes the definition- // id as `propertyDefinitionId` (not `id`) so properties embed.- assert_eq!(type_meta("GraphqlSoupProperty").unwrap().key_fields, None);+ // Property assignments have globally unique database ids and are+ // normalized independently from their shared definitions.+ assert_eq!(+ type_meta("GraphqlSoupProperty").unwrap().key_fields,+ Some(&["id"][..])+ );assert!(field_meta("GraphqlSoupProperty", "propertyDefinitionId").is_some());// No id field → embedded.assert_eq!(type_meta("SoupPage").unwrap().key_fields, None);diff --git a/crates/client/cache-core/src/normalize.rs b/crates/client/cache-core/src/normalize.rsindex 52c9d9b3a3..62e6a50b68 100644--- a/crates/client/cache-core/src/normalize.rs+++ b/crates/client/cache-core/src/normalize.rs@@ -1,6 +1,8 @@//! Write path: response JSON → normalized records.-use crate::document::{FieldNode, MissingVariable, Operation, Selection, resolve_args_key};+use crate::document::{+ FieldNode, MissingVariable, Operation, OperationKind, Selection, resolve_args_key,+};use crate::meta::{self, FieldKind, TypeKind};use crate::value::{CacheValue, EntityKey, Record, field_key};use serde_json::Value as Json;@@ -36,16 +38,26 @@ pub enum NormalizeError {/// records.pub type RecordUpdates = BTreeMap<EntityKey, Record>;-/// Normalizes a response's `data` object into record updates rooted at-/// [`ROOT_QUERY`](crate::value::ROOT_QUERY).+/// Normalizes a response's `data` object into record updates.+///+/// Query responses are rooted at [`ROOT_QUERY`](crate::value::ROOT_QUERY).+/// Mutation responses traverse from the schema's mutation root: entities in+/// the payload are normalized as usual, but the root mutation fields+/// themselves are discarded — mutation roots are transient cache entry+/// points, never read back.pub fn normalize(op: &Operation,variables: &serde_json::Map<String, Json>,data: &Json,) -> Result<RecordUpdates, NormalizeError> {+ let root_type = match op.kind {+ OperationKind::Query => meta::QUERY_ROOT_TYPE,+ OperationKind::Mutation => meta::MUTATION_ROOT_TYPE+ .ok_or_else(|| NormalizeError::UnknownType("(mutation root)".to_string()))?,+ };let Json::Object(data) = data else {return Err(NormalizeError::Shape {- type_name: meta::QUERY_ROOT_TYPE.to_string(),+ type_name: root_type.to_string(),field: "(data)".to_string(),detail: "response data is not an object",});@@ -54,13 +66,15 @@ pub fn normalize(let mut root = Record::default();write_object_fields(&op.selection_set,- meta::QUERY_ROOT_TYPE,+ root_type,data,variables,&mut root.fields,&mut records,)?;- merge_into(&mut records, EntityKey::root(), root);+ if op.kind == OperationKind::Query {+ merge_into(&mut records, EntityKey::root(), root);+ }Ok(records)}diff --git a/crates/client/cache-core/tests/optimistic.rs b/crates/client/cache-core/tests/optimistic.rsnew file mode 100644index 0000000000..9e672101cf--- /dev/null+++ b/crates/client/cache-core/tests/optimistic.rs@@ -0,0 +1,689 @@+//! Optimistic mutation layer tests: begin/read/commit/rollback, out-of-order+//! settlement, layer composition, durable isolation, and lifecycle resets.++use cache_core::engine::{Engine, EngineError, ReadResult};+use cache_core::store::InMemoryStorage;+use cache_core::value::EntityKey;+use pollster::block_on;+use serde_json::{Value as Json, json};++const QUERY: &str = r#"+query Soup($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ id+ entity {+ __typename+ ... on GraphqlSoupDocument {+ id+ properties { id displayName value { kind stringValue } }+ }+ }+ }+ hasMore+ }+ }+}+"#;++const MUTATION: &str = r#"+mutation SetEntityProperty($input: SetEntityPropertyInput!) {+ setEntityProperty(input: $input) {+ id+ displayName+ value { kind stringValue }+ }+}+"#;++const PROPERTY_KEY: &str = "GraphqlSoupProperty:prop-1";++fn query_vars() -> serde_json::Map<String, Json> {+ let Json::Object(map) = json!({ "input": { "limit": 10 } }) else {+ unreachable!()+ };+ map+}++fn mutation_vars(value: &str) -> serde_json::Map<String, Json> {+ let Json::Object(map) = json!({+ "input": {+ "entityType": "DOCUMENT",+ "entityId": "doc-1",+ "propertyDefinitionId": "def-1",+ "value": { "string": value }+ }+ }) else {+ unreachable!()+ };+ map+}++fn soup_page(display_name: &str, value: &str) -> Json {+ json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [{+ "id": "item-1",+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": "doc-1",+ "properties": [{+ "id": "prop-1",+ "displayName": display_name,+ "value": { "kind": "String", "stringValue": value }+ }]+ }+ }],+ "hasMore": false+ }+ }+ })+}++fn mutation_response(display_name: &str, value: &str) -> Json {+ json!({+ "setEntityProperty": {+ "id": "prop-1",+ "displayName": display_name,+ "value": { "kind": "String", "stringValue": value }+ }+ })+}++/// Reads the property object out of a soup query hit.+fn property_of(data: &Json) -> &Json {+ &data["user"]["soup"]["items"][0]["entity"]["properties"][0]+}++async fn engine_with_base(display_name: &str, value: &str) -> Engine<InMemoryStorage> {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ QUERY,+ Some("Soup"),+ &query_vars(),+ &soup_page(display_name, value),+ None,+ )+ .await+ .unwrap();+ engine+}++async fn read_hit(engine: &mut Engine<InMemoryStorage>, op: Option<u64>) -> Json {+ match engine+ .read_query(op, QUERY, Some("Soup"), &query_vars())+ .await+ .unwrap()+ {+ ReadResult::Hit { data } => data,+ ReadResult::Miss => panic!("expected hit"),+ }+}++/// The durable (storage) value of the property record's displayName, read+/// directly from the underlying store — bypassing optimistic layers.+async fn durable_display_name(engine: &Engine<InMemoryStorage>) -> Option<String> {+ use cache_core::store::Storage;+ use cache_core::value::CacheValue;+ let records = engine+ .storage()+ .get_batch(&[EntityKey(PROPERTY_KEY.to_string())])+ .await+ .unwrap();+ records+ .into_iter()+ .next()+ .flatten()+ .and_then(|record| match record.fields.get("displayName") {+ Some(CacheValue::String(s)) => Some(s.clone()),+ _ => None,+ })+}++#[test]+fn network_mutation_without_layer_writes_through() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ // Register op 1 on the soup query.+ read_hit(&mut engine, Some(1)).await;++ // A plain (non-optimistic) mutation response normalizes into the+ // same records and notifies dependents.+ let write = engine+ .write_query(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("done"),+ &mutation_response("Status", "done"),+ None,+ )+ .await+ .unwrap();+ assert!(write.changed.contains(&EntityKey(PROPERTY_KEY.to_string())));+ assert!(write.affected_ops.contains(&1));+ // Mutation root fields are transient: nothing lands on ROOT_QUERY.+ assert!(!write.changed.iter().any(|k| k.is_root()));++ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("done"));+ assert_eq!(+ durable_display_name(&engine).await.as_deref(),+ Some("Status")+ );+ });+}++#[test]+fn reads_reject_mutation_documents() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ let err = engine+ .read_query(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("x"),+ )+ .await+ .unwrap_err();+ assert!(matches!(err, EngineError::Document(_)));+ });+}++#[test]+fn begin_composes_over_base_without_persisting() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ let (txn, begin) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();+ assert!(txn > 0);+ assert!(begin.changed.contains(&EntityKey(PROPERTY_KEY.to_string())));+ assert!(begin.affected_ops.contains(&1));+ assert!(!begin.reset);++ // Reads see the optimistic value; durable state is untouched.+ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("doing"));+ use cache_core::store::Storage;+ use cache_core::value::CacheValue;+ let stored = engine+ .storage()+ .get_batch(&[EntityKey(PROPERTY_KEY.to_string())])+ .await+ .unwrap();+ let stored = stored.into_iter().next().flatten().unwrap();+ let Some(CacheValue::Object(value)) = stored.fields.get("value") else {+ panic!("stored value shape");+ };+ assert_eq!(+ value.get("stringValue"),+ Some(&CacheValue::String("todo".into()))+ );+ });+}++#[test]+fn begin_with_identical_data_notifies_nobody() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ // Optimistic response identical to the cached data → the effective+ // view is unchanged, nobody re-executes.+ let (_, begin) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("todo"),+ &mutation_response("Status", "todo"),+ )+ .await+ .unwrap();+ assert!(begin.changed.is_empty());+ assert!(begin.affected_ops.is_empty());+ });+}++#[test]+fn commit_replaces_layer_and_flushes_durably() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ let (txn, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();++ // The network result differs from the optimistic response.+ let commit = engine+ .commit_optimistic_write(+ txn,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status (renamed)", "doing"),+ )+ .await+ .unwrap();+ // Durable flush happened (single layer = contiguous prefix).+ assert!(+ commit+ .changed+ .contains(&EntityKey(PROPERTY_KEY.to_string()))+ );+ // displayName's visible value changed with the real response.+ assert!(commit.affected_ops.contains(&1));++ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["displayName"], json!("Status (renamed)"));+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("doing"));+ assert_eq!(+ durable_display_name(&engine).await.as_deref(),+ Some("Status (renamed)")+ );++ // Settled transactions are gone: settling again is an error.+ assert!(matches!(+ engine.rollback_optimistic_write(txn).await,+ Err(EngineError::UnknownTransaction(_))+ ));+ });+}++#[test]+fn commit_matching_optimistic_response_is_silent() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ let (txn, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();+ let commit = engine+ .commit_optimistic_write(+ txn,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();+ // Visible data did not change (real == optimistic) → no local+ // notifications; durable keys still broadcast for other instances.+ assert!(commit.affected_ops.is_empty());+ assert!(+ commit+ .changed+ .contains(&EntityKey(PROPERTY_KEY.to_string()))+ );+ });+}++#[test]+fn rollback_restores_base_view() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ let (txn, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();+ let rollback = engine.rollback_optimistic_write(txn).await.unwrap();+ assert!(rollback.affected_ops.contains(&1));+ // Nothing was ever durable, nothing flushed.+ assert!(rollback.changed.is_empty());++ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("todo"));+ assert_eq!(+ durable_display_name(&engine).await.as_deref(),+ Some("Status")+ );+ });+}++#[test]+fn out_of_order_settlement_preserves_later_layer() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ // A then B target the same field.+ let (txn_a, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("a"),+ &mutation_response("Status", "a"),+ )+ .await+ .unwrap();+ let (txn_b, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("b"),+ &mutation_response("Status", "b"),+ )+ .await+ .unwrap();+ assert_ne!(txn_a, txn_b);++ // B settles first: nothing flushes (A still pending ahead of it),+ // and B's real value stays visible over A's pending layer.+ let commit_b = engine+ .commit_optimistic_write(+ txn_b,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("b"),+ &mutation_response("Status", "b!"),+ )+ .await+ .unwrap();+ assert!(commit_b.changed.is_empty(), "no durable flush yet");+ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("b!"));+ assert_eq!(+ durable_display_name(&engine).await.as_deref(),+ Some("Status")+ );++ // A settles second: settling the earlier layer must not clobber the+ // later one. The visible value stays B's; the flush persists both in+ // order (B's response wins the shared field).+ let commit_a = engine+ .commit_optimistic_write(+ txn_a,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("a"),+ &mutation_response("Status", "a!"),+ )+ .await+ .unwrap();+ assert!(commit_a.affected_ops.is_empty(), "visible data unchanged");+ assert!(+ commit_a+ .changed+ .contains(&EntityKey(PROPERTY_KEY.to_string()))+ );++ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("b!"));+ });+}++#[test]+fn rollback_of_earlier_layer_keeps_later_success() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ let (txn_a, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("a"),+ &mutation_response("Status", "a"),+ )+ .await+ .unwrap();+ let (txn_b, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("b"),+ &mutation_response("Status", "b"),+ )+ .await+ .unwrap();++ // B succeeds first; A then fails. The failed tombstone unblocks the+ // prefix and B's real response is what persists.+ engine+ .commit_optimistic_write(+ txn_b,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("b"),+ &mutation_response("Status", "b!"),+ )+ .await+ .unwrap();+ let rollback = engine.rollback_optimistic_write(txn_a).await.unwrap();+ // A's contribution was masked by B → visible data unchanged.+ assert!(rollback.affected_ops.is_empty());+ // The flush persisted B's committed layer.+ assert!(+ rollback+ .changed+ .contains(&EntityKey(PROPERTY_KEY.to_string()))+ );++ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("b!"));+ });+}++#[test]+fn different_fields_on_same_record_compose() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ read_hit(&mut engine, Some(1)).await;++ // Layer A renames; layer B (pending) changes the value.+ let (txn_a, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("todo"),+ &json!({ "setEntityProperty": {+ "id": "prop-1",+ "displayName": "Stage",+ "value": { "kind": "String", "stringValue": "todo" }+ }}),+ )+ .await+ .unwrap();+ let (_txn_b, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &json!({ "setEntityProperty": {+ "id": "prop-1",+ "displayName": "Stage",+ "value": { "kind": "String", "stringValue": "doing" }+ }}),+ )+ .await+ .unwrap();++ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["displayName"], json!("Stage"));+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("doing"));++ // A commits while B remains pending: B's pending layer stays+ // visible over the committed base.+ engine+ .commit_optimistic_write(+ txn_a,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("todo"),+ &json!({ "setEntityProperty": {+ "id": "prop-1",+ "displayName": "Stage",+ "value": { "kind": "String", "stringValue": "todo" }+ }}),+ )+ .await+ .unwrap();+ let data = read_hit(&mut engine, Some(1)).await;+ assert_eq!(property_of(&data)["value"]["stringValue"], json!("doing"));+ assert_eq!(+ durable_display_name(&engine).await.as_deref(),+ Some("Stage")+ );+ });+}++#[test]+fn unknown_transaction_ids_error() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ assert!(matches!(+ engine.rollback_optimistic_write(42).await,+ Err(EngineError::UnknownTransaction(42))+ ));+ assert!(matches!(+ engine+ .commit_optimistic_write(+ 7,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("x"),+ &mutation_response("Status", "x"),+ )+ .await,+ Err(EngineError::UnknownTransaction(7))+ ));+ });+}++#[test]+fn clear_discards_pending_layers() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ let (txn, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();++ engine.clear().await.unwrap();+ let read = engine+ .read_query(None, QUERY, Some("Soup"), &query_vars())+ .await+ .unwrap();+ assert!(matches!(read, ReadResult::Miss));+ // The layer is gone; settling it later is an error, never a write.+ assert!(matches!(+ engine.rollback_optimistic_write(txn).await,+ Err(EngineError::UnknownTransaction(_))+ ));+ });+}++#[test]+fn identity_reset_discards_pending_layers() {+ block_on(async {+ let mut engine = engine_with_base("Status", "todo").await;+ engine+ .write_query(+ None,+ QUERY,+ Some("Soup"),+ &query_vars(),+ &soup_page("Status", "todo"),+ Some("user-1"),+ )+ .await+ .unwrap();++ let (txn, _) = engine+ .begin_optimistic_write(+ None,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await+ .unwrap();++ // A response for another user silently wipes the cache — including+ // the pending optimistic layer.+ let write = engine+ .write_query(+ None,+ QUERY,+ Some("Soup"),+ &query_vars(),+ &json!({+ "user": {+ "id": "user-2",+ "soup": { "items": [], "hasMore": false }+ }+ }),+ Some("user-2"),+ )+ .await+ .unwrap();+ assert!(write.reset);+ assert!(matches!(+ engine+ .commit_optimistic_write(+ txn,+ MUTATION,+ Some("SetEntityProperty"),+ &mutation_vars("doing"),+ &mutation_response("Status", "doing"),+ )+ .await,+ Err(EngineError::UnknownTransaction(_))+ ));+ });+}diff --git a/crates/client/cache-core/tests/roundtrip.rs b/crates/client/cache-core/tests/roundtrip.rsindex 0f0989dbe4..922dcb9004 100644--- a/crates/client/cache-core/tests/roundtrip.rs+++ b/crates/client/cache-core/tests/roundtrip.rs@@ -51,6 +51,7 @@ query Soup($input: SoupInput!) {}fragment SoupPropertyFields on GraphqlSoupProperty {+ idpropertyDefinitionIddisplayNamedataType@@ -105,6 +106,7 @@ fn response_data() -> Json {"updatedAt": "2026-07-01T00:00:00Z","properties": [{+ "id": "entity-prop-1","propertyDefinitionId": "prop-1","displayName": "Status","dataType": "select",@@ -176,6 +178,7 @@ fn normalizes_expected_records() {"GraphqlSoupDocument:doc-1","GraphqlSoupItem:ch-1","GraphqlSoupItem:doc-1",+ "GraphqlSoupProperty:entity-prop-1","GraphqlUser:user-1","ROOT_QUERY",]@@ -189,10 +192,11 @@ fn normalizes_expected_records() {));assert!(!doc_record.fields.contains_key("documentName"));- // Properties embedded (not their own records), message keyed by messageId.+ // Property assignments and messages are normalized by their ids.assert!(matches!(doc_record.fields.get("properties"),- Some(CacheValue::List(items)) if matches!(&items[0], CacheValue::Object(_))+ Some(CacheValue::List(items))+ if matches!(&items[0], CacheValue::Ref(k) if k.0 == "GraphqlSoupProperty:entity-prop-1")));let channel = &records[&EntityKey("GraphqlSoupChannel:ch-1".into())];assert!(matches!(@@ -238,6 +242,7 @@ fn round_trip_reproduces_response() {"GraphqlSoupDocument:doc-1","GraphqlSoupItem:ch-1","GraphqlSoupItem:doc-1",+ "GraphqlSoupProperty:entity-prop-1","GraphqlUser:user-1","ROOT_QUERY",]diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rsindex 9203f9dd42..bbb6e82049 100644--- a/crates/client/cache-wasm/src/shell.rs+++ b/crates/client/cache-wasm/src/shell.rs@@ -58,6 +58,22 @@ struct JsWriteResult {reset: bool,}+#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct JsOptimisticWriteResult {+ transaction_id: String,+ changed: Vec<String>,+ affected_ops: Vec<String>,+ reset: bool,+}++/// Transaction ids cross the boundary as strings (JS numbers lose precision+/// past 2^53; ids are opaque to the host anyway).+fn parse_transaction_id(id: &str) -> Result<u64, JsValue> {+ id.parse::<u64>()+ .map_err(|_| err_js(format!("invalid optimistic transaction id `{id}`")))+}+#[wasm_bindgen]pub struct CacheEngine {engine: Rc<Mutex<Engine<IdbStorage>>>,@@ -190,6 +206,100 @@ impl CacheEngine {})}+ /// Installs an in-memory optimistic layer from a mutation's optimistic+ /// response; persists nothing. Resolves to `{transactionId: string,+ /// changed: string[], affectedOps: string[], reset: false}` where+ /// `changed`/`affectedOps` reflect *visible* (composed-view) changes.+ #[wasm_bindgen(js_name = beginOptimisticWrite)]+ pub fn begin_optimistic_write(+ &self,+ origin_op_id: Option<String>,+ query: String,+ operation_name: Option<String>,+ variables: JsValue,+ data: JsValue,+ ) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let vars = parse_variables(variables)?;+ let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;+ let origin = origin_op_id.map(|name| ops.borrow_mut().intern(&name));+ let mut engine = engine.lock().await;+ let (transaction, result) = engine+ .begin_optimistic_write(origin, &query, operation_name.as_deref(), &vars, &data)+ .await+ .map_err(err_js)?;+ to_js(&JsOptimisticWriteResult {+ transaction_id: transaction.to_string(),+ changed: result.changed.into_iter().map(|k| k.0).collect(),+ affected_ops: ops.borrow().names(result.affected_ops),+ reset: result.reset,+ })+ })+ }++ /// Atomically replaces a pending optimistic layer with the real network+ /// response and flushes any contiguous settled layers durably. Resolves+ /// to a write result whose `changed` keys are the *durably* changed+ /// records (cross-instance broadcast) and whose `affectedOps` reflect+ /// visible changes. Rejects on unknown/settled transaction ids.+ #[wasm_bindgen(js_name = commitOptimisticWrite)]+ pub fn commit_optimistic_write(+ &self,+ transaction_id: String,+ query: String,+ operation_name: Option<String>,+ variables: JsValue,+ data: JsValue,+ ) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let transaction = parse_transaction_id(&transaction_id)?;+ let vars = parse_variables(variables)?;+ let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;+ let mut engine = engine.lock().await;+ let result = engine+ .commit_optimistic_write(+ transaction,+ &query,+ operation_name.as_deref(),+ &vars,+ &data,+ )+ .await+ .map_err(err_js)?;+ to_js(&JsWriteResult {+ changed: result.changed.into_iter().map(|k| k.0).collect(),+ affected_ops: ops.borrow().names(result.affected_ops),+ reset: result.reset,+ })+ })+ }++ /// Removes a pending optimistic layer's contribution (mutation failed)+ /// and flushes any now-contiguous settled layers. Result semantics match+ /// [`commitOptimisticWrite`](Self::commit_optimistic_write).+ #[wasm_bindgen(js_name = rollbackOptimisticWrite)]+ pub fn rollback_optimistic_write(&self, transaction_id: String) -> js_sys::Promise {+ let engine = self.engine.clone();+ let ops = self.ops.clone();+ future_to_promise(async move {+ let transaction = parse_transaction_id(&transaction_id)?;+ let mut engine = engine.lock().await;+ let result = engine+ .rollback_optimistic_write(transaction)+ .await+ .map_err(err_js)?;+ to_js(&JsWriteResult {+ changed: result.changed.into_iter().map(|k| k.0).collect(),+ affected_ops: ops.borrow().names(result.affected_ops),+ reset: result.reset,+ })+ })+ }+/// Evicts externally-changed records from the hot tier (cross-tab/// broadcasts, push invalidation). Resolves to the affected local/// operation ids.diff --git a/crates/client/cache-wasm/tests/web.rs b/crates/client/cache-wasm/tests/web.rsindex 8f72a68c4d..6fc135ccdf 100644--- a/crates/client/cache-wasm/tests/web.rs+++ b/crates/client/cache-wasm/tests/web.rs@@ -85,3 +85,122 @@ async fn write_then_read_through_js_boundary() {JsFuture::from(engine.close()).await.unwrap();destroy_cache("wasm-shell-test".into()).await.unwrap();}++const PROPERTY_QUERY: &str = r#"query Soup($input: SoupInput!) {+ user { id soup(input: $input) { hasMore items { id entity {+ __typename+ ... on GraphqlSoupDocument { id properties { id displayName } }+ } } } }+}"#;++const PROPERTY_MUTATION: &str = r#"mutation SetEntityProperty($input: SetEntityPropertyInput!) {+ setEntityProperty(input: $input) { id displayName }+}"#;++#[wasm_bindgen_test]+async fn optimistic_write_round_trip() {+ destroy_cache("wasm-shell-optimistic".into()).await.unwrap();+ let engine = open_cache("wasm-shell-optimistic".into(), None)+ .await+ .unwrap();++ let vars = serde_json::json!({"input": {"limit": 1}});+ let base = serde_json::json!({+ "user": { "id": "user-1", "soup": { "hasMore": false, "items": [{+ "id": "item-1",+ "entity": {+ "__typename": "GraphqlSoupDocument",+ "id": "doc-1",+ "properties": [{ "id": "prop-1", "displayName": "Status" }]+ }+ }] } }+ });+ JsFuture::from(engine.write_query(+ None,+ PROPERTY_QUERY.into(),+ Some("Soup".into()),+ js(vars.clone()),+ js(base),+ None,+ ))+ .await+ .unwrap();+ // Register op 1 against the property record.+ let read = JsFuture::from(engine.read_query(+ Some("tab1:1".into()),+ PROPERTY_QUERY.into(),+ Some("Soup".into()),+ js(vars.clone()),+ ))+ .await+ .unwrap();+ let read: serde_json::Value = serde_wasm_bindgen::from_value(read).unwrap();+ assert_eq!(read["kind"], "hit");++ let mutation_vars = serde_json::json!({"input": {+ "entityType": "DOCUMENT",+ "entityId": "doc-1",+ "propertyDefinitionId": "def-1",+ "value": { "string": "x" }+ }});++ // Begin: op 1 is affected, a string transaction id comes back.+ let begin = JsFuture::from(engine.begin_optimistic_write(+ None,+ PROPERTY_MUTATION.into(),+ Some("SetEntityProperty".into()),+ js(mutation_vars.clone()),+ js(serde_json::json!({ "setEntityProperty": { "id": "prop-1", "displayName": "Stage" } })),+ ))+ .await+ .unwrap();+ let begin: serde_json::Value = serde_wasm_bindgen::from_value(begin).unwrap();+ let txn = begin["transactionId"].as_str().unwrap().to_string();+ assert_eq!(begin["affectedOps"], serde_json::json!(["tab1:1"]));+ assert_eq!(+ begin["changed"],+ serde_json::json!(["GraphqlSoupProperty:prop-1"])+ );++ // The optimistic layer is visible through reads.+ let read = JsFuture::from(engine.read_query(+ Some("tab1:1".into()),+ PROPERTY_QUERY.into(),+ Some("Soup".into()),+ js(vars.clone()),+ ))+ .await+ .unwrap();+ let read: serde_json::Value = serde_wasm_bindgen::from_value(read).unwrap();+ assert_eq!(+ read["data"]["user"]["soup"]["items"][0]["entity"]["properties"][0]["displayName"],+ serde_json::json!("Stage")+ );++ // Commit with the real response; the layer flushes durably.+ let commit = JsFuture::from(engine.commit_optimistic_write(+ txn.clone(),+ PROPERTY_MUTATION.into(),+ Some("SetEntityProperty".into()),+ js(mutation_vars.clone()),+ js(serde_json::json!({ "setEntityProperty": { "id": "prop-1", "displayName": "Stage!" } })),+ ))+ .await+ .unwrap();+ let commit: serde_json::Value = serde_wasm_bindgen::from_value(commit).unwrap();+ assert_eq!(+ commit["changed"],+ serde_json::json!(["GraphqlSoupProperty:prop-1"])+ );+ assert_eq!(commit["affectedOps"], serde_json::json!(["tab1:1"]));++ // Settled transactions reject further commits/rollbacks.+ let err = JsFuture::from(engine.rollback_optimistic_write(txn)).await;+ assert!(err.is_err());+ // Malformed ids reject too.+ let err = JsFuture::from(engine.rollback_optimistic_write("not-a-number".into())).await;+ assert!(err.is_err());++ JsFuture::from(engine.close()).await.unwrap();+ destroy_cache("wasm-shell-optimistic".into()).await.unwrap();+}diff --git a/crates/complete_graph/AGENTS.md b/crates/complete_graph/AGENTS.mdindex 5efec3bea4..afd3963d55 100644--- a/crates/complete_graph/AGENTS.md+++ b/crates/complete_graph/AGENTS.md@@ -19,9 +19,9 @@ Clients key cache records by `__typename:id`. Consequences:can appear, across all queries, arguments, and parent objects.- **Only name a field `id` when it is the object's global identity.** If atype carries a reference to something else's id, name it accordingly:- - `GraphqlSoupProperty` exposes `propertyDefinitionId`, **not** `id` — a- property instance's `value` is per-entity, while the definition id is- shared. Naming it `id` would merge property values across entities.+ - `GraphqlSoupProperty.id` is the globally unique entity-property assignment+ id. `propertyDefinitionId` remains separate because definitions are shared+ while assignment values are per-entity.- `GraphqlSoupChannelMessage.id` (renamed from `messageId`) — it *is* themessage's identity, so it uses the reserved name.- **Types without an `id` field are embedded** inline in their parentdiff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rsindex 13957b39b7..a7d2f95ad6 100644--- a/crates/complete_graph/src/lib.rs+++ b/crates/complete_graph/src/lib.rs@@ -9,11 +9,12 @@ mod sdl_test;pub use graphql_common::GraphqlSoupRequestParts;pub use graphql_notification::{- EntityNotificationsKey, EntityNotificationsLoader, SoupNotificationEdgeReader,- entity_notifications_loader,+ EntityNotificationsLoader, SoupNotificationEdgeReader, entity_notifications_loader,};pub use graphql_properties::{- EntityPropertiesKey, EntityPropertiesLoader, SoupPropertyEdgeReader, entity_properties_loader,+ EntityPropertiesLoader, EntityPropertyWriter, PropertiesEntityPropertyWriter,+ PropertiesMutationRoot, PropertiesSoupPropertyEdgeReader, SoupPropertyEdgeReader,+ entity_properties_loader,};pub use graphql_soup::SharedSoupService;pub use schema::{diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rsindex cc34610c70..b46d120e08 100644--- a/crates/complete_graph/src/schema.rs+++ b/crates/complete_graph/src/schema.rs@@ -3,7 +3,7 @@ mod test;use std::{marker::PhantomData, sync::Arc};-use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};+use async_graphql::{Context, EmptySubscription, Object, Schema};use axum::extract::FromRef;use axum_extra::extract::Cached;use email::{@@ -12,6 +12,8 @@ use email::{};use entity_access::domain::ports::{EntityAccessService, NoOpEntityAccessService};use graphql_common::extract_part;+use graphql_notification::{NoOpSoupNotificationEdgeReader, SoupNotificationEdgeReader};+use graphql_properties::{EntityPropertyWriter, NoOpEntityPropertyWriter, PropertiesMutationRoot};use graphql_soup::{SharedSoupService, SoupInput, SoupPage, resolve_soup};use model_user::axum_extractor::MacroUserExtractor;use soup::domain::ports::{NoOpSoupService, SoupService};@@ -19,18 +21,25 @@ use soup::domain::ports::{NoOpSoupService, SoupService};/// GraphQL Soup schema type.////// `S` is the soup service, `E` the email service, `EAS` the entity access-/// service, and `St` the embedding axum router state that can hand out the-/// email router state and entity access service for the lazy extractors.-pub type SoupSchema<S, E, EAS, St> =- Schema<SoupQueryRoot<S, E, EAS, St>, EmptyMutation, EmptySubscription>;+/// service, `St` the embedding axum router state, `W` the property mutation+/// writer, and `NR` the notification edge reader.+pub type SoupSchema<S, E, EAS, St, W, NR> =+ Schema<SoupQueryRoot<S, E, EAS, St, NR>, PropertiesMutationRoot<W>, EmptySubscription>;/// GraphQL Soup schema type backed by a shared soup service.-pub type SharedSoupSchema<S, E, EAS, St> = SoupSchema<SharedSoupService<S>, E, EAS, St>;+pub type SharedSoupSchema<S, E, EAS, St, W, NR> =+ SoupSchema<SharedSoupService<S>, E, EAS, St, W, NR>;/// GraphQL Soup schema type backed by the no-op services, used only for/// SDL export or introspection.-pub type SchemaOnlySoupSchema =- SoupSchema<NoOpSoupService, NoOpEmailService, NoOpEntityAccessService, SchemaOnlyState>;+pub type SchemaOnlySoupSchema = SoupSchema<+ NoOpSoupService,+ NoOpEmailService,+ NoOpEntityAccessService,+ SchemaOnlyState,+ NoOpEntityPropertyWriter,+ NoOpSoupNotificationEdgeReader,+>;/// Axum-style state used only to construct the GraphQL schema for SDL export.#[derive(Clone, Copy, Debug, Default)]@@ -50,15 +59,15 @@ impl FromRef<SchemaOnlyState> for Arc<NoOpEntityAccessService> {/// Zero-sized marker tying the query objects to the email/entity-access/state/// generics without requiring values of those types.-type ServicesMarker<E, EAS, St> = PhantomData<fn() -> (E, EAS, St)>;+type ServicesMarker<E, EAS, St, NR> = PhantomData<fn() -> (E, EAS, St, NR)>;/// Root GraphQL query object for Soup.-pub struct SoupQueryRoot<S, E, EAS, St> {+pub struct SoupQueryRoot<S, E, EAS, St, NR> {service: S,- _marker: ServicesMarker<E, EAS, St>,+ _marker: ServicesMarker<E, EAS, St, NR>,}-impl<S, E, EAS, St> SoupQueryRoot<S, E, EAS, St> {+impl<S, E, EAS, St, NR> SoupQueryRoot<S, E, EAS, St, NR> {/// Create a root GraphQL query object.pub fn new(service: S) -> Self {Self {@@ -71,9 +80,9 @@ impl<S, E, EAS, St> SoupQueryRoot<S, E, EAS, St> {/// The authenticated user (viewer). All user-scoped data hangs off this/// object so clients (and their normalized caches) observe data ownership/// structurally rather than implicitly through the session.-pub struct GraphqlUser<S, E, EAS, St> {+pub struct GraphqlUser<S, E, EAS, St, NR> {service: S,- _marker: ServicesMarker<E, EAS, St>,+ _marker: ServicesMarker<E, EAS, St, NR>,}/// Build a GraphQL schema for Soup suitable for SDL export or introspection.@@ -82,7 +91,9 @@ pub fn build_schema() -> SchemaOnlySoupSchema {}/// Build a GraphQL schema for Soup backed by the provided service.-pub fn build_schema_with_service<S, E, EAS, St>(service: S) -> SoupSchema<S, E, EAS, St>+pub fn build_schema_with_service<S, E, EAS, St, W, NR>(+ service: S,+) -> SoupSchema<S, E, EAS, St, W, NR>whereS: SoupService + Clone,E: EmailService,@@ -90,17 +101,21 @@ whereSt: Clone + Send + Sync + 'static,EmailRouterState<E>: FromRef<St>,Arc<EAS>: FromRef<St>,+ W: EntityPropertyWriter,+ NR: SoupNotificationEdgeReader,{Schema::build(SoupQueryRoot::new(service),- EmptyMutation,+ PropertiesMutationRoot::<W>::new(),EmptySubscription,).finish()}/// Build a GraphQL schema for Soup backed by an `Arc`-shared service.-pub fn build_schema_from_arc<S, E, EAS, St>(service: Arc<S>) -> SharedSoupSchema<S, E, EAS, St>+pub fn build_schema_from_arc<S, E, EAS, St, W, NR>(+ service: Arc<S>,+) -> SharedSoupSchema<S, E, EAS, St, W, NR>whereS: SoupService,E: EmailService,@@ -108,12 +123,14 @@ whereSt: Clone + Send + Sync + 'static,EmailRouterState<E>: FromRef<St>,Arc<EAS>: FromRef<St>,+ W: EntityPropertyWriter,+ NR: SoupNotificationEdgeReader,{build_schema_with_service(SharedSoupService::new(service))}#[Object]-impl<S, E, EAS, St> SoupQueryRoot<S, E, EAS, St>+impl<S, E, EAS, St, NR> SoupQueryRoot<S, E, EAS, St, NR>whereS: SoupService + Clone,E: EmailService,@@ -121,9 +138,10 @@ whereSt: Clone + Send + Sync + 'static,EmailRouterState<E>: FromRef<St>,Arc<EAS>: FromRef<St>,+ NR: SoupNotificationEdgeReader,{/// The authenticated user.- async fn user(&self) -> GraphqlUser<S, E, EAS, St> {+ async fn user(&self) -> GraphqlUser<S, E, EAS, St, NR> {GraphqlUser {service: self.service.clone(),_marker: PhantomData,@@ -132,7 +150,7 @@ where}#[Object(name = "GraphqlUser")]-impl<S, E, EAS, St> GraphqlUser<S, E, EAS, St>+impl<S, E, EAS, St, NR> GraphqlUser<S, E, EAS, St, NR>whereS: SoupService,E: EmailService,@@ -140,6 +158,7 @@ whereSt: Clone + Send + Sync + 'static,EmailRouterState<E>: FromRef<St>,Arc<EAS>: FromRef<St>,+ NR: SoupNotificationEdgeReader,{/// Stable id of the authenticated user.async fn id(&self, ctx: &Context<'_>) -> async_graphql::Result<async_graphql::ID> {@@ -149,7 +168,11 @@ where}/// Fetch a page of Soup items using the existing Soup filter AST format.- async fn soup(&self, ctx: &Context<'_>, input: SoupInput) -> async_graphql::Result<SoupPage> {- resolve_soup::<S, E, EAS, St>(&self.service, ctx, input).await+ async fn soup(+ &self,+ ctx: &Context<'_>,+ input: SoupInput,+ ) -> async_graphql::Result<SoupPage<NR>> {+ resolve_soup::<S, E, EAS, St, NR>(&self.service, ctx, input).await}}diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rsindex 7a78ca4eb4..a6978d3fe2 100644--- a/crates/complete_graph/src/schema/test.rs+++ b/crates/complete_graph/src/schema/test.rs@@ -262,8 +262,14 @@ impl FromRef<TestState> for Arc<CountingEntityAccessService> {}struct TestHarness {- schema:- SoupSchema<NoOpSoupService, CountingEmailService, CountingEntityAccessService, TestState>,+ schema: SoupSchema<+ NoOpSoupService,+ CountingEmailService,+ CountingEntityAccessService,+ TestState,+ NoOpEntityPropertyWriter,+ NoOpSoupNotificationEdgeReader,+ >,state: TestState,inbox_calls: Arc<AtomicUsize>,team_calls: Arc<AtomicUsize>,diff --git a/crates/graphql_notification/Cargo.toml b/crates/graphql_notification/Cargo.tomlindex de0efb967e..12b8eaa671 100644--- a/crates/graphql_notification/Cargo.toml+++ b/crates/graphql_notification/Cargo.toml@@ -6,9 +6,9 @@ publish = false[dependencies]async-graphql = { workspace = true, features = ["dataloader"] }-async-trait = { workspace = true }graphql_common = { path = "../graphql_common" }macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }notification = { path = "../notification" }rootcause = { workspace = true }serde_json = { workspace = true }diff --git a/crates/graphql_notification/src/lib.rs b/crates/graphql_notification/src/lib.rsindex 8de5cf1693..57286e4641 100644--- a/crates/graphql_notification/src/lib.rs+++ b/crates/graphql_notification/src/lib.rs@@ -6,7 +6,7 @@ mod loaders;mod objects;pub use loaders::{- EntityNotificationsKey, EntityNotificationsLoader, SoupNotificationEdgeReader,+ EntityNotificationsLoader, NoOpSoupNotificationEdgeReader, SoupNotificationEdgeReader,entity_notifications_loader,};pub use objects::{GraphqlSoupNotification, load_entity_notifications};diff --git a/crates/graphql_notification/src/loaders.rs b/crates/graphql_notification/src/loaders.rsindex 245ad49e34..ea34e2677c 100644--- a/crates/graphql_notification/src/loaders.rs+++ b/crates/graphql_notification/src/loaders.rs@@ -6,60 +6,53 @@ use notification::domain::models::{UserNotificationRow,request::{NotificationEntityRef, NotificationItemType},};+use rootcause::markers::{Cloneable, Dynamic};-/// Key for loading notifications attached to an entity.-#[derive(Debug, Clone, Hash, PartialEq, Eq)]-pub struct EntityNotificationsKey {- /// Entity type key used by the notification service.- pub entity_type: String,- /// Entity ID used by the notification service.- pub entity_id: String,-}--impl EntityNotificationsKey {- fn notification_item_type(&self) -> Result<NotificationItemType, rootcause::Report> {- match self.entity_type.as_str() {- "email" | "email_thread" => Ok(NotificationItemType::Email),- "message" | "channel_message" => Ok(NotificationItemType::Message),- "channel" => Ok(NotificationItemType::Channel),- "document" => Ok(NotificationItemType::Document),- "project" => Ok(NotificationItemType::Project),- "chat" => Ok(NotificationItemType::Chat),- "call" => Ok(NotificationItemType::Call),- "task" => Ok(NotificationItemType::Task),- "github" | "foreign_entity" => Ok(NotificationItemType::Github),- other => Err(rootcause::report!(- "unsupported notification entity type {other}"- )),- }+fn notification_item_type(+ entity_type: model_entity::EntityType,+) -> Result<NotificationItemType, rootcause::Report> {+ use model_entity::EntityType;+ match entity_type {+ EntityType::EmailThread => Ok(NotificationItemType::Email),+ EntityType::ChannelMessage => Ok(NotificationItemType::Message),+ EntityType::Channel => Ok(NotificationItemType::Channel),+ EntityType::Document => Ok(NotificationItemType::Document),+ EntityType::Project => Ok(NotificationItemType::Project),+ EntityType::Chat => Ok(NotificationItemType::Chat),+ EntityType::Call => Ok(NotificationItemType::Call),+ EntityType::ForeignEntity => Ok(NotificationItemType::Github),+ other => Err(rootcause::report!(+ "unsupported notification entity type {other}"+ )),}}-/// Object-safe reader used by GraphQL notification edges.-#[async_trait::async_trait]+/// Reader used by GraphQL notification edges.pub trait SoupNotificationEdgeReader: Send + Sync + 'static {/// Load notifications for the requested entity keys.- async fn get_notifications(- &self,+ fn get_notifications<'a>(+ &'a self,user_id: MacroUserIdStr<'static>,- keys: Vec<EntityNotificationsKey>,- ) -> Result<- HashMap<EntityNotificationsKey, Vec<UserNotificationRow<serde_json::Value>>>,- rootcause::Report,- >;+ keys: Vec<model_entity::Entity<'static>>,+ ) -> impl Future<+ Output = Result<+ HashMap<model_entity::Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>,+ rootcause::Report,+ >,+ > + Send+ + 'a;}-#[async_trait::async_trait]-impl<T> SoupNotificationEdgeReader for T+impl<T> SoupNotificationEdgeReader for Arc<T>whereT: notification::domain::service::NotificationReader,{async fn get_notifications(&self,user_id: MacroUserIdStr<'static>,- keys: Vec<EntityNotificationsKey>,+ keys: Vec<model_entity::Entity<'static>>,) -> Result<- HashMap<EntityNotificationsKey, Vec<UserNotificationRow<serde_json::Value>>>,+ HashMap<model_entity::Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>,rootcause::Report,> {let mut result = keys@@ -74,8 +67,8 @@ whereOk((key.clone(),NotificationEntityRef {- entity_type: key.notification_item_type()?,- id: key.entity_id.clone(),+ entity_type: notification_item_type(key.entity_type)?,+ id: key.entity_id.to_string(),},))})@@ -101,42 +94,76 @@ where}}+/// Notification reader used by schema-only GraphQL construction.+#[derive(Clone, Copy, Debug, Default)]+pub struct NoOpSoupNotificationEdgeReader;++impl SoupNotificationEdgeReader for NoOpSoupNotificationEdgeReader {+ async fn get_notifications(+ &self,+ _user_id: MacroUserIdStr<'static>,+ keys: Vec<model_entity::Entity<'static>>,+ ) -> Result<+ HashMap<model_entity::Entity<'static>, Vec<UserNotificationRow<serde_json::Value>>>,+ rootcause::Report,+ > {+ Ok(keys.iter().map(|key| (key.clone(), Vec::new())).collect())+ }+}+/// DataLoader for entity notification edges.-pub struct EntityNotificationsLoader {+pub struct EntityNotificationsLoader<R> {user_id: MacroUserIdStr<'static>,- reader: Arc<dyn SoupNotificationEdgeReader>,+ reader: R,}-impl EntityNotificationsLoader {+impl<R> EntityNotificationsLoader<R> {/// Create a new entity notifications DataLoader.- pub fn new(- user_id: MacroUserIdStr<'static>,- reader: Arc<dyn SoupNotificationEdgeReader>,- ) -> Self {+ pub fn new(user_id: MacroUserIdStr<'static>, reader: R) -> Self {Self { user_id, reader }}}-impl Loader<EntityNotificationsKey> for EntityNotificationsLoader {+impl<R> Loader<model_entity::OwnedEntity> for EntityNotificationsLoader<R>+where+ R: SoupNotificationEdgeReader,+{type Value = Vec<UserNotificationRow<serde_json::Value>>;- type Error = Arc<rootcause::Report>;+ type Error = rootcause::Report<Dynamic, Cloneable>;async fn load(&self,- keys: &[EntityNotificationsKey],- ) -> Result<HashMap<EntityNotificationsKey, Self::Value>, Self::Error> {- self.reader- .get_notifications(self.user_id.clone(), keys.to_vec())+ keys: &[model_entity::OwnedEntity],+ ) -> Result<HashMap<model_entity::OwnedEntity, Self::Value>, Self::Error> {+ let entities = keys+ .iter()+ .map(|key| key.as_entity().clone())+ .collect::<Vec<_>>();+ let loaded = self+ .reader+ .get_notifications(self.user_id.clone(), entities).await- .map_err(Arc::new)+ .map_err(|error| error.into_cloneable())?;++ Ok(keys+ .iter()+ .cloned()+ .map(|key| {+ let notifications = loaded.get(key.as_entity()).cloned().unwrap_or_default();+ (key, notifications)+ })+ .collect())}}/// Build a DataLoader for entity notification edges.-pub fn entity_notifications_loader(+pub fn entity_notifications_loader<R>(user_id: MacroUserIdStr<'static>,- reader: Arc<dyn SoupNotificationEdgeReader>,-) -> DataLoader<EntityNotificationsLoader> {+ reader: R,+) -> DataLoader<EntityNotificationsLoader<R>>+where+ R: SoupNotificationEdgeReader,+{DataLoader::new(EntityNotificationsLoader::new(user_id, reader),tokio::spawn,diff --git a/crates/graphql_notification/src/objects.rs b/crates/graphql_notification/src/objects.rsindex 2f2d44d61e..6ff88f54b7 100644--- a/crates/graphql_notification/src/objects.rs+++ b/crates/graphql_notification/src/objects.rs@@ -3,7 +3,7 @@ use graphql_common::GraphqlSoupEntityType;use notification::domain::models::UserNotificationRow;use serde_json::Value;-use crate::loaders::{EntityNotificationsKey, EntityNotificationsLoader};+use crate::loaders::{EntityNotificationsLoader, SoupNotificationEdgeReader};/// GraphQL notification attached to a Soup entity.pub struct GraphqlSoupNotification(UserNotificationRow<serde_json::Value>);@@ -61,13 +61,16 @@ impl GraphqlSoupNotification {/// Load the notifications attached to the given entity via the/// [`EntityNotificationsLoader`] stored in the GraphQL context.-pub async fn load_entity_notifications(- ctx: &Context<'_>,- key: EntityNotificationsKey,-) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- let loader = ctx.data::<DataLoader<EntityNotificationsLoader>>()?;+pub async fn load_entity_notifications<'a, R>(+ ctx: &'a Context<'a>,+ entity: model_entity::Entity<'static>,+) -> async_graphql::Result<Vec<GraphqlSoupNotification>>+where+ R: SoupNotificationEdgeReader,+{+ let loader = ctx.data::<DataLoader<EntityNotificationsLoader<R>>>()?;let notifications = loader- .load_one(key)+ .load_one(model_entity::OwnedEntity::from(entity)).await.map_err(|err| async_graphql::Error::new(err.to_string()))?.unwrap_or_default();diff --git a/crates/graphql_properties/Cargo.toml b/crates/graphql_properties/Cargo.tomlindex f20d3ffbc1..d11f96ddc8 100644--- a/crates/graphql_properties/Cargo.toml+++ b/crates/graphql_properties/Cargo.toml@@ -1,16 +1,18 @@[package]-name = "graphql_properties"-version = "0.1.0"edition = "2024"+name = "graphql_properties"publish = false+version = "0.1.0"[dependencies]async-graphql = { workspace = true, features = ["dataloader"] }-async-trait = { workspace = true }+chrono = { workspace = true }+entity_access = { path = "../entity_access", default-features = false }filter_ast = { path = "../filter_ast" }graphql_common = { path = "../graphql_common" }item_filters = { path = "../item_filters" }macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }models_properties = { path = "../models_properties" }models_soup = { path = "../models_soup" }properties = { path = "../properties", default-features = false, features = [@@ -19,4 +21,5 @@ properties = { path = "../properties", default-features = false, features = [rootcause = { workspace = true }tokio = { workspace = true }tracing = { workspace = true }+uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/graphql_properties/src/inputs.rs b/crates/graphql_properties/src/inputs.rsindex cc55e6777a..d38bd03901 100644--- a/crates/graphql_properties/src/inputs.rs+++ b/crates/graphql_properties/src/inputs.rs@@ -79,6 +79,21 @@ pub enum GraphqlPropertyEntityType {User,}+impl From<GraphqlPropertyEntityType> for models_properties::EntityType {+ fn from(value: GraphqlPropertyEntityType) -> Self {+ match value {+ GraphqlPropertyEntityType::Channel => Self::Channel,+ GraphqlPropertyEntityType::Chat => Self::Chat,+ GraphqlPropertyEntityType::Company => Self::Company,+ GraphqlPropertyEntityType::Document => Self::Document,+ GraphqlPropertyEntityType::Project => Self::Project,+ GraphqlPropertyEntityType::Task => Self::Task,+ GraphqlPropertyEntityType::Thread => Self::Thread,+ GraphqlPropertyEntityType::User => Self::User,+ }+ }+}+impl From<GraphqlPropertyEntityType> for PropertyEntityType {fn from(value: GraphqlPropertyEntityType) -> Self {match value {diff --git a/crates/graphql_properties/src/lib.rs b/crates/graphql_properties/src/lib.rsindex 53f7c7fa0d..d34e3eb5fd 100644--- a/crates/graphql_properties/src/lib.rs+++ b/crates/graphql_properties/src/lib.rs@@ -4,11 +4,17 @@mod inputs;mod loaders;+mod mutations;mod objects;pub use inputs::{GraphqlPropertiesBinaryExpr, GraphqlPropertiesExpr};pub use loaders::{- EntityPropertiesKey, EntityPropertiesLoader, SoupPropertyEdgeReader, entity_properties_loader,+ EntityPropertiesLoader, PropertiesSoupPropertyEdgeReader, SoupPropertyEdgeReader,+ entity_properties_loader,+};+pub use mutations::{+ EntityPropertyWriter, NoOpEntityPropertyWriter, PropertiesEntityPropertyWriter,+ PropertiesMutationRoot,};pub use objects::{GraphqlSoupProperty, GraphqlSoupPropertyEntityReference, GraphqlSoupPropertyValue,diff --git a/crates/graphql_properties/src/loaders.rs b/crates/graphql_properties/src/loaders.rsindex 1e82cb1cfd..9356384c2d 100644--- a/crates/graphql_properties/src/loaders.rs+++ b/crates/graphql_properties/src/loaders.rs@@ -1,57 +1,68 @@use std::{collections::HashMap, str::FromStr, sync::Arc};use async_graphql::dataloader::{DataLoader, Loader};+use entity_access::domain::models::ViewAccessLevel;+use entity_access::domain::ports::EntityAccessService;use macro_user_id::user_id::MacroUserIdStr;use models_soup::SoupProperty;+use rootcause::markers::{Cloneable, Dynamic};-/// Key for loading properties attached to an entity.-#[derive(Debug, Clone, Hash, PartialEq, Eq)]-pub struct EntityPropertiesKey {- /// Entity type key used by the property service.- pub entity_type: String,- /// Entity ID used by the property service.- pub entity_id: String,-}--impl EntityPropertiesKey {- fn property_entity_type(- &self,- ) -> Result<Option<models_properties::EntityType>, rootcause::Report> {- match self.entity_type.as_str() {- "email" | "email_thread" => Ok(Some(models_properties::EntityType::Thread)),- "crm_company" => Ok(Some(models_properties::EntityType::Company)),- "call" | "channel_message" | "channel_thread" | "foreign_entity" | "github" => Ok(None),- other => models_properties::EntityType::from_str(other)- .map(Some)- .map_err(|err| {- rootcause::report!("invalid entity type {other} for property edge: {err}")- }),- }+fn property_entity_type(+ entity_type: model_entity::EntityType,+) -> Option<models_properties::EntityType> {+ use model_entity::EntityType;+ match entity_type {+ EntityType::EmailThread => Some(models_properties::EntityType::Thread),+ EntityType::CrmCompany => Some(models_properties::EntityType::Company),+ EntityType::Call | EntityType::ChannelMessage | EntityType::ForeignEntity => None,+ other => models_properties::EntityType::from_str(other.as_ref()).ok(),}}-/// Object-safe reader used by GraphQL property edges.-#[async_trait::async_trait]+/// Reader used by GraphQL property edges.pub trait SoupPropertyEdgeReader: Send + Sync + 'static {/// Load properties for the requested entity keys on behalf of the given/// user. Entities the user cannot view yield an empty property list.- async fn get_properties(+ fn get_properties(&self,user_id: &MacroUserIdStr<'static>,- keys: Vec<EntityPropertiesKey>,- ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report>;+ keys: &[model_entity::Entity<'static>],+ ) -> impl Future<+ Output = Result<+ HashMap<model_entity::Entity<'static>, Vec<SoupProperty>>,+ rootcause::Report,+ >,+ > + Send;}-#[async_trait::async_trait]-impl<T> SoupPropertyEdgeReader for T+/// GraphQL property reader backed by the properties domain service and the+/// canonical entity access service.+pub struct PropertiesSoupPropertyEdgeReader<P, A> {+ properties_service: Arc<P>,+ entity_access_service: Arc<A>,+}++impl<P, A> PropertiesSoupPropertyEdgeReader<P, A> {+ /// Create a property edge reader from the services supplied by the+ /// application composition root.+ pub fn new(properties_service: Arc<P>, entity_access_service: Arc<A>) -> Self {+ Self {+ properties_service,+ entity_access_service,+ }+ }+}++impl<P, A> SoupPropertyEdgeReader for PropertiesSoupPropertyEdgeReader<P, A>where- T: properties::PropertiesService,+ P: properties::PropertiesService,+ A: EntityAccessService,{async fn get_properties(&self,user_id: &MacroUserIdStr<'static>,- keys: Vec<EntityPropertiesKey>,- ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report> {+ keys: &[model_entity::Entity<'static>],+ ) -> Result<HashMap<model_entity::Entity<'static>, Vec<SoupProperty>>, rootcause::Report> {let mut result = keys.iter().cloned()@@ -61,14 +72,25 @@ where// Mint a view receipt per entity; entities the caller cannot view are// skipped and keep their empty property list.let mut receipts = Vec::with_capacity(keys.len());- for key in &keys {- let Some(entity_type) = key.property_entity_type()? else {+ for key in keys {+ let Some(entity_type) = property_entity_type(key.entity_type) else {continue;};- match self- .mint_view_receipt(Some(user_id), &key.entity_id, entity_type)- .await- {+ let access_receipt = self+ .entity_access_service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ user_id,+ None,+ &key.entity_id,+ properties::access_entity_type(entity_type),+ )+ .await;+ match access_receipt.and_then(|receipt| {+ properties::PropertiesAccessReceipt::try_from_entity_access_receipt(+ receipt,+ entity_type,+ )+ }) {Ok(receipt) => receipts.push(receipt),Err(err) => {tracing::debug!(@@ -86,6 +108,7 @@ where}let properties_by_entity = self+ .properties_service.get_bulk_entity_properties(&receipts, Vec::new()).await.map_err(|err| rootcause::report!(err))?;@@ -93,12 +116,12 @@ where// Merge back under the original loader keys: the batch result is keyed// by the normalized entity type, which for alias keys ("email",// "email_thread", "crm_company") differs from the requested key.- for key in &keys {- let Ok(Some(entity_type)) = key.property_entity_type() else {+ for key in keys {+ let Some(entity_type) = property_entity_type(key.entity_type) else {continue;};let batch_key = properties::EntityPropertiesKey {- entity_id: key.entity_id.clone(),+ entity_id: key.entity_id.to_string(),entity_type,};if let Some(properties) = properties_by_entity.get(&batch_key) {@@ -114,37 +137,57 @@ where}/// DataLoader for entity property edges.-pub struct EntityPropertiesLoader {+pub struct EntityPropertiesLoader<R> {user_id: MacroUserIdStr<'static>,- reader: Arc<dyn SoupPropertyEdgeReader>,+ reader: R,}-impl EntityPropertiesLoader {+impl<R> EntityPropertiesLoader<R> {/// Create a new entity properties DataLoader scoped to the requesting user.- pub fn new(user_id: MacroUserIdStr<'static>, reader: Arc<dyn SoupPropertyEdgeReader>) -> Self {+ pub fn new(user_id: MacroUserIdStr<'static>, reader: R) -> Self {Self { user_id, reader }}}-impl Loader<EntityPropertiesKey> for EntityPropertiesLoader {+impl<R> Loader<model_entity::OwnedEntity> for EntityPropertiesLoader<R>+where+ R: SoupPropertyEdgeReader,+{type Value = Vec<SoupProperty>;- type Error = Arc<rootcause::Report>;+ type Error = rootcause::Report<Dynamic, Cloneable>;async fn load(&self,- keys: &[EntityPropertiesKey],- ) -> Result<HashMap<EntityPropertiesKey, Self::Value>, Self::Error> {- self.reader- .get_properties(&self.user_id, keys.to_vec())+ keys: &[model_entity::OwnedEntity],+ ) -> Result<HashMap<model_entity::OwnedEntity, Self::Value>, Self::Error> {+ let entities = keys+ .iter()+ .map(|key| key.as_entity().clone())+ .collect::<Vec<_>>();+ let loaded = self+ .reader+ .get_properties(&self.user_id, &entities).await- .map_err(Arc::new)+ .map_err(|error| error.into_cloneable())?;++ Ok(keys+ .iter()+ .cloned()+ .map(|key| {+ let properties = loaded.get(key.as_entity()).cloned().unwrap_or_default();+ (key, properties)+ })+ .collect())}}/// Build a DataLoader for entity property edges scoped to the requesting user.-pub fn entity_properties_loader(+pub fn entity_properties_loader<R>(user_id: MacroUserIdStr<'static>,- reader: Arc<dyn SoupPropertyEdgeReader>,-) -> DataLoader<EntityPropertiesLoader> {+ reader: R,+) -> DataLoader<EntityPropertiesLoader<R>>+where+ R: SoupPropertyEdgeReader,+{DataLoader::new(EntityPropertiesLoader::new(user_id, reader), tokio::spawn)}diff --git a/crates/graphql_properties/src/mutations.rs b/crates/graphql_properties/src/mutations.rsnew file mode 100644index 0000000000..83c4a79ca8--- /dev/null+++ b/crates/graphql_properties/src/mutations.rs@@ -0,0 +1,368 @@+use async_graphql::{Context, ID, Object};+use entity_access::domain::models::EditAccessLevel;+use entity_access::domain::ports::EntityAccessService;+use graphql_common::parse_id;+use macro_user_id::user_id::MacroUserIdStr;+use models_properties::api::requests::SetPropertyValue;+use models_properties::shared::EntityReference;+use models_soup::SoupProperty;+use properties::{PropertiesAccessReceipt, PropertiesService, access_entity_type};+use std::{marker::PhantomData, sync::Arc};+use uuid::Uuid;++use crate::{inputs::GraphqlPropertyEntityType, objects::GraphqlSoupProperty};++/// Mutation root for entity property writes.+#[derive(Default)]+pub struct PropertiesMutationRoot<T>(PhantomData<T>);++impl<T> PropertiesMutationRoot<T> {+ /// Create a mutation root for the configured property writer.+ pub fn new() -> Self {+ Self(PhantomData)+ }+}++/// GraphQL boundary for setting an entity property.+pub trait EntityPropertyWriter: Send + Sync + 'static {+ /// Set or attach one property on an entity.+ fn set_entity_property(+ &self,+ entity_type: models_properties::EntityType,+ entity_id: String,+ property_definition_id: Uuid,+ value: Option<SetPropertyValue>,+ ) -> impl Future<Output = Result<SoupProperty, rootcause::Report>> + Send;+}++/// Property writer used by schema-only GraphQL construction.+#[derive(Clone, Copy, Debug, Default)]+pub struct NoOpEntityPropertyWriter;++impl EntityPropertyWriter for NoOpEntityPropertyWriter {+ async fn set_entity_property(+ &self,+ _entity_type: models_properties::EntityType,+ _entity_id: String,+ _property_definition_id: Uuid,+ _value: Option<SetPropertyValue>,+ ) -> Result<SoupProperty, rootcause::Report> {+ Err(rootcause::report!("property writer is not configured"))+ }+}++/// Entity property writer backed by the properties and entity access services.+pub struct PropertiesEntityPropertyWriter<P, A> {+ properties_service: Arc<P>,+ entity_access_service: Arc<A>,+ user_id: MacroUserIdStr<'static>,+}++impl<P, A> PropertiesEntityPropertyWriter<P, A> {+ /// Create a writer for the authenticated caller.+ pub fn new(+ properties_service: Arc<P>,+ entity_access_service: Arc<A>,+ user_id: MacroUserIdStr<'static>,+ ) -> Self {+ Self {+ properties_service,+ entity_access_service,+ user_id,+ }+ }+}++impl<P, A> EntityPropertyWriter for PropertiesEntityPropertyWriter<P, A>+where+ P: PropertiesService,+ A: EntityAccessService,+{+ async fn set_entity_property(+ &self,+ entity_type: models_properties::EntityType,+ entity_id: String,+ property_definition_id: Uuid,+ value: Option<SetPropertyValue>,+ ) -> Result<SoupProperty, rootcause::Report> {+ let entity_access_receipt = self+ .entity_access_service+ .generate_entity_access_receipt::<EditAccessLevel>(+ &self.user_id,+ None,+ &entity_id,+ access_entity_type(entity_type),+ )+ .await+ .map_err(|err| rootcause::report!(err))?;+ let access = PropertiesAccessReceipt::try_from_entity_access_receipt(+ entity_access_receipt,+ entity_type,+ )+ .map_err(|err| rootcause::report!(err))?;++ let property = self+ .properties_service+ .set_entity_property(&access, property_definition_id, value)+ .await+ .map_err(|err| rootcause::report!(err))?;++ Ok(property.into())+ }+}++#[derive(async_graphql::InputObject)]+struct SetEntityPropertyInput {+ entity_type: GraphqlPropertyEntityType,+ entity_id: String,+ property_definition_id: ID,+ /// Omit or pass null to attach the property without a value.+ value: Option<GraphqlSetPropertyValue>,+}++#[derive(async_graphql::InputObject)]+struct GraphqlEntityReferenceInput {+ entity_type: GraphqlPropertyEntityType,+ entity_id: String,+ specific_message_id: Option<ID>,+}++impl GraphqlEntityReferenceInput {+ fn try_into_model(self) -> async_graphql::Result<EntityReference> {+ Ok(EntityReference {+ entity_type: self.entity_type.into(),+ entity_id: self.entity_id,+ specific_message_id: self+ .specific_message_id+ .map(|id| parse_id(id, "specificMessageId"))+ .transpose()?,+ })+ }+}++#[derive(async_graphql::OneofObject)]+enum GraphqlSetPropertyValue {+ Boolean(bool),+ Date(String),+ Number(f64),+ String(String),+ SelectOption(ID),+ MultiSelectOption(Vec<ID>),+ EntityReference(GraphqlEntityReferenceInput),+ MultiEntityReference(Vec<GraphqlEntityReferenceInput>),+ Link(String),+ MultiLink(Vec<String>),+}++impl GraphqlSetPropertyValue {+ fn try_into_model(self) -> async_graphql::Result<SetPropertyValue> {+ Ok(match self {+ Self::Boolean(value) => SetPropertyValue::Boolean { value },+ Self::Date(value) => SetPropertyValue::Date {+ value: chrono::DateTime::parse_from_rfc3339(&value)+ .map(|date| date.with_timezone(&chrono::Utc))+ .map_err(|err| {+ async_graphql::Error::new(format!(+ "invalid RFC3339 property date `{value}`: {err}"+ ))+ })?,+ },+ Self::Number(value) => SetPropertyValue::Number { value },+ Self::String(value) => SetPropertyValue::String { value },+ Self::SelectOption(option_id) => SetPropertyValue::SelectOption {+ option_id: parse_id(option_id, "selectOption")?,+ },+ Self::MultiSelectOption(option_ids) => SetPropertyValue::MultiSelectOption {+ option_ids: option_ids+ .into_iter()+ .map(|id| parse_id(id, "multiSelectOption"))+ .collect::<async_graphql::Result<_>>()?,+ },+ Self::EntityReference(reference) => SetPropertyValue::EntityReference {+ reference: reference.try_into_model()?,+ },+ Self::MultiEntityReference(references) => SetPropertyValue::MultiEntityReference {+ references: references+ .into_iter()+ .map(GraphqlEntityReferenceInput::try_into_model)+ .collect::<async_graphql::Result<_>>()?,+ },+ Self::Link(url) => SetPropertyValue::Link { url },+ Self::MultiLink(urls) => SetPropertyValue::MultiLink { urls },+ })+ }+}++#[Object]+impl<T> PropertiesMutationRoot<T>+where+ T: EntityPropertyWriter,+{+ /// Set or attach one property on an entity.+ async fn set_entity_property(+ &self,+ ctx: &Context<'_>,+ input: SetEntityPropertyInput,+ ) -> async_graphql::Result<GraphqlSoupProperty> {+ let writer = ctx.data::<T>()?;+ let property_definition_id =+ parse_id(input.property_definition_id, "propertyDefinitionId")?;+ let value = input+ .value+ .map(GraphqlSetPropertyValue::try_into_model)+ .transpose()?;++ let property = writer+ .set_entity_property(+ input.entity_type.into(),+ input.entity_id,+ property_definition_id,+ value,+ )+ .await+ .map_err(|err| async_graphql::Error::new(err.to_string()))?;++ Ok(property.into())+ }+}++#[cfg(test)]+mod tests {+ use std::sync::{Arc, Mutex};++ use async_graphql::{EmptySubscription, Object, Schema};++ use super::*;++ #[derive(Default)]+ struct QueryRoot;++ #[Object]+ impl QueryRoot {+ async fn health(&self) -> bool {+ true+ }+ }++ type CapturedWrite = (+ models_properties::EntityType,+ String,+ Uuid,+ Option<SetPropertyValue>,+ );++ #[derive(Clone)]+ struct CapturingWriter {+ write: Arc<Mutex<Option<CapturedWrite>>>,+ property: SoupProperty,+ }++ impl EntityPropertyWriter for CapturingWriter {+ async fn set_entity_property(+ &self,+ entity_type: models_properties::EntityType,+ entity_id: String,+ property_definition_id: Uuid,+ value: Option<SetPropertyValue>,+ ) -> Result<SoupProperty, rootcause::Report> {+ *self.write.lock().expect("capture mutex poisoned") =+ Some((entity_type, entity_id, property_definition_id, value));+ Ok(self.property.clone())+ }+ }++ #[tokio::test]+ async fn set_entity_property_forwards_to_writer() {+ let property_assignment_id = Uuid::from_u128(3);+ let property_definition_id = Uuid::from_u128(1);+ let option_id = Uuid::from_u128(2);+ let writer = CapturingWriter {+ write: Arc::default(),+ property: SoupProperty {+ id: property_assignment_id,+ definition: models_properties::service::property_definition::PropertyDefinition {+ id: property_definition_id,+ owner: models_properties::PropertyOwner::System,+ display_name: "Status".to_owned(),+ data_type: models_properties::DataType::SelectString,+ is_multi_select: false,+ specific_entity_type: Some(models_properties::EntityType::Task),+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ is_system: true,+ is_metadata: false,+ },+ value: Some(+ models_properties::service::property_value::PropertyValue::SelectOption(vec![+ option_id,+ ]),+ ),+ },+ };+ let writer_data = writer.clone();+ let schema = Schema::build(+ QueryRoot,+ PropertiesMutationRoot::<CapturingWriter>::new(),+ EmptySubscription,+ )+ .data(writer_data)+ .finish();+ let response = schema+ .execute(format!(+ r#"+ mutation {{+ setEntityProperty(input: {{+ entityType: TASK,+ entityId: "task-1",+ propertyDefinitionId: "{property_definition_id}",+ value: {{ selectOption: "{option_id}" }}+ }}) {{+ id+ propertyDefinitionId+ displayName+ dataType+ isMultiSelect+ specificEntityType+ isSystem+ isMetadata+ value {{+ kind+ selectOptionIds+ }}+ }}+ }}+ "#+ ))+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(+ response.data,+ async_graphql::value!({+ "setEntityProperty": {+ "id": property_assignment_id.to_string(),+ "propertyDefinitionId": property_definition_id.to_string(),+ "displayName": "Status",+ "dataType": "SELECT_STRING",+ "isMultiSelect": false,+ "specificEntityType": "TASK",+ "isSystem": true,+ "isMetadata": false,+ "value": {+ "kind": "SelectOption",+ "selectOptionIds": [option_id.to_string()],+ },+ }+ })+ );+ assert_eq!(+ writer.write.lock().expect("capture mutex poisoned").clone(),+ Some((+ models_properties::EntityType::Task,+ "task-1".to_string(),+ property_definition_id,+ Some(SetPropertyValue::SelectOption { option_id }),+ ))+ );+ }+}diff --git a/crates/graphql_properties/src/objects.rs b/crates/graphql_properties/src/objects.rsindex a829fe4a35..a497a312b6 100644--- a/crates/graphql_properties/src/objects.rs+++ b/crates/graphql_properties/src/objects.rs@@ -41,7 +41,7 @@ impl From<models_properties::DataType> for GraphqlSoupDataType {}}-/// GraphQL property attached to a Soup entity.+/// GraphQL property assignment attached to a Soup entity.pub struct GraphqlSoupProperty(SoupProperty);impl From<SoupProperty> for GraphqlSoupProperty {@@ -52,10 +52,12 @@ impl From<SoupProperty> for GraphqlSoupProperty {#[Object]impl GraphqlSoupProperty {- /// Id of the shared property *definition* — deliberately not named `id`:- /// a property instance has no global identity (its `value` is- /// per-entity), so it must never be treated as a cacheable entity.- /// Normalized caches key objects by the presence of an `id` field.+ /// Globally unique id of this property assignment.+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ /// Id of the shared property definition.async fn property_definition_id(&self) -> ID {ID(self.0.definition.id.to_string())}diff --git a/crates/graphql_soup/src/lib.rs b/crates/graphql_soup/src/lib.rsindex 0e136780cd..8e6e13f156 100644--- a/crates/graphql_soup/src/lib.rs+++ b/crates/graphql_soup/src/lib.rs@@ -11,13 +11,12 @@ mod resolvers;pub use graphql_common::{GraphqlSoupEntityType, GraphqlSoupRequestParts};pub use graphql_notification::{- EntityNotificationsKey, EntityNotificationsLoader, GraphqlSoupNotification,- SoupNotificationEdgeReader, entity_notifications_loader,+ EntityNotificationsLoader, GraphqlSoupNotification, SoupNotificationEdgeReader,+ entity_notifications_loader,};pub use graphql_properties::{- EntityPropertiesKey, EntityPropertiesLoader, GraphqlSoupProperty,- GraphqlSoupPropertyEntityReference, GraphqlSoupPropertyValue, SoupPropertyEdgeReader,- entity_properties_loader,+ EntityPropertiesLoader, GraphqlSoupProperty, GraphqlSoupPropertyEntityReference,+ GraphqlSoupPropertyValue, SoupPropertyEdgeReader, entity_properties_loader,};pub use inputs::{GraphqlSimpleSortMethod, SoupInput};pub use objects::{diff --git a/crates/graphql_soup/src/objects.rs b/crates/graphql_soup/src/objects.rsindex 84134f4a7b..6b6538f142 100644--- a/crates/graphql_soup/src/objects.rs+++ b/crates/graphql_soup/src/objects.rs@@ -1,7 +1,9 @@-use async_graphql::{Context, ID, Json, Object, SimpleObject, Union};+use std::marker::PhantomData;++use async_graphql::{Context, ID, Json, Object, Union};use graphql_common::GraphqlSoupEntityType;use graphql_notification::{- EntityNotificationsKey, GraphqlSoupNotification, load_entity_notifications,+ GraphqlSoupNotification, SoupNotificationEdgeReader, load_entity_notifications,};use graphql_properties::GraphqlSoupProperty;use models_pagination::PaginatedOpaqueCursor;@@ -23,17 +25,35 @@ use serde_json::Value;use soup::domain::models::FrecencySoupItem;/// Page returned by `Query.soup`.-#[derive(SimpleObject)]-pub struct SoupPage {+pub struct SoupPage<R: SoupNotificationEdgeReader> {+ items: Vec<GraphqlSoupItem<R>>,+ next_cursor: Option<String>,+ has_more: bool,+}++/// Page returned by `Query.soup`.+#[Object(name = "SoupPage")]+impl<R> SoupPage<R>+where+ R: SoupNotificationEdgeReader,+{/// Items in the current page.- pub items: Vec<GraphqlSoupItem>,+ async fn items(&self) -> &[GraphqlSoupItem<R>] {+ &self.items+ }+/// Opaque cursor for the next page, if one exists.- pub next_cursor: Option<String>,+ async fn next_cursor(&self) -> Option<&str> {+ self.next_cursor.as_deref()+ }+/// Whether more items are available after this page.- pub has_more: bool,+ async fn has_more(&self) -> bool {+ self.has_more+ }}-impl From<PaginatedOpaqueCursor<FrecencySoupItem>> for SoupPage {+impl<R: SoupNotificationEdgeReader> From<PaginatedOpaqueCursor<FrecencySoupItem>> for SoupPage<R> {fn from(page: PaginatedOpaqueCursor<FrecencySoupItem>) -> Self {let has_more = page.next_cursor.is_some();Self {@@ -45,15 +65,18 @@ impl From<PaginatedOpaqueCursor<FrecencySoupItem>> for SoupPage {}/// GraphQL Soup item envelope.-pub struct GraphqlSoupItem {+pub struct GraphqlSoupItem<R: SoupNotificationEdgeReader> {id: String,entity_type: GraphqlSoupEntityType,frecency_score: f64,- entity: GraphqlSoupEntity,+ entity: GraphqlSoupEntity<R>,}-#[Object]-impl GraphqlSoupItem {+#[Object(name = "GraphqlSoupItem")]+impl<R> GraphqlSoupItem<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.id.clone())}@@ -66,12 +89,12 @@ impl GraphqlSoupItem {self.frecency_score}- async fn entity(&self) -> &GraphqlSoupEntity {+ async fn entity(&self) -> &GraphqlSoupEntity<R> {&self.entity}}-impl From<FrecencySoupItem> for GraphqlSoupItem {+impl<R: SoupNotificationEdgeReader> From<FrecencySoupItem> for GraphqlSoupItem<R> {fn from(item: FrecencySoupItem) -> Self {let FrecencySoupItem {item,@@ -93,48 +116,62 @@ impl From<FrecencySoupItem> for GraphqlSoupItem {/// GraphQL union over expanded Soup entity variants.#[derive(Union)]-pub enum GraphqlSoupEntity {+pub enum GraphqlSoupEntity<R: SoupNotificationEdgeReader> {/// Document entity.- Document(GraphqlSoupDocument),+ Document(GraphqlSoupDocument<R>),/// Chat entity.- Chat(GraphqlSoupChat),+ Chat(GraphqlSoupChat<R>),/// Project entity.- Project(GraphqlSoupProject),+ Project(GraphqlSoupProject<R>),/// Email thread entity.- EmailThread(GraphqlSoupEmailThread),+ EmailThread(GraphqlSoupEmailThread<R>),/// Channel entity.- Channel(GraphqlSoupChannel),+ Channel(GraphqlSoupChannel<R>),/// Channel thread entity.- ChannelThread(GraphqlSoupChannelThread),+ ChannelThread(GraphqlSoupChannelThread<R>),/// Call entity.- Call(GraphqlSoupCall),+ Call(GraphqlSoupCall<R>),/// CRM company entity.- CrmCompany(GraphqlSoupCrmCompany),+ CrmCompany(GraphqlSoupCrmCompany<R>),/// Foreign entity.- ForeignEntity(GraphqlSoupForeignEntity),+ ForeignEntity(GraphqlSoupForeignEntity<R>),}-impl From<SoupItem> for GraphqlSoupEntity {+impl<R> From<SoupItem> for GraphqlSoupEntity<R>+where+ R: SoupNotificationEdgeReader,+{fn from(item: SoupItem) -> Self {match item {- SoupItem::Document(item) => Self::Document(GraphqlSoupDocument(item)),- SoupItem::Chat(item) => Self::Chat(GraphqlSoupChat(item)),- SoupItem::Project(item) => Self::Project(GraphqlSoupProject(item)),- SoupItem::EmailThread(item) => Self::EmailThread(GraphqlSoupEmailThread(item)),- SoupItem::Channel(item) => Self::Channel(GraphqlSoupChannel(item)),- SoupItem::ChannelThread(item) => Self::ChannelThread(GraphqlSoupChannelThread(item)),- SoupItem::Call(item) => Self::Call(GraphqlSoupCall(item)),- SoupItem::CrmCompany(item) => Self::CrmCompany(GraphqlSoupCrmCompany(item)),- SoupItem::ForeignEntity(item) => Self::ForeignEntity(GraphqlSoupForeignEntity(item)),+ SoupItem::Document(item) => Self::Document(GraphqlSoupDocument(item, PhantomData)),+ SoupItem::Chat(item) => Self::Chat(GraphqlSoupChat(item, PhantomData)),+ SoupItem::Project(item) => Self::Project(GraphqlSoupProject(item, PhantomData)),+ SoupItem::EmailThread(item) => {+ Self::EmailThread(GraphqlSoupEmailThread(item, PhantomData))+ }+ SoupItem::Channel(item) => Self::Channel(GraphqlSoupChannel(item, PhantomData)),+ SoupItem::ChannelThread(item) => {+ Self::ChannelThread(GraphqlSoupChannelThread(item, PhantomData))+ }+ SoupItem::Call(item) => Self::Call(GraphqlSoupCall(item, PhantomData)),+ SoupItem::CrmCompany(item) => {+ Self::CrmCompany(GraphqlSoupCrmCompany(item, PhantomData))+ }+ SoupItem::ForeignEntity(item) => {+ Self::ForeignEntity(GraphqlSoupForeignEntity(item, PhantomData))+ }}}}/// GraphQL document entity.-pub struct GraphqlSoupDocument(SoupDocument);+pub struct GraphqlSoupDocument<R: SoupNotificationEdgeReader>(SoupDocument, PhantomData<R>);-#[Object]-impl GraphqlSoupDocument {+#[Object(name = "GraphqlSoupDocument")]+impl<R> GraphqlSoupDocument<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.id.to_string())}@@ -191,12 +228,9 @@ impl GraphqlSoupDocument {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.id.to_string(),- entity_type: self.0.entity_type().to_string(),- },+ model_entity::EntityType::Document.with_entity_string(self.0.id.to_string()),).await}@@ -235,10 +269,13 @@ impl GraphqlSoupDocumentSubType {}/// GraphQL chat entity.-pub struct GraphqlSoupChat(SoupChat);+pub struct GraphqlSoupChat<R: SoupNotificationEdgeReader>(SoupChat, PhantomData<R>);-#[Object]-impl GraphqlSoupChat {+#[Object(name = "GraphqlSoupChat")]+impl<R> GraphqlSoupChat<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.id.to_string())}@@ -288,22 +325,22 @@ impl GraphqlSoupChat {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.id.to_string(),- entity_type: "chat".to_owned(),- },+ model_entity::EntityType::Chat.with_entity_string(self.0.id.to_string()),).await}}/// GraphQL project entity.-pub struct GraphqlSoupProject(SoupProject);+pub struct GraphqlSoupProject<R: SoupNotificationEdgeReader>(SoupProject, PhantomData<R>);-#[Object]-impl GraphqlSoupProject {+#[Object(name = "GraphqlSoupProject")]+impl<R> GraphqlSoupProject<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.id.to_string())}@@ -345,16 +382,13 @@ impl GraphqlSoupProject {.collect()}- async fn notifications(- &self,- ctx: &Context<'_>,+ async fn notifications<'a>(+ &'a self,+ ctx: &'a Context<'a>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.id.to_string(),- entity_type: "project".to_owned(),- },+ model_entity::EntityType::Project.with_entity_string(self.0.id.to_string()),).await}@@ -539,10 +573,16 @@ impl GraphqlSoupEmailAttachment {}/// GraphQL email thread entity.-pub struct GraphqlSoupEmailThread(SoupEnrichedEmailThreadPreview);--#[Object]-impl GraphqlSoupEmailThread {+pub struct GraphqlSoupEmailThread<R: SoupNotificationEdgeReader>(+ SoupEnrichedEmailThreadPreview,+ PhantomData<R>,+);++#[Object(name = "GraphqlSoupEmailThread")]+impl<R> GraphqlSoupEmailThread<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.thread.id.to_string())}@@ -665,12 +705,9 @@ impl GraphqlSoupEmailThread {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.thread.id.to_string(),- entity_type: "email".to_owned(),- },+ model_entity::EntityType::EmailThread.with_entity_string(self.0.thread.id.to_string()),).await}@@ -748,9 +785,9 @@ impl GraphqlSoupChannelMessage {}/// GraphQL channel entity.-pub struct GraphqlSoupChannel(SoupChannel);+pub struct GraphqlSoupChannel<R: SoupNotificationEdgeReader>(SoupChannel, PhantomData<R>);-impl GraphqlSoupChannel {+impl<R: SoupNotificationEdgeReader> GraphqlSoupChannel<R> {fn channel_type_name(channel_type: ChannelType) -> &'static str {match channel_type {ChannelType::Public => "public",@@ -761,8 +798,11 @@ impl GraphqlSoupChannel {}}-#[Object]-impl GraphqlSoupChannel {+#[Object(name = "GraphqlSoupChannel")]+impl<R> GraphqlSoupChannel<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.channel.channel.id.0.to_string())}@@ -851,22 +891,26 @@ impl GraphqlSoupChannel {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.channel.channel.id.0.to_string(),- entity_type: "channel".to_owned(),- },+ model_entity::EntityType::Channel+ .with_entity_string(self.0.channel.channel.id.0.to_string()),).await}}/// GraphQL channel thread entity.-pub struct GraphqlSoupChannelThread(SoupChannelThread);--#[Object]-impl GraphqlSoupChannelThread {+pub struct GraphqlSoupChannelThread<R: SoupNotificationEdgeReader>(+ SoupChannelThread,+ PhantomData<R>,+);++#[Object(name = "GraphqlSoupChannelThread")]+impl<R> GraphqlSoupChannelThread<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.id.to_string())}@@ -903,12 +947,9 @@ impl GraphqlSoupChannelThread {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.id.to_string(),- entity_type: "message".to_owned(),- },+ model_entity::EntityType::ChannelMessage.with_entity_string(self.0.id.to_string()),).await}@@ -947,10 +988,13 @@ impl GraphqlSoupCallParticipant {}/// GraphQL call entity.-pub struct GraphqlSoupCall(SoupCallRecord);+pub struct GraphqlSoupCall<R: SoupNotificationEdgeReader>(SoupCallRecord, PhantomData<R>);-#[Object]-impl GraphqlSoupCall {+#[Object(name = "GraphqlSoupCall")]+impl<R> GraphqlSoupCall<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.call_id.to_string())}@@ -1034,22 +1078,22 @@ impl GraphqlSoupCall {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.call_id.to_string(),- entity_type: "call".to_owned(),- },+ model_entity::EntityType::Call.with_entity_string(self.0.call_id.to_string()),).await}}/// GraphQL CRM company entity.-pub struct GraphqlSoupCrmCompany(SoupCrmCompany);+pub struct GraphqlSoupCrmCompany<R: SoupNotificationEdgeReader>(SoupCrmCompany, PhantomData<R>);-#[Object]-impl GraphqlSoupCrmCompany {+#[Object(name = "GraphqlSoupCrmCompany")]+impl<R> GraphqlSoupCrmCompany<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.id.to_string())}@@ -1109,10 +1153,16 @@ impl GraphqlSoupCrmCompany {}/// GraphQL foreign entity.-pub struct GraphqlSoupForeignEntity(SoupForeignEntity);--#[Object]-impl GraphqlSoupForeignEntity {+pub struct GraphqlSoupForeignEntity<R: SoupNotificationEdgeReader>(+ SoupForeignEntity,+ PhantomData<R>,+);++#[Object(name = "GraphqlSoupForeignEntity")]+impl<R> GraphqlSoupForeignEntity<R>+where+ R: SoupNotificationEdgeReader,+{async fn id(&self) -> ID {ID(self.0.id.to_string())}@@ -1149,12 +1199,10 @@ impl GraphqlSoupForeignEntity {&self,ctx: &Context<'_>,) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {- load_entity_notifications(+ load_entity_notifications::<R>(ctx,- EntityNotificationsKey {- entity_id: self.0.foreign_entity_id.clone(),- entity_type: "github".to_owned(),- },+ model_entity::EntityType::ForeignEntity+ .with_entity_string(self.0.foreign_entity_id.clone()),).await}diff --git a/crates/graphql_soup/src/resolvers.rs b/crates/graphql_soup/src/resolvers.rsindex a2c155d564..5b729457f5 100644--- a/crates/graphql_soup/src/resolvers.rs+++ b/crates/graphql_soup/src/resolvers.rs@@ -15,13 +15,14 @@ use entity_access::{inbound::axum_extractors::OptionalMacroUserTeamExtractor,};use graphql_common::extract_part;+use graphql_notification::SoupNotificationEdgeReader;use model_user::axum_extractor::MacroUserExtractor;use models_pagination::TypeEraseCursor;use soup::domain::{models::SoupRequest, ports::SoupService};use crate::{inputs::SoupInput, objects::SoupPage};-/// Object-safe-ish wrapper for sharing a concrete Soup service with GraphQL.+/// Shared wrapper for a concrete Soup service.pub struct SharedSoupService<S>(Arc<S>);impl<S> Clone for SharedSoupService<S> {@@ -74,11 +75,11 @@ where/// Resolve a page of Soup items for the authenticated user: runs the lazy/// axum extractors against the request context, converts the GraphQL input/// into a Soup request, and executes it against the Soup service.-pub async fn resolve_soup<S, E, EAS, St>(+pub async fn resolve_soup<S, E, EAS, St, R>(service: &S,ctx: &Context<'_>,input: SoupInput,-) -> async_graphql::Result<SoupPage>+) -> async_graphql::Result<SoupPage<R>>whereS: SoupService,E: EmailService,@@ -86,6 +87,7 @@ whereSt: Clone + Send + Sync + 'static,EmailRouterState<E>: FromRef<St>,Arc<EAS>: FromRef<St>,+ R: SoupNotificationEdgeReader,{let Cached(MacroUserExtractor { macro_user_id, .. }) =extract_part::<Cached<MacroUserExtractor>, St>(ctx).await?;diff --git a/crates/memory/src/context.rs b/crates/memory/src/context.rsindex 57025052af..ced721b3cf 100644--- a/crates/memory/src/context.rs+++ b/crates/memory/src/context.rs@@ -135,7 +135,11 @@ pub async fn build_tool_service_context(let properties_service =ai_tools::build_properties_service(pool.clone(), entity_access_service.clone());let task_properties_service =- ai_tools::build_task_properties_adapter(pool.clone(), properties_service.clone());+ ai_tools::build_task_properties_adapter(+ pool.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ );let document_service = documents::domain::service::DocumentServiceImpl::new(document_repo,cloudfront_config,@@ -156,7 +160,7 @@ pub async fn build_tool_service_context();// Properties tool context- let properties_tool_context = ai_tools::build_properties_tool_context(properties_service);+ let properties_tool_context = ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());// Email tool contextlet email_tool_context = email::inbound::toolset::EmailToolContext::new(diff --git a/crates/model-entity/src/lib.rs b/crates/model-entity/src/lib.rsindex 164bc8c1ec..5fda4ac07c 100644--- a/crates/model-entity/src/lib.rs+++ b/crates/model-entity/src/lib.rs@@ -135,3 +135,31 @@ impl<'a> CowLike<'a> for Entity<'a> {}}}++/// An owned entity wrapper for APIs that require a non-lifetime-parameterized type.+#[derive(Debug, Clone, Hash, PartialEq, Eq)]+pub struct OwnedEntity(Entity<'static>);++impl OwnedEntity {+ /// Borrow the wrapped entity.+ pub fn as_entity(&self) -> &Entity<'static> {+ &self.0+ }++ /// Consume the wrapper and return the wrapped entity.+ pub fn into_entity(self) -> Entity<'static> {+ self.0+ }+}++impl From<Entity<'static>> for OwnedEntity {+ fn from(entity: Entity<'static>) -> Self {+ Self(entity)+ }+}++impl From<OwnedEntity> for Entity<'static> {+ fn from(entity: OwnedEntity) -> Self {+ entity.into_entity()+ }+}diff --git a/crates/models_soup/src/properties.rs b/crates/models_soup/src/properties.rsindex 7f0878c121..95b471154b 100644--- a/crates/models_soup/src/properties.rs+++ b/crates/models_soup/src/properties.rs@@ -5,6 +5,7 @@ use models_properties::service::{property_definition::PropertyDefinition, property_value::PropertyValue,};use serde::{Deserialize, Serialize};+use uuid::Uuid;/// A property attached to a Soup item.///@@ -14,6 +15,9 @@ use serde::{Deserialize, Serialize};#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[serde(rename_all = "camelCase")]pub struct SoupProperty {+ /// Globally unique id of the assignment attaching this property to an entity.+ pub id: Uuid,+/// The property definitionpub definition: PropertyDefinition,@@ -30,6 +34,7 @@ impl From<EntityPropertyWithDefinition> for SoupProperty {/// should be fetched separately when needed for editing UI.fn from(prop: EntityPropertyWithDefinition) -> Self {Self {+ id: prop.property.id,definition: prop.definition,value: prop.value,}diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rsindex 19b349adfb..dfd85bec7c 100644--- a/crates/properties/src/domain/model.rs+++ b/crates/properties/src/domain/model.rs@@ -49,15 +49,25 @@ pub type ViewReceipt = PropertiesAccessReceipt<ViewAccessLevel>;pub type EditReceipt = PropertiesAccessReceipt<EditAccessLevel>;impl<T: RequiredPermission> PropertiesAccessReceipt<T> {- /// Wrap a minted access receipt, keeping the original properties entity- /// type. Only the permission adapter constructs these.- pub(crate) fn new(receipt: EntityAccessReceipt<T>, entity_type: EntityType) -> Self {+ /// Wrap a receipt minted by the entity access service while preserving the+ /// original properties entity type (notably, tasks map to documents in the+ /// access service).+ pub fn try_from_entity_access_receipt(+ receipt: EntityAccessReceipt<T>,+ entity_type: EntityType,+ ) -> Result<Self, entity_access::domain::models::AccessError> {+ if receipt.entity().entity_type != access_entity_type(entity_type) {+ return Err(entity_access::domain::models::AccessError::BadRequest(+ "entity access receipt type does not match properties entity type",+ ));+ }+let entity_id = receipt.entity().entity_id.clone();- Self {+ Ok(Self {receipt,entity_id,entity_type,- }+ })}/// The entity this receipt grants access to.@@ -136,7 +146,7 @@ impl<T: RequiredPermission> PropertiesAccessReceipt<T> {},EntityPermission::AccessLevel { access_level },)?;- Ok(Self::new(receipt, entity_type))+ Self::try_from_entity_access_receipt(receipt, entity_type)}}diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rsindex 647b78bd44..66a5702273 100644--- a/crates/properties/src/domain/ports.rs+++ b/crates/properties/src/domain/ports.rs@@ -7,6 +7,7 @@ use std::collections::HashMap;use macro_user_id::user_id::MacroUserIdStr;use models_properties::service::document_metadata::DocumentMetadata;+use models_properties::service::entity_property::EntityProperty;use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::project_metadata::ProjectMetadata;use models_properties::service::property_definition::PropertyDefinition;@@ -158,26 +159,16 @@ pub trait PropertiesRepo: Send + Sync + 'static {option_ids: &[Uuid],) -> impl Future<Output = Result<i64, Self::Err>> + Send;- /// Atomically update a property value if the property is attached to the entity.- /// No-op if the property is not attached.- fn update_entity_property_value_if_exists(- &self,- entity_id: &str,- entity_type: EntityType,- property_definition_id: Uuid,- value: Option<PropertyValue>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;-/// Upsert an entity property value (insert or update)./// If the property doesn't exist, it will be created and attached to the entity.- /// If it exists, the value will be updated.+ /// If it exists, the value will be updated. Returns the persisted assignment.fn upsert_entity_property(&self,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,value: Option<PropertyValue>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<EntityProperty, Self::Err>> + Send;/// Atomically add one option to a multi-select entity property value,/// attaching the property if needed. Re-adding a present option is a no-op.@@ -214,7 +205,7 @@ pub trait PropertiesRepo: Send + Sync + 'static {&self,task_id: Uuid,parent_task_id: Option<Uuid>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<EntityProperty>, Self::Err>> + Send;/// Atomically set a task's subtasks (for Subtasks property).///@@ -225,7 +216,7 @@ pub trait PropertiesRepo: Send + Sync + 'static {&self,task_id: Uuid,subtask_ids: Vec<Uuid>,- ) -> impl Future<Output = Result<(), Self::Err>> + Send;+ ) -> impl Future<Output = Result<Option<EntityProperty>, Self::Err>> + Send;/// Get a property value for a specific entity and property definition./// Returns `None` if the property is not attached to the entity.diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rsindex 087fdac8d3..c26524063b 100644--- a/crates/properties/src/domain/service.rs+++ b/crates/properties/src/domain/service.rs@@ -3,9 +3,8 @@//! Access control is represented in the method types: every entity-scoped//! method takes a [`ViewReceipt`] or [`EditReceipt`] proving the caller's//! access, and owner-scoped methods take the caller's identity plus their-//! team-membership receipt. Receipts are minted at the inbound edges via-//! [`PropertiesService::mint_view_receipt`] /-//! [`PropertiesService::mint_edit_receipt`]; internal (machine) callers mint+//! team-membership receipt. User-facing callers mint receipts through the+//! entity access service at the inbound edge; internal (machine) callers mint//! via [`PropertiesAccessReceipt::dangerously_assert_internal`](super::model::PropertiesAccessReceipt::dangerously_assert_internal),//! which makes unchecked paths explicit and greppable.@@ -42,31 +41,6 @@ pub fn team_id_from_receipt(team: Option<&TeamReceipt>) -> Option<Uuid> {/// Service trait for property operations.pub trait PropertiesService: Send + Sync + 'static {- /// Mint a proof that the user (or the public, for `None`) has view access- /// to the entity. Fails with [`PropertiesErr::PermissionDenied`] otherwise.- fn mint_view_receipt(- &self,- user_id: Option<&MacroUserIdStr<'_>>,- entity_id: &str,- entity_type: EntityType,- ) -> impl Future<Output = Result<ViewReceipt, PropertiesErr>> + Send;-- /// Mint a proof that the user has edit (or owner) access to the entity.- /// Fails with [`PropertiesErr::PermissionDenied`] otherwise.- fn mint_edit_receipt(- &self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,- ) -> impl Future<Output = Result<EditReceipt, PropertiesErr>> + Send;-- /// Set an entity's status system property to "Completed".- /// No-op if the entity doesn't have a status property.- fn set_system_property_status_complete(- &self,- access: &EditReceipt,- ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;-/// Get all properties attached to an entity, with definitions, values, and/// options. Tag properties are restricted to the viewer's own and their/// teams' definitions (the viewer being the receipt's authenticated user).@@ -99,6 +73,7 @@ pub trait PropertiesService: Send + Sync + 'static {) -> impl Future<Output = Result<Option<PropertyValue>, PropertiesErr>> + Send;/// Set or update a property value for an entity, or attach a property without a value.+ /// Returns the canonical property assignment, definition, and persisted value./// Validates property options if the value contains select options./// Linking Parent Task / Subtasks additionally requires edit access to the/// referenced tasks.@@ -107,7 +82,7 @@ pub trait PropertiesService: Send + Sync + 'static {access: &EditReceipt,property_definition_id: Uuid,value: Option<SetPropertyValue>,- ) -> impl Future<Output = Result<(), PropertiesErr>> + Send;+ ) -> impl Future<Output = Result<EntityPropertyWithDefinition, PropertiesErr>> + Send;/// Add one option to a multi-select entity property value atomically./// Attaches the property if needed and dedupes. Validates the option belongsdiff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rsindex 5c5e14cdd4..92979a6d72 100644--- a/crates/properties/src/domain/service_impl/mod.rs+++ b/crates/properties/src/domain/service_impl/mod.rs@@ -19,7 +19,7 @@ use models_properties::service::property_definition_with_options::PropertyDefiniuse models_properties::service::property_option::{PropertyOption, PropertyOptionValue};use models_properties::service::property_value::PropertyValue;use models_properties::{EntityPropertyReference, EntityReference, EntityType};-use system_properties::{StatusOption, SystemPropertyKey};+use system_properties::SystemPropertyKey;use uuid::Uuid;use std::sync::Arc;@@ -223,57 +223,6 @@ whereN: NotificationService,anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,{- #[tracing::instrument(skip(self), fields(user_id = ?user_id, entity_id = %entity_id, entity_type = ?entity_type))]- async fn mint_view_receipt(- &self,- user_id: Option<&MacroUserIdStr<'_>>,- entity_id: &str,- entity_type: EntityType,- ) -> Result<ViewReceipt, PropertiesErr> {- self.permission_service()?- .mint_view_receipt(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)- }-- #[tracing::instrument(skip(self), fields(user_id = %user_id, entity_id = %entity_id, entity_type = ?entity_type))]- async fn mint_edit_receipt(- &self,- user_id: &MacroUserIdStr<'_>,- entity_id: &str,- entity_type: EntityType,- ) -> Result<EditReceipt, PropertiesErr> {- self.permission_service()?- .mint_edit_receipt(user_id, entity_id, entity_type)- .await- .map_err(|_| PropertiesErr::PermissionDenied)- }-- #[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()))]- async fn set_system_property_status_complete(- &self,- access: &EditReceipt,- ) -> Result<(), PropertiesErr> {- let status_property_id = SystemPropertyKey::STATUS_UUID;- let completed_value = PropertyValue::SelectOption(vec![StatusOption::COMPLETED_UUID]);-- // Atomically update status to "Completed" if the property is attached- self.repository- .update_entity_property_value_if_exists(- access.entity_id(),- access.entity_type(),- status_property_id,- Some(completed_value),- )- .await- .map_err(anyhow::Error::from)?;-- self.enqueue_property_upsert(access.entity_id(), access.entity_type())- .await;-- Ok(())- }-#[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]async fn get_entity_properties(&self,@@ -345,7 +294,7 @@ whereaccess: &EditReceipt,property_definition_id: Uuid,value: Option<SetPropertyValue>,- ) -> Result<(), PropertiesErr> {+ ) -> Result<EntityPropertyWithDefinition, PropertiesErr> {let entity_id = access.entity_id();let entity_type = access.entity_type();@@ -401,39 +350,50 @@ where));}- // Handle special property types that require custom logic- match property_definition_id {+ // Relationship writes update both sides transactionally and return the+ // primary entity's canonical assignment from that transaction.+ if matches!(+ property_definition_id,SystemPropertyKey::PARENT_TASK_UUID | SystemPropertyKey::SUBTASKS_UUID- if entity_type == EntityType::Task =>- {- return self- .handle_task_relationship_property(access, property_definition_id, value)- .await;- }- SystemPropertyKey::ASSIGNEES_UUID if entity_type == EntityType::Task => {- self.handle_task_assignees_property(entity_id, value, access.authenticated_user())- .await?;- }- _ => {- // No special handling needed- }+ ) && entity_type == EntityType::Task+ {+ let property = self+ .handle_task_relationship_property(access, property_definition_id, value)+ .await?;+ return Ok(EntityPropertyWithDefinition {+ property,+ definition: property_definition,+ value: property_value,+ options: None,+ });}- // For all properties (including those with special handling that don't return early),- // upsert the already-converted PropertyValue- self.repository+ if property_definition_id == SystemPropertyKey::ASSIGNEES_UUID+ && entity_type == EntityType::Task+ {+ self.handle_task_assignees_property(entity_id, value, access.authenticated_user())+ .await?;+ }++ let property = self+ .repository.upsert_entity_property(entity_id,entity_type,property_definition_id,- property_value,+ property_value.clone(),).await.map_err(anyhow::Error::from)?;self.enqueue_property_upsert(entity_id, entity_type).await;- Ok(())+ Ok(EntityPropertyWithDefinition {+ property,+ definition: property_definition,+ value: property_value,+ options: None,+ })}#[tracing::instrument(diff --git a/crates/properties/src/domain/service_impl/task_properties.rs b/crates/properties/src/domain/service_impl/task_properties.rsindex e961d048b2..5e932c32f4 100644--- a/crates/properties/src/domain/service_impl/task_properties.rs+++ b/crates/properties/src/domain/service_impl/task_properties.rs@@ -6,7 +6,7 @@ use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;-use models_properties::service::property_value::PropertyValue;+use models_properties::service::{entity_property::EntityProperty, property_value::PropertyValue};use system_properties::SystemPropertyKey;use uuid::Uuid;@@ -54,11 +54,11 @@ whereaccess: &EditReceipt,property_definition_id: Uuid,value: Option<SetPropertyValue>,- ) -> Result<(), PropertiesErr> {+ ) -> Result<EntityProperty, PropertiesErr> {let task_id = Uuid::parse_str(access.entity_id()).map_err(|_| PropertiesErr::Validation("Invalid task ID".to_string()))?;- match property_definition_id {+ let property = match property_definition_id {SystemPropertyKey::PARENT_TASK_UUID => {let parent_task_id = match &value {None => None,@@ -85,7 +85,8 @@ whereself.repository.link_parent_task(task_id, parent_task_id).await- .map_err(anyhow::Error::from)?;+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::EntityPropertyNotFound)?}SystemPropertyKey::SUBTASKS_UUID => {let subtask_ids = match &value {@@ -117,16 +118,17 @@ whereself.repository.link_subtasks(task_id, subtask_ids).await- .map_err(anyhow::Error::from)?;+ .map_err(anyhow::Error::from)?+ .ok_or(PropertiesErr::EntityPropertyNotFound)?}_ => {return Err(PropertiesErr::Validation("Invalid property for task relationship handling".to_string(),));}- }+ };- Ok(())+ Ok(property)}/// Handle task assignees property with permissions.diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rsindex 8245c07f24..cae92a156e 100644--- a/crates/properties/src/domain/test.rs+++ b/crates/properties/src/domain/test.rs@@ -10,11 +10,29 @@ use anyhow::anyhow;use macro_user_id::user_id::MacroUserIdStr;use models_properties::{EntityType,- service::{property_definition::PropertyDefinition, property_value::PropertyValue},+ service::{+ entity_property::EntityProperty, property_definition::PropertyDefinition,+ property_value::PropertyValue,+ },};use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;+fn entity_property(+ entity_id: &str,+ entity_type: EntityType,+ property_definition_id: Uuid,+) -> EntityProperty {+ EntityProperty {+ id: Uuid::new_v4(),+ entity_id: entity_id.to_owned(),+ entity_type,+ property_definition_id,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ }+}+fn caller_user_id() -> MacroUserIdStr<'static> {MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()}@@ -54,28 +72,45 @@ fn create_mock_permission_service() -> MockPermissionService {}#[tokio::test]-async fn test_set_system_property_status_complete_happy_path() {+async fn test_set_status_complete_through_general_property_mutation() {let mut repo = MockPropertiesRepo::new();- repo.expect_update_entity_property_value_if_exists()- .withf(|entity_id, entity_type, prop_id, value| {- if entity_id != "e1" {- return false;- }- if *entity_type != EntityType::Document {- return false;- }- if *prop_id != SystemPropertyKey::STATUS_UUID {- return false;- }- match value {- Some(PropertyValue::SelectOption(ids)) => {- ids.len() == 1 && ids[0] == StatusOption::COMPLETED_UUID- }- _ => false,- }+ repo.expect_get_property_definition().returning(|_| {+ Box::pin(async {+ Ok(Some(PropertyDefinition {+ id: SystemPropertyKey::STATUS_UUID,+ owner: models_properties::PropertyOwner::System,+ display_name: "Status".to_string(),+ data_type: models_properties::DataType::SelectString,+ is_multi_select: false,+ specific_entity_type: None,+ created_at: chrono::Utc::now(),+ updated_at: chrono::Utc::now(),+ is_system: true,+ is_metadata: false,+ }))})- .returning(|_, _, _, _| Box::pin(async { Ok(()) }));+ });+ repo.expect_count_valid_property_options()+ .withf(|property_id, option_ids| {+ *property_id == SystemPropertyKey::STATUS_UUID+ && option_ids == [StatusOption::COMPLETED_UUID]+ })+ .returning(|_, _| Box::pin(async { Ok(1) }));+ repo.expect_upsert_entity_property()+ .withf(|entity_id, entity_type, property_id, value| {+ entity_id == "e1"+ && *entity_type == EntityType::Document+ && *property_id == SystemPropertyKey::STATUS_UUID+ && *value+ == Some(PropertyValue::SelectOption(vec![+ StatusOption::COMPLETED_UUID,+ ]))+ })+ .returning(|entity_id, entity_type, property_definition_id, _| {+ let property = entity_property(entity_id, entity_type, property_definition_id);+ Box::pin(async move { Ok(property) })+ });let service = PropertiesServiceImpl::new(repo,@@ -83,32 +118,30 @@ async fn test_set_system_property_status_complete_happy_path() {None::<MockNotificationService>,);- service- .set_system_property_status_complete(&edit_receipt("e1", EntityType::Document))+ let property = service+ .set_entity_property(+ &edit_receipt("e1", EntityType::Document),+ SystemPropertyKey::STATUS_UUID,+ Some(+ models_properties::api::requests::SetPropertyValue::SelectOption {+ option_id: StatusOption::COMPLETED_UUID,+ },+ ),+ ).await.unwrap();- // expectations on the mock validate the call shape-}--#[tokio::test]-async fn test_set_system_property_status_complete_error_path() {- let mut repo = MockPropertiesRepo::new();- repo.expect_update_entity_property_value_if_exists()- .returning(|_, _, _, _| Box::pin(async { Err(anyhow!("boom")) }));-- let service = PropertiesServiceImpl::new(- repo,- Some(create_mock_permission_service()),- None::<MockNotificationService>,+ assert_eq!(property.property.entity_id, "e1");+ assert_eq!(+ property.property.property_definition_id,+ SystemPropertyKey::STATUS_UUID+ );+ assert_eq!(+ property.value,+ Some(PropertyValue::SelectOption(vec![+ StatusOption::COMPLETED_UUID+ ])));-- let err = service- .set_system_property_status_complete(&edit_receipt("e1", EntityType::Document))- .await- .unwrap_err();-- assert_eq!(err.to_string(), "boom");}// ============================================================================@@ -147,7 +180,14 @@ async fn test_link_parent_task_delegates_to_repo() {repo.expect_link_parent_task().withf(move |t, p| *t == task_id && *p == Some(parent_id))- .returning(|_, _| Box::pin(async { Ok(()) }));+ .returning(|task_id, _| {+ let property = entity_property(+ &task_id.to_string(),+ EntityType::Task,+ SystemPropertyKey::PARENT_TASK_UUID,+ );+ Box::pin(async move { Ok(Some(property)) })+ });let service = PropertiesServiceImpl::new(repo,@@ -173,7 +213,14 @@ async fn test_link_parent_task_clear_parent() {repo.expect_link_parent_task().withf(move |t, p| *t == task_id && p.is_none())- .returning(|_, _| Box::pin(async { Ok(()) }));+ .returning(|task_id, _| {+ let property = entity_property(+ &task_id.to_string(),+ EntityType::Task,+ SystemPropertyKey::PARENT_TASK_UUID,+ );+ Box::pin(async move { Ok(Some(property)) })+ });let service = PropertiesServiceImpl::new(repo,@@ -260,7 +307,14 @@ async fn test_link_subtasks_delegates_to_repo() {.withf(move |t, s| {*t == task_id && s.len() == 2 && s.contains(&subtask_1) && s.contains(&subtask_2)})- .returning(|_, _| Box::pin(async { Ok(()) }));+ .returning(|task_id, _| {+ let property = entity_property(+ &task_id.to_string(),+ EntityType::Task,+ SystemPropertyKey::SUBTASKS_UUID,+ );+ Box::pin(async move { Ok(Some(property)) })+ });let service = PropertiesServiceImpl::new(repo,@@ -286,7 +340,14 @@ async fn test_link_subtasks_clear_all() {repo.expect_link_subtasks().withf(move |t, s| *t == task_id && s.is_empty())- .returning(|_, _| Box::pin(async { Ok(()) }));+ .returning(|task_id, _| {+ let property = entity_property(+ &task_id.to_string(),+ EntityType::Task,+ SystemPropertyKey::SUBTASKS_UUID,+ );+ Box::pin(async move { Ok(Some(property)) })+ });let service = PropertiesServiceImpl::new(repo,@@ -521,52 +582,6 @@ async fn test_get_system_property_value_error_path() {assert_eq!(err.to_string(), "db error");}-// ============================================================================-// receipt minting unit tests-// ============================================================================--#[tokio::test]-async fn test_mint_edit_receipt_no_permission_service() {- let repo = MockPropertiesRepo::new();- let service = PropertiesServiceImpl::new(- repo,- None::<MockPermissionService>,- None::<MockNotificationService>,- );-- let err = service- .mint_edit_receipt(&caller_user_id(), "doc1", EntityType::Document)- .await- .unwrap_err();-- assert!(matches!(- err,- crate::domain::error::PropertiesErr::PermissionServiceNotConfigured- ));-}--#[tokio::test]-async fn test_mint_edit_receipt_denied() {- let repo = MockPropertiesRepo::new();- let mut perm_service = MockPermissionService::new();- perm_service- .expect_mint_edit_receipt()- .returning(|_, _, _| Box::pin(async { Err(anyhow!("Access denied")) }));-- let service =- PropertiesServiceImpl::new(repo, Some(perm_service), None::<MockNotificationService>);-- let err = service- .mint_edit_receipt(&caller_user_id(), "doc1", EntityType::Document)- .await- .unwrap_err();-- assert!(matches!(- err,- crate::domain::error::PropertiesErr::PermissionDenied- ));-}-// ============================================================================// delete_entity_property unit tests// ============================================================================diff --git a/crates/properties/src/inbound/axum_router.rs b/crates/properties/src/inbound/axum_router.rsindex 4c46a5fded..29bae5cc9a 100644--- a/crates/properties/src/inbound/axum_router.rs+++ b/crates/properties/src/inbound/axum_router.rs@@ -22,7 +22,7 @@ use axum::{extract::{FromRef, Request},http::StatusCode,response::IntoResponse,- routing::{Route, delete, get, patch, post, put},+ routing::{Route, delete, get, post, put},};use entity_access::domain::models::MemberTeamRole;use entity_access::domain::ports::EntityAccessService;@@ -159,11 +159,6 @@ where).route("/entity_properties/{entity_property_id}",- delete(entities::delete_entity_property::<S, A>).layer(ensure_user_exists.clone()),- )- // Status shortcut - requires authentication- .route(- "/entities/{entity_type}/{entity_id}/status/complete",- patch(entities::set_property_status_complete::<S, A>).layer(ensure_user_exists),+ delete(entities::delete_entity_property::<S, A>).layer(ensure_user_exists),)}diff --git a/crates/properties/src/inbound/axum_router/entities.rs b/crates/properties/src/inbound/axum_router/entities.rsindex acc1fe0807..bb8129c0f4 100644--- a/crates/properties/src/inbound/axum_router/entities.rs+++ b/crates/properties/src/inbound/axum_router/entities.rs@@ -13,6 +13,7 @@ use axum::{http::StatusCode,response::{IntoResponse, Response},};+use entity_access::domain::models::EditAccessLevel;use entity_access::domain::ports::EntityAccessService;use model::user::axum_extractor::MacroUserExtractor;use models_properties::api::SetPropertyValue;@@ -24,6 +25,7 @@ use utoipa::ToSchema;use uuid::Uuid;use super::extract::{EditReceiptExtractor, ViewReceiptExtractor};+use super::extract::{mint_authenticated_receipt, mint_view_receipt};use super::{PropertiesRouterState, properties_err_status};use crate::domain::error::PropertiesErr;use crate::domain::service::PropertiesService;@@ -253,10 +255,13 @@ pub async fn get_bulk_entity_properties<S: PropertiesService, A: EntityAccessSer// permission to view.let mut receipts = Vec::with_capacity(request.entities.len());for entity_ref in &request.entities {- match state- .properties_service- .mint_view_receipt(Some(&user), &entity_ref.entity_id, entity_ref.entity_type)- .await+ match mint_view_receipt(+ state.entity_access_service.as_ref(),+ Some(&user),+ &entity_ref.entity_id,+ entity_ref.entity_type,+ )+ .await{Ok(receipt) => receipts.push(receipt),Err(e) => {@@ -533,10 +538,13 @@ pub async fn delete_entity_property<S: PropertiesService, A: EntityAccessService.await?.ok_or(PropertiesErr::EntityPropertyNotFound)?;- let access = state- .properties_service- .mint_edit_receipt(&user, &property_info.entity_id, property_info.entity_type)- .await?;+ let access = mint_authenticated_receipt::<EditAccessLevel, A>(+ state.entity_access_service.as_ref(),+ &user,+ &property_info.entity_id,+ property_info.entity_type,+ )+ .await?;state.properties_service@@ -545,61 +553,3 @@ pub async fn delete_entity_property<S: PropertiesService, A: EntityAccessServiceOk(StatusCode::NO_CONTENT)}--#[derive(Debug, Error)]-pub enum SetPropertyStatusCompleteErr {- #[error(transparent)]- Properties(#[from] PropertiesErr),-}--impl IntoResponse for SetPropertyStatusCompleteErr {- fn into_response(self) -> Response {- let status_code = match &self {- SetPropertyStatusCompleteErr::Properties(e) => properties_err_status(e),- };-- if status_code.is_server_error() {- tracing::error!(- error = ?self,- error_type = "SetPropertyStatusCompleteErr",- "Internal server error"- );- }-- (status_code, self.to_string()).into_response()- }-}--/// Set an entity's status property to "Completed".-///-/// If the entity has a status property attached, it will be set to "Completed".-/// If the entity does not have a status property, this is a no-op and returns success.-#[utoipa::path(- patch,- path = "/properties/entities/{entity_type}/{entity_id}/status/complete",- params(- ("entity_type" = EntityType, Path, description = "Entity type (document, channel, project, thread, chat)"),- ("entity_id" = String, Path, description = "Entity ID")- ),- responses(- (status = 204, description = "Status set to complete"),- (status = 403, description = "Access denied"),- (status = 500, description = "Internal server error")- ),- tags = ["Properties"]-)]-#[tracing::instrument(skip(state, access), fields(entity_id = %access.0.entity_id(), entity_type = ?access.0.entity_type()), err)]-pub async fn set_property_status_complete<S: PropertiesService, A: EntityAccessService>(- State(state): State<PropertiesRouterState<S, A>>,- access: EditReceiptExtractor,-) -> Result<StatusCode, SetPropertyStatusCompleteErr> {- tracing::info!("setting entity status to complete");-- state- .properties_service- .set_system_property_status_complete(&access.0)- .await?;-- tracing::debug!("status complete handled");- Ok(StatusCode::NO_CONTENT)-}diff --git a/crates/properties/src/inbound/axum_router/extract.rs b/crates/properties/src/inbound/axum_router/extract.rsindex 6eecfd2356..8457acab28 100644--- a/crates/properties/src/inbound/axum_router/extract.rs+++ b/crates/properties/src/inbound/axum_router/extract.rs@@ -12,13 +12,18 @@ use axum::{http::request::Parts,response::{IntoResponse, Response},};+use entity_access::domain::models::{+ AccessLevel, EditAccessLevel, Entity, EntityAccessAuth, EntityAccessReceipt, EntityPermission,+ RequiredPermission, ViewAccessLevel,+};use entity_access::domain::ports::EntityAccessService;+use macro_user_id::user_id::MacroUserIdStr;use model::user::axum_extractor::{MacroUserExtractor, OptionalMacroUserExtractor};use models_properties::EntityType;use super::{PropertiesRouterState, properties_err_status};use crate::domain::error::PropertiesErr;-use crate::domain::model::{EditReceipt, ViewReceipt};+use crate::domain::model::{EditReceipt, PropertiesAccessReceipt, ViewReceipt, access_entity_type};use crate::domain::service::PropertiesService;/// Path parameters for entity-scoped properties routes.@@ -62,6 +67,68 @@ impl IntoResponse for ReceiptRejection {}}+pub(crate) async fn mint_authenticated_receipt<T, A>(+ entity_access_service: &A,+ user_id: &MacroUserIdStr<'_>,+ entity_id: &str,+ entity_type: EntityType,+) -> Result<PropertiesAccessReceipt<T>, PropertiesErr>+where+ T: RequiredPermission,+ A: EntityAccessService,+{+ let receipt = entity_access_service+ .generate_entity_access_receipt::<T>(+ user_id,+ None,+ entity_id,+ access_entity_type(entity_type),+ )+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?;++ PropertiesAccessReceipt::try_from_entity_access_receipt(receipt, entity_type)+ .map_err(|_| PropertiesErr::PermissionDenied)+}++pub(crate) async fn mint_view_receipt<A>(+ entity_access_service: &A,+ user_id: Option<&MacroUserIdStr<'_>>,+ entity_id: &str,+ entity_type: EntityType,+) -> Result<ViewReceipt, PropertiesErr>+where+ A: EntityAccessService,+{+ if let Some(user_id) = user_id {+ return mint_authenticated_receipt::<ViewAccessLevel, A>(+ entity_access_service,+ user_id,+ entity_id,+ entity_type,+ )+ .await;+ }++ let access_entity_type = access_entity_type(entity_type);+ let access_level = entity_access_service+ .check_public_access(entity_id, access_entity_type, AccessLevel::View)+ .await+ .map_err(|_| PropertiesErr::PermissionDenied)?;+ let receipt = EntityAccessReceipt::try_new(+ EntityAccessAuth::Unauthenticated,+ Entity {+ entity_id: entity_id.to_string(),+ entity_type: access_entity_type,+ },+ EntityPermission::AccessLevel { access_level },+ )+ .map_err(|_| PropertiesErr::PermissionDenied)?;++ PropertiesAccessReceipt::try_from_entity_access_receipt(receipt, entity_type)+ .map_err(|_| PropertiesErr::PermissionDenied)+}+async fn entity_path_params(parts: &mut Parts) -> Result<EntityPathParams, ReceiptRejection> {let Path(params): Path<EntityPathParams> = parts.extract().await.map_err(|_| {ReceiptRejection::BadRequest("Missing or invalid entity_type / entity_id in path")@@ -95,10 +162,13 @@ where.await.map_err(|_| ReceiptRejection::Unauthorized)?;- let receipt = state- .properties_service- .mint_view_receipt(user.as_ref(), ¶ms.entity_id, params.entity_type)- .await?;+ let receipt = mint_view_receipt(+ state.entity_access_service.as_ref(),+ user.as_ref(),+ ¶ms.entity_id,+ params.entity_type,+ )+ .await?;Ok(Self(receipt))}@@ -130,10 +200,13 @@ where.await.map_err(|_| ReceiptRejection::Unauthorized)?;- let receipt = state- .properties_service- .mint_edit_receipt(&user, ¶ms.entity_id, params.entity_type)- .await?;+ let receipt = mint_authenticated_receipt::<EditAccessLevel, A>(+ state.entity_access_service.as_ref(),+ &user,+ ¶ms.entity_id,+ params.entity_type,+ )+ .await?;Ok(Self(receipt))}diff --git a/crates/properties/src/inbound/toolset/get_entity_properties.rs b/crates/properties/src/inbound/toolset/get_entity_properties.rsindex e861fd80f2..74988cbeee 100644--- a/crates/properties/src/inbound/toolset/get_entity_properties.rs+++ b/crates/properties/src/inbound/toolset/get_entity_properties.rs@@ -1,9 +1,13 @@//! GetEntityProperties tool for reading properties attached to an entity.-use crate::domain::model::{EntityPropertyInfo, PropertyOptionInfo};+use crate::domain::model::{+ EntityPropertyInfo, PropertiesAccessReceipt, PropertyOptionInfo, access_entity_type,+};use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use entity_access::domain::models::ViewAccessLevel;+use entity_access::domain::ports::EntityAccessService;use models_properties::PropertyOwner;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::property_value::PropertyValue;@@ -107,16 +111,17 @@ pub struct GetEntityPropertiesResponse {}#[async_trait]-impl<T> AsyncTool<PropertiesToolContext<T>> for GetEntityProperties+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for GetEntityPropertieswhereT: PropertiesService,+ A: EntityAccessService,{type Output = GetEntityPropertiesResponse;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, entity_id=%self.entity_id), err)]async fn call(&self,- service_context: ServiceContext<PropertiesToolContext<T>>,+ service_context: ServiceContext<PropertiesToolContext<T, A>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!(params=?self, "Get entity properties");@@ -124,14 +129,27 @@ wherelet entity_type = EntityType::from(self.entity_type);// Prove the requesting user can view the entity before reading anything.- let access = service_context- .service- .mint_view_receipt(Some(&request_context.user_id), &self.entity_id, entity_type)+ let entity_access_receipt = service_context+ .entity_access_service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ &request_context.user_id,+ None,+ &self.entity_id,+ access_entity_type(entity_type),+ ).await.map_err(|e| ToolCallError {description: "You do not have access to this entity".to_string(),internal_error: e.into(),})?;+ let access = PropertiesAccessReceipt::try_from_entity_access_receipt(+ entity_access_receipt,+ entity_type,+ )+ .map_err(|e| ToolCallError {+ description: "Unable to validate entity access".to_string(),+ internal_error: e.into(),+ })?;let props = service_context.servicediff --git a/crates/properties/src/inbound/toolset/list_tags.rs b/crates/properties/src/inbound/toolset/list_tags.rsindex 4319da2bc6..41b70fc696 100644--- a/crates/properties/src/inbound/toolset/list_tags.rs+++ b/crates/properties/src/inbound/toolset/list_tags.rs@@ -3,6 +3,7 @@use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;use models_properties::PropertyOwner;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::tag_sets::TagScope;@@ -59,16 +60,17 @@ pub struct ListTagsResponse {pub struct ListTags {}#[async_trait]-impl<T> AsyncTool<PropertiesToolContext<T>> for ListTags+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for ListTagswhereT: PropertiesService,+ A: EntityAccessService,{type Output = ListTagsResponse;#[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]async fn call(&self,- service_context: ServiceContext<PropertiesToolContext<T>>,+ service_context: ServiceContext<PropertiesToolContext<T, A>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!("List tags");diff --git a/crates/properties/src/inbound/toolset/mod.rs b/crates/properties/src/inbound/toolset/mod.rsindex b710246a07..10174f64e8 100644--- a/crates/properties/src/inbound/toolset/mod.rs+++ b/crates/properties/src/inbound/toolset/mod.rs@@ -9,6 +9,7 @@ mod test;use crate::domain::service::PropertiesService;use ai_toolset::AsyncToolCollection;+use entity_access::domain::ports::EntityAccessService;use std::sync::Arc;pub use get_entity_properties::{GetEntityProperties, GetEntityPropertiesResponse};@@ -16,35 +17,40 @@ pub use list_tags::{ListTags, ListTagsResponse};pub use set_entity_property::{SetEntityProperty, SetEntityPropertyResponse};/// Service context for properties AI tools.-pub struct PropertiesToolContext<T: PropertiesService> {+pub struct PropertiesToolContext<T: PropertiesService, A: EntityAccessService> {/// The properties service instance.pub service: Arc<T>,+ /// The canonical service used to mint entity access receipts.+ pub entity_access_service: Arc<A>,}-impl<T: PropertiesService> Clone for PropertiesToolContext<T> {+impl<T: PropertiesService, A: EntityAccessService> Clone for PropertiesToolContext<T, A> {fn clone(&self) -> Self {Self {service: self.service.clone(),+ entity_access_service: self.entity_access_service.clone(),}}}-impl<T: PropertiesService> PropertiesToolContext<T> {+impl<T: PropertiesService, A: EntityAccessService> PropertiesToolContext<T, A> {/// Create a new properties tool context.- pub fn new(service: T) -> Self {+ pub fn new(service: T, entity_access_service: A) -> Self {Self {service: Arc::new(service),+ entity_access_service: Arc::new(entity_access_service),}}}/// Create a properties toolset.-pub fn properties_toolset<T>() -> AsyncToolCollection<PropertiesToolContext<T>>+pub fn properties_toolset<T, A>() -> AsyncToolCollection<PropertiesToolContext<T, A>>whereT: PropertiesService,+ A: EntityAccessService,{AsyncToolCollection::new()- .add_tool::<GetEntityProperties, PropertiesToolContext<T>>()- .add_tool::<SetEntityProperty, PropertiesToolContext<T>>()- .add_tool::<ListTags, PropertiesToolContext<T>>()+ .add_tool::<GetEntityProperties, PropertiesToolContext<T, A>>()+ .add_tool::<SetEntityProperty, PropertiesToolContext<T, A>>()+ .add_tool::<ListTags, PropertiesToolContext<T, A>>()}diff --git a/crates/properties/src/inbound/toolset/set_entity_property.rs b/crates/properties/src/inbound/toolset/set_entity_property.rsindex 4181127e8e..1d501e2fb4 100644--- a/crates/properties/src/inbound/toolset/set_entity_property.rs+++ b/crates/properties/src/inbound/toolset/set_entity_property.rs@@ -1,9 +1,12 @@//! SetEntityProperty tool for updating property values on entities.+use crate::domain::model::{PropertiesAccessReceipt, access_entity_type};use crate::domain::service::PropertiesService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;use chrono::{DateTime, Utc};+use entity_access::domain::models::EditAccessLevel;+use entity_access::domain::ports::EntityAccessService;use models_properties::EntityType;use models_properties::api::requests::SetPropertyValue;use models_properties::shared::EntityReference;@@ -189,9 +192,10 @@ pub struct SetEntityPropertyResponse {}#[async_trait]-impl<T> AsyncTool<PropertiesToolContext<T>> for SetEntityProperty+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for SetEntityPropertywhereT: PropertiesService,+ A: EntityAccessService,{type Output = SetEntityPropertyResponse;@@ -206,7 +210,7 @@ where)]async fn call(&self,- service_context: ServiceContext<PropertiesToolContext<T>>,+ service_context: ServiceContext<PropertiesToolContext<T, A>>,request_context: RequestContext,) -> ToolResult<Self::Output> {tracing::info!("Set entity property");@@ -215,14 +219,27 @@ wherelet set_value = self.to_set_property_value();// Prove the requesting user can edit the entity before writing anything.- let access = service_context- .service- .mint_edit_receipt(&request_context.user_id, &self.entity_id, entity_type)+ let entity_access_receipt = service_context+ .entity_access_service+ .generate_entity_access_receipt::<EditAccessLevel>(+ &request_context.user_id,+ None,+ &self.entity_id,+ access_entity_type(entity_type),+ ).await.map_err(|e| ToolCallError {description: "You do not have edit access to this entity".to_string(),internal_error: e.into(),})?;+ let access = PropertiesAccessReceipt::try_from_entity_access_receipt(+ entity_access_receipt,+ entity_type,+ )+ .map_err(|e| ToolCallError {+ description: "Unable to validate entity access".to_string(),+ internal_error: e.into(),+ })?;// Delta mode: add/remove specific options atomically so concurrent// edits to the same multi-select value are never overwritten.diff --git a/crates/properties/src/lib.rs b/crates/properties/src/lib.rsindex c7e4c73889..99311cd334 100644--- a/crates/properties/src/lib.rs+++ b/crates/properties/src/lib.rs@@ -19,7 +19,7 @@ pub mod outbound;pub use domain::error::PropertiesErr;pub use domain::model::{EditReceipt, EntityPropertiesKey, EntityPropertyInfo, PropertiesAccessReceipt,- PropertyOptionInfo, ViewReceipt,+ PropertyOptionInfo, ViewReceipt, access_entity_type,};pub use domain::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer,diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rsindex 042bd5801f..939d9b0752 100644--- a/crates/properties/src/outbound/entity_property_queries.rs+++ b/crates/properties/src/outbound/entity_property_queries.rs@@ -1,53 +1,10 @@//! General entity property query helpers.-use models_properties::service::property_value::PropertyValue;+use models_properties::service::{entity_property::EntityProperty, property_value::PropertyValue};use models_properties::{EntityReference, EntityType};use sqlx::{Pool, Postgres};use uuid::Uuid;-/// Atomically update a property value if the property is attached to the entity.-/// No-op if the property is not attached.-pub async fn update_entity_property_value_if_exists(- pool: &Pool<Postgres>,- entity_id: &str,- entity_type: EntityType,- property_definition_id: Uuid,- value: Option<PropertyValue>,-) -> anyhow::Result<()> {- // Serialize PropertyValue to JSONB (or NULL if None)- let value_json = match value {- Some(v) => serde_json::to_value(&v)?,- None => serde_json::Value::Null,- };-- tracing::debug!(value_json = ?value_json, "updating entity property if exists");-- // Atomic update - only updates if the property is already attached- let result = sqlx::query!(- r#"- UPDATE entity_properties- SET values = $4, updated_at = NOW()- WHERE entity_id = $1- AND entity_type = $2- AND property_definition_id = $3- "#,- entity_id,- entity_type as EntityType,- property_definition_id,- value_json- )- .execute(pool)- .await?;-- if result.rows_affected() > 0 {- tracing::debug!("successfully updated entity property");- } else {- tracing::debug!("entity property not attached, no-op");- }-- Ok(())-}-/// Upsert an entity property value (insert or update)./// If the property doesn't exist, it will be created and attached to the entity./// If it exists, the value will be updated.@@ -57,7 +14,7 @@ pub async fn upsert_entity_property(entity_type: EntityType,property_definition_id: Uuid,value: Option<PropertyValue>,-) -> anyhow::Result<()> {+) -> anyhow::Result<EntityProperty> {let id = macro_uuid::generate_uuid_v7();// Serialize PropertyValue to JSONB (or NULL if None)@@ -68,16 +25,24 @@ pub async fn upsert_entity_property(tracing::debug!(value_json = ?value_json, "upserting entity property");- // Single UPSERT operation - handles both INSERT and UPDATE cases- // When value is None, JSONB will be NULL, effectively clearing the value while keeping the property attached- sqlx::query!(+ // Single UPSERT operation - handles both INSERT and UPDATE cases.+ // RETURNING yields the canonical assignment for both branches without a second query.+ let property = sqlx::query_as!(+ EntityProperty,r#"INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)VALUES ($1, $2, $3, $4, $5)- ON CONFLICT (entity_id, entity_type, property_definition_id)- DO UPDATE SET+ ON CONFLICT (entity_id, entity_type, property_definition_id)+ DO UPDATE SETvalues = EXCLUDED.values,updated_at = NOW()+ RETURNING+ id,+ entity_id,+ entity_type as "entity_type: EntityType",+ property_definition_id,+ created_at,+ updated_at"#,id,entity_id,@@ -85,12 +50,12 @@ pub async fn upsert_entity_property(property_definition_id,value_json)- .execute(pool)+ .fetch_one(pool).await?;tracing::debug!("successfully upserted entity property");- Ok(())+ Ok(property)}/// Atomically add one option to a multi-select entity property value, creatingdiff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rsindex 20d0f452fa..d0d67b621a 100644--- a/crates/properties/src/outbound/properties_pg_repo.rs+++ b/crates/properties/src/outbound/properties_pg_repo.rs@@ -245,24 +245,6 @@ impl PropertiesRepo for PropertiesPgRepo {.await}- #[tracing::instrument(skip(self, value))]- async fn update_entity_property_value_if_exists(- &self,- entity_id: &str,- entity_type: EntityType,- property_definition_id: Uuid,- value: Option<PropertyValue>,- ) -> Result<(), Self::Err> {- entity_property_queries::update_entity_property_value_if_exists(- &self.pool,- entity_id,- entity_type,- property_definition_id,- value,- )- .await- }-#[tracing::instrument(skip(self, value))]async fn upsert_entity_property(&self,@@ -270,7 +252,7 @@ impl PropertiesRepo for PropertiesPgRepo {entity_type: EntityType,property_definition_id: Uuid,value: Option<PropertyValue>,- ) -> Result<(), Self::Err> {+ ) -> Result<models_properties::service::entity_property::EntityProperty, Self::Err> {entity_property_queries::upsert_entity_property(&self.pool,entity_id,@@ -322,12 +304,18 @@ impl PropertiesRepo for PropertiesPgRepo {&self,task_id: Uuid,parent_task_id: Option<Uuid>,- ) -> Result<(), Self::Err> {+ ) -> Result<Option<models_properties::service::entity_property::EntityProperty>, Self::Err>+ {task_property_queries::link_parent_task(&self.pool, task_id, parent_task_id).await}#[tracing::instrument(skip(self))]- async fn link_subtasks(&self, task_id: Uuid, subtask_ids: Vec<Uuid>) -> Result<(), Self::Err> {+ async fn link_subtasks(+ &self,+ task_id: Uuid,+ subtask_ids: Vec<Uuid>,+ ) -> Result<Option<models_properties::service::entity_property::EntityProperty>, Self::Err>+ {task_property_queries::link_subtasks(&self.pool, task_id, subtask_ids).await}diff --git a/crates/properties/src/outbound/task_property_queries.rs b/crates/properties/src/outbound/task_property_queries.rsindex b7075d5bdc..ee1a59485b 100644--- a/crates/properties/src/outbound/task_property_queries.rs+++ b/crates/properties/src/outbound/task_property_queries.rs@@ -4,7 +4,7 @@ use std::collections::HashSet;use models_properties::EntityReference;use models_properties::EntityType;-use models_properties::service::property_value::PropertyValue;+use models_properties::service::{entity_property::EntityProperty, property_value::PropertyValue};use sqlx::{PgConnection, Pool, Postgres};use system_properties::SystemPropertyKey;use uuid::Uuid;@@ -18,7 +18,7 @@ pub async fn link_parent_task(pool: &Pool<Postgres>,task_id: Uuid,parent_task_id: Option<Uuid>,-) -> anyhow::Result<()> {+) -> anyhow::Result<Option<EntityProperty>> {// Validate: can't set self as parentif parent_task_id == Some(task_id) {anyhow::bail!("a task cannot be its own parent");@@ -46,11 +46,11 @@ pub async fn link_parent_task(tracing::debug!(old_parent = %old_parent_id, "removed task from old parent's Subtasks");}- // 3. Set new parent (returns true if task exists)- let task_exists = set_task_parent(&mut tx, task_id, parent_task_id).await?;+ // 3. Set new parent and retain the canonical assignment returned by Postgres.+ let property = set_task_parent(&mut tx, task_id, parent_task_id).await?;// 4. Add to new parent's subtasks (only if task exists)- if task_exists {+ if property.is_some() {if let Some(parent_id) = parent_task_id {add_to_parent_subtasks(&mut tx, parent_id, task_id).await?;tracing::debug!("added task to parent's Subtasks");@@ -61,7 +61,7 @@ pub async fn link_parent_task(tx.commit().await?;tracing::info!("successfully linked parent task");- Ok(())+ Ok(property)}/// Set a task's subtasks (for Subtasks property).@@ -69,7 +69,7 @@ pub async fn link_subtasks(pool: &Pool<Postgres>,task_id: Uuid,subtask_ids: Vec<Uuid>,-) -> anyhow::Result<()> {+) -> anyhow::Result<Option<EntityProperty>> {// Validate: can't include self as subtaskif subtask_ids.contains(&task_id) {anyhow::bail!("a task cannot be its own subtask");@@ -112,8 +112,8 @@ pub async fn link_subtasks("computed subtasks diff");- // 2. Set task's subtasks to new list- set_task_subtasks(&mut tx, task_id, subtask_ids).await?;+ // 2. Set task's subtasks to new list and retain the canonical assignment.+ let property = set_task_subtasks(&mut tx, task_id, subtask_ids).await?;// 3. For added subtasks: remove from old parent, set new parentfor subtask_id in &added {@@ -141,7 +141,7 @@ pub async fn link_subtasks(removed_count = removed.len(),"successfully linked subtasks");- Ok(())+ Ok(property)}// ============================================================================@@ -208,15 +208,17 @@ async fn remove_from_parent_subtasks() -> anyhow::Result<()> {let current = get_task_subtasks(&mut *tx, parent_id).await?;let updated: Vec<Uuid> = current.into_iter().filter(|id| *id != task_id).collect();- set_task_subtasks(&mut *tx, parent_id, updated).await+ set_task_subtasks(&mut *tx, parent_id, updated)+ .await+ .map(|_| ())}-/// Set a task's parent task property. Returns true if the task exists (row was updated).+/// Set a task's parent task property, returning the updated assignment when present.async fn set_task_parent(tx: &mut PgConnection,task_id: Uuid,parent_task_id: Option<Uuid>,-) -> anyhow::Result<bool> {+) -> anyhow::Result<Option<EntityProperty>> {let parent_task_prop_id = SystemPropertyKey::PARENT_TASK_UUID;let task_id_str = task_id.to_string();@@ -228,23 +230,29 @@ async fn set_task_parent(None => serde_json::Value::Null,};- let result = sqlx::query!(+ Ok(sqlx::query_as!(+ EntityProperty,r#"UPDATE entity_propertiesSET values = $4, updated_at = NOW()WHERE entity_id = $1AND entity_type = $2AND property_definition_id = $3+ RETURNING+ id,+ entity_id,+ entity_type as "entity_type: EntityType",+ property_definition_id,+ created_at,+ updated_at"#,task_id_str,EntityType::Task as EntityType,parent_task_prop_id,parent_value)- .execute(&mut *tx)- .await?;-- Ok(result.rows_affected() > 0)+ .fetch_optional(&mut *tx)+ .await?)}/// Add a task to a parent's subtasks array (if not already present).@@ -269,7 +277,7 @@ async fn set_task_subtasks(tx: &mut PgConnection,task_id: Uuid,subtask_ids: Vec<Uuid>,-) -> anyhow::Result<()> {+) -> anyhow::Result<Option<EntityProperty>> {let subtasks_prop_id = SystemPropertyKey::SUBTASKS_UUID;let task_id_str = task_id.to_string();@@ -283,21 +291,27 @@ async fn set_task_subtasks(serde_json::to_value(PropertyValue::EntityRef(refs))?};- sqlx::query!(+ Ok(sqlx::query_as!(+ EntityProperty,r#"UPDATE entity_propertiesSET values = $4, updated_at = NOW()WHERE entity_id = $1AND entity_type = $2AND property_definition_id = $3+ RETURNING+ id,+ entity_id,+ entity_type as "entity_type: EntityType",+ property_definition_id,+ created_at,+ updated_at"#,task_id_str,EntityType::Task as EntityType,subtasks_prop_id,subtasks_value)- .execute(&mut *tx)- .await?;-- Ok(())+ .fetch_optional(&mut *tx)+ .await?)}diff --git a/crates/properties/src/outbound/test.rs b/crates/properties/src/outbound/test.rsindex 3ced1edf9d..947a5c6235 100644--- a/crates/properties/src/outbound/test.rs+++ b/crates/properties/src/outbound/test.rs@@ -3,127 +3,11 @@use super::properties_pg_repo::PropertiesPgRepo;use crate::domain::ports::PropertiesRepo;use macro_db_migrator::MACRO_DB_MIGRATIONS;-use models_properties::{EntityType, service::property_value::PropertyValue};+use models_properties::EntityType;use sqlx::{Pool, Postgres};-use system_properties::{StatusOption, SystemPropertyKey};+use system_properties::SystemPropertyKey;use uuid::Uuid;-#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties_seed"))-)]-async fn updates_existing_property(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PropertiesPgRepo::new(pool.clone());- let entity_id = "entity-status-incomplete";- let property_id = SystemPropertyKey::STATUS_UUID;-- // Update value to completed- repo.update_entity_property_value_if_exists(- entity_id,- EntityType::Document,- property_id,- Some(PropertyValue::SelectOption(vec![- StatusOption::COMPLETED_UUID,- ])),- )- .await?;-- // Verify- let stored: serde_json::Value = sqlx::query_scalar::<_, serde_json::Value>(- r#"- SELECT values FROM entity_properties- WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3- "#,- )- .bind(entity_id)- .bind(EntityType::Document)- .bind(property_id)- .fetch_one(&pool)- .await?;-- assert_eq!(- stored,- serde_json::json!({"type": "SelectOption", "value": [StatusOption::COMPLETED_UUID]})- );-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties_seed"))-)]-async fn no_op_when_property_not_attached(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PropertiesPgRepo::new(pool.clone());- let entity_id = "entity-no-status";- let property_id = SystemPropertyKey::STATUS_UUID;-- repo.update_entity_property_value_if_exists(- entity_id,- EntityType::Document,- property_id,- Some(PropertyValue::SelectOption(vec![- StatusOption::COMPLETED_UUID,- ])),- )- .await?;-- let count: i64 = sqlx::query_scalar::<_, i64>(- r#"- SELECT COUNT(*) FROM entity_properties- WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3- "#,- )- .bind(entity_id)- .bind(EntityType::Document)- .bind(property_id)- .fetch_one(&pool)- .await?;-- assert_eq!(count, 0, "no rows should be created or updated");-- Ok(())-}--#[sqlx::test(- migrator = "MACRO_DB_MIGRATIONS",- fixtures(path = "../../fixtures", scripts("properties_seed"))-)]-async fn idempotent_when_already_completed(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = PropertiesPgRepo::new(pool.clone());- let entity_id = "entity-status-complete";- let property_id = SystemPropertyKey::STATUS_UUID;-- repo.update_entity_property_value_if_exists(- entity_id,- EntityType::Document,- property_id,- Some(PropertyValue::SelectOption(vec![- StatusOption::COMPLETED_UUID,- ])),- )- .await?;-- let stored: serde_json::Value = sqlx::query_scalar::<_, serde_json::Value>(- r#"- SELECT values FROM entity_properties- WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3- "#,- )- .bind(entity_id)- .bind(EntityType::Document)- .bind(property_id)- .fetch_one(&pool)- .await?;-- assert_eq!(- stored,- serde_json::json!({"type": "SelectOption", "value": [StatusOption::COMPLETED_UUID]})- );-- Ok(())-}-// ============================================================================// Task linking tests - link_parent_task// ============================================================================diff --git a/crates/search_service/src/api/search/document/test.rs b/crates/search_service/src/api/search/document/test.rsindex 686048d70b..26095573e7 100644--- a/crates/search_service/src/api/search/document/test.rs+++ b/crates/search_service/src/api/search/document/test.rs@@ -647,6 +647,7 @@ fn test_sort_stability() {fn make_test_soup_property(name: &str) -> SoupProperty {SoupProperty {+ id: Uuid::new_v4(),definition: PropertyDefinition {id: Uuid::new_v4(),owner: PropertyOwner::System,diff --git a/crates/soup/src/inbound/toolset/test.rs b/crates/soup/src/inbound/toolset/test.rsindex 96f6c6521f..b138ee9697 100644--- a/crates/soup/src/inbound/toolset/test.rs+++ b/crates/soup/src/inbound/toolset/test.rs@@ -381,6 +381,7 @@ fn test_from_soup_item_resolves_tags_via_caller_map() {let now = Utc::now();let tag_property = SoupProperty {+ id: Uuid::new_v4(),definition: PropertyDefinition {id: definition_id,owner: PropertyOwner::User {diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 5cc6eb08fa..bdad43e4eb 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -244,8 +244,11 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar);let properties_service =ai_tools::build_properties_service(pool.clone(), entity_access_service.clone());- let task_properties_service =- ai_tools::build_task_properties_adapter(pool.clone(), properties_service.clone());+ let task_properties_service = ai_tools::build_task_properties_adapter(+ pool.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ );let document_service = documents::domain::service::DocumentServiceImpl::new(document_repo,cloudfront_config,@@ -281,7 +284,8 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arlet search_service_client = Arc::new(search_service_client);// Build properties tool context- let properties_tool_context = ai_tools::build_properties_tool_context(properties_service);+ let properties_tool_context =+ ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());let email_tool_context = email::inbound::toolset::EmailToolContext::new(Arc::new(email::domain::service::EmailServiceImpl::new(diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex 129c58c177..ad97e3f3dd 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -273,8 +273,11 @@ async fn main() -> anyhow::Result<()> {};let properties_service =ai_tools::build_properties_service(db.clone(), entity_access_service.clone());- let task_properties_service =- ai_tools::build_task_properties_adapter(db.clone(), properties_service.clone());+ let task_properties_service = ai_tools::build_task_properties_adapter(+ db.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ );let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(macro_event_broker::KafkaEventPublisher::new(config.kafka_brokers.as_ref()).context("failed to create kafka event publisher")?,@@ -342,7 +345,8 @@ async fn main() -> anyhow::Result<()> {let search_service_client = Arc::new(search_service_client);- let properties_tool_context = ai_tools::build_properties_tool_context(properties_service);+ let properties_tool_context =+ ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());tracing::info!("initialized properties tool context");diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 35aa53965a..1ada4c0eca 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -48,7 +48,12 @@ use email::{domain::{ports::ReadonlyEmailPreviewAdapter, service::EmailServiceImpl},outbound::EmailPgRepo,};-use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};+use entity_access::{+ domain::{+ models::EditAccessLevel, ports::EntityAccessService as _, service::EntityAccessServiceImpl,+ },+ outbound::PgAccessRepository,+};use favorites::{domain::service::FavoritesServiceImpl, inbound::axum_router::FavoritesRouterState,outbound::pg_favorites_repo::PgFavoritesRepo,@@ -139,6 +144,8 @@ pub(crate) type DssGraphqlSoupSchema = complete_graph::SharedSoupSchema<DssEmailService,EntityAccessService,ApiContext,+ complete_graph::PropertiesEntityPropertyWriter<PropertiesService, EntityAccessService>,+ Arc<ai_tools::ToolNotificationService>,>;type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;@@ -156,6 +163,7 @@ pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepositorypub(crate) struct TaskPropertiesAdapter {pub system_properties: Arc<SystemPropertiesService>,pub properties: Arc<PropertiesService>,+ pub entity_access_service: Arc<EntityAccessService>,}impl TaskPropertiesPort for TaskPropertiesAdapter {@@ -187,14 +195,24 @@ impl TaskPropertiesPort for TaskPropertiesAdapter {let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str(user_id)?;- let access = self- .properties- .mint_edit_receipt(&user_id, entity_id, models_properties::EntityType::Task)+ let entity_access_receipt = self+ .entity_access_service+ .generate_entity_access_receipt::<EditAccessLevel>(+ &user_id,+ None,+ entity_id,+ properties::access_entity_type(models_properties::EntityType::Task),+ ).await?;+ let access = properties::PropertiesAccessReceipt::try_from_entity_access_receipt(+ entity_access_receipt,+ models_properties::EntityType::Task,+ )?;self.properties.set_entity_property(&access, property_definition_id, value).await+ .map(|_| ()).map_err(Into::into)}@@ -353,7 +371,7 @@ pub(crate) struct ApiContext {#[cfg(feature = "graphql")]pub graphql_soup_schema: DssGraphqlSoupSchema,#[cfg(feature = "graphql")]- pub graphql_notification_reader: Arc<dyn complete_graph::SoupNotificationEdgeReader>,+ pub graphql_notification_reader: Arc<ai_tools::ToolNotificationService>,pub favorites_state: DssFavoritesState,pub favorites_service: Arc<FavoritesServiceType>,pub foreign_entity_state: DssForeignEntityState,diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rsindex cde91db6cb..7282ad5fbb 100644--- a/services/document_storage_service/src/api/graphql_soup.rs+++ b/services/document_storage_service/src/api/graphql_soup.rs@@ -54,8 +54,15 @@ async fn handler(State(state): State<ApiContext>, req: Request) -> Response {.into_response();};- let property_reader: std::sync::Arc<dyn complete_graph::SoupPropertyEdgeReader> =- state.properties_service.clone();+ let property_reader = complete_graph::PropertiesSoupPropertyEdgeReader::new(+ state.properties_service.clone(),+ state.entity_access_service.clone(),+ );+ let property_writer = complete_graph::PropertiesEntityPropertyWriter::new(+ state.properties_service.clone(),+ state.entity_access_service.clone(),+ macro_user_id.clone(),+ );let request = request.data(GraphqlSoupRequestParts::new(parts)).data(state.clone())@@ -63,6 +70,7 @@ async fn handler(State(state): State<ApiContext>, req: Request) -> Response {macro_user_id.clone(),property_reader,))+ .data(property_writer).data(complete_graph::entity_notifications_loader(macro_user_id,state.graphql_notification_reader.clone(),diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 0105cfd899..79c4e7fac4 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -291,7 +291,7 @@ async fn main() -> anyhow::Result<()> {queue: ingress_queue.clone(),});#[cfg(feature = "graphql")]- let graphql_notification_reader: Arc<dyn complete_graph::SoupNotificationEdgeReader> =+ let graphql_notification_reader: Arc<ai_tools::ToolNotificationService> =Arc::new(NotificationReaderService {repository: notification::outbound::repository::DbNotificationRepository::new(db.clone(),@@ -406,6 +406,7 @@ async fn main() -> anyhow::Result<()> {TaskPropertiesAdapter {system_properties: system_properties_service.clone(),properties: properties_service.clone(),+ entity_access_service: entity_access_service.clone(),},connection_service,entity_access_management_service.clone(),diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rsindex 49224695b9..a72d798f8c 100644--- a/services/mcp_service/src/context.rs+++ b/services/mcp_service/src/context.rs@@ -214,8 +214,11 @@ async fn build_tool_context()));let properties_service =ai_tools::build_properties_service(db.clone(), entity_access_service.clone());- let task_properties_service =- ai_tools::build_task_properties_adapter(db.clone(), properties_service.clone());+ let task_properties_service = ai_tools::build_task_properties_adapter(+ db.clone(),+ properties_service.clone(),+ entity_access_service.clone(),+ );let macro_event_broker = macro_event_broker::MacroEventBrokerService::new(macro_event_broker::KafkaEventPublisher::new(config.kafka_brokers.as_ref()).context("failed to create kafka event publisher")?,@@ -244,7 +247,8 @@ async fn build_tool_context(config.document_permission_jwt.to_string(),);- let properties_tool_context = ai_tools::build_properties_tool_context(properties_service);+ let properties_tool_context =+ ai_tools::build_properties_tool_context(properties_service, entity_access_service.clone());let email_tool_context = email::inbound::toolset::EmailToolContext::new(Arc::new(EmailServiceImpl::new(diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 4d71377e87..81e347098e 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -235,6 +235,12 @@ input GraphqlEntityFilterAst {propertiesFilter: GraphqlPropertiesExpr}+input GraphqlEntityReferenceInput {+ entityType: GraphqlPropertyEntityType!+ entityId: String!+ specificMessageId: ID+}+input GraphqlForeignEntityBinaryExpr {left: GraphqlForeignEntityExpr!right: GraphqlForeignEntityExpr!@@ -361,6 +367,19 @@ input GraphqlPropertyMatchValue @oneOf {entityRef: String}+input GraphqlSetPropertyValue @oneOf {+ boolean: Boolean+ date: String+ number: Float+ string: String+ selectOption: ID+ multiSelectOption: [ID!]+ entityReference: GraphqlEntityReferenceInput+ multiEntityReference: [GraphqlEntityReferenceInput!]+ link: String+ multiLink: [String!]+}+enum GraphqlSharedEmailFilter {EXCLUDEINCLUDE@@ -726,10 +745,11 @@ type GraphqlSoupProject {type GraphqlSoupProperty {"""- Id of the shared property *definition* — deliberately not named `id`:- a property instance has no global identity (its `value` is- per-entity), so it must never be treated as a cacheable entity.- Normalized caches key objects by the presence of an `id` field.+ Globally unique id of this property assignment.+ """+ id: ID!+ """+ Id of the shared property definition."""propertyDefinitionId: ID!displayName: String!@@ -818,6 +838,23 @@ A scalar that can represent any JSON value."""scalar JSON+type PropertiesMutationRoot {+ """+ Set or attach one property on an entity.+ """+ setEntityProperty(input: SetEntityPropertyInput!): GraphqlSoupProperty!+}++input SetEntityPropertyInput {+ entityType: GraphqlPropertyEntityType!+ entityId: String!+ propertyDefinitionId: ID!+ """+ Omit or pass null to attach the property without a value.+ """+ value: GraphqlSetPropertyValue+}+"""Input for `Query.soup`."""@@ -888,5 +925,6 @@ Directs the executor to skip this field or fragment when the `if` argument is trdirective @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENTschema {query: SoupQueryRoot+ mutation: PropertiesMutationRoot}