Skip to content

The open alternative to Salesforce, designed for AI.

fix(ai): navigate_app takes explicit record and view ids (#27108)

Félix Malfait5d2e1afe8016
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
index d2974180039..dbfc38994c3 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/action-tool.provider.ts
@@ -267,6 +267,7 @@ export class ActionToolProvider implements ToolProvider {
userId: context.userId,
userWorkspaceId: context.userWorkspaceId,
threadId: context.threadId,
+ rolePermissionConfig: context.rolePermissionConfig,
onCodeExecutionUpdate: context.onCodeExecutionUpdate,
});
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts b/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts
index b09e42ac386..57585112aee 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tool.module.ts
@@ -26,11 +26,11 @@ import { ConnectedAccountMetadataModule } from 'src/engine/metadata-modules/conn
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { NavigationMenuItemModule } from 'src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.module';
import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
-import { ViewModule } from 'src/engine/metadata-modules/view/view.module';
import { CalendarEventCreationManagerModule } from 'src/modules/calendar/calendar-event-creation-manager/calendar-event-creation-manager.module';
import { MessagingImportManagerModule } from 'src/modules/messaging/message-import-manager/messaging-import-manager.module';
import { MessagingSendManagerModule } from 'src/modules/messaging/message-outbound-manager/messaging-send-manager.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
imports: [
MessagingImportManagerModule,
@@ -44,9 +44,9 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
JwtModule,
SecureHttpClientModule,
ObjectMetadataModule,
- ViewModule,
NavigationMenuItemModule,
WorkspaceManyOrAllFlatEntityMapsCacheModule,
+ WorkspaceCacheModule,
],
providers: [
HttpTool,
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/__tests__/navigate-app-tool.schema.spec.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/__tests__/navigate-app-tool.schema.spec.ts
new file mode 100644
index 00000000000..0c278b07717
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/__tests__/navigate-app-tool.schema.spec.ts
@@ -0,0 +1,54 @@
+import { NavigateAppInputZodSchema } from 'src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.schema';
+
+const RECORD_ID = '20202020-0000-4000-8000-000000000001';
+
+describe('NavigateAppInputZodSchema', () => {
+ it('should accept a record navigation by id', () => {
+ const parseResult = NavigateAppInputZodSchema.safeParse({
+ navigation: {
+ type: 'navigateToRecord',
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ },
+ });
+
+ expect(parseResult.success).toBe(true);
+ });
+
+ it('should reject a record navigation by name', () => {
+ const parseResult = NavigateAppInputZodSchema.safeParse({
+ navigation: {
+ type: 'navigateToRecord',
+ objectNameSingular: 'company',
+ recordName: 'Acme',
+ },
+ });
+
+ expect(parseResult.success).toBe(false);
+ });
+
+ it('should reject a record id that is not a uuid', () => {
+ const parseResult = NavigateAppInputZodSchema.safeParse({
+ navigation: {
+ type: 'navigateToRecord',
+ objectNameSingular: 'company',
+ recordId: 'Acme',
+ },
+ });
+
+ expect(parseResult.success).toBe(false);
+ });
+
+ it('should accept a view navigation by id and reject one by name', () => {
+ expect(
+ NavigateAppInputZodSchema.safeParse({
+ navigation: { type: 'navigateToView', viewId: RECORD_ID },
+ }).success,
+ ).toBe(true);
+ expect(
+ NavigateAppInputZodSchema.safeParse({
+ navigation: { type: 'navigateToView', viewName: 'All Companies' },
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.schema.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.schema.ts
index 4e5a571d558..1bf156e9ba7 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.schema.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.schema.ts
@@ -5,12 +5,13 @@ export const NavigateAppActionZodSchema = z.discriminatedUnion('type', [
type: z
.literal('navigateToView')
.describe(
- 'Navigate to a specific view by name. ONLY use this type when the user explicitly mentions the word "view" (e.g. "go to the My Companies view", "open view All People"). Do NOT use this for general navigation requests.',
+ 'Navigate to a specific view by id. ONLY use this type when the user explicitly mentions the word "view" (e.g. "go to the My Companies view") or right after you created or updated a view. Do NOT use this for general navigation requests.',
),
- viewName: z
+ viewId: z
.string()
+ .uuid()
.describe(
- 'The name of the view to navigate to (e.g. "My Companies", "All People")',
+ 'The id of the view to navigate to. Take it from get_views, or from the result of the tool that created or updated the view (e.g. upsert_complete_view, create_view).',
),
}),
z.object({
@@ -29,18 +30,14 @@ export const NavigateAppActionZodSchema = z.discriminatedUnion('type', [
type: z
.literal('navigateToRecord')
.describe(
- 'Navigate to a specific record page. Use this when the user wants to go to a particular record by name (e.g. "go to the company Acme", "open the person John Doe", "show me the deal Enterprise Plan").',
+ 'Navigate to a specific record page by id. Find the record id first with the find_* tools (e.g. find_many_companies filtered by name), or take it from the result of the tool that created the record. If several records match what the user asked for, ask which one they mean before navigating.',
),
objectNameSingular: z
.string()
.describe(
'The singular name of the object type (e.g. "company", "person", "opportunity")',
),
- recordName: z
- .string()
- .describe(
- 'The name or label of the record to navigate to (e.g. "Acme", "John Doe", "Enterprise Plan")',
- ),
+ recordId: z.string().uuid().describe('The id of the record to navigate to'),
}),
z.object({
type: z
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.ts
index 9baacb9bdcc..4f0780b26a9 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.ts
@@ -3,42 +3,43 @@ import { Injectable } from '@nestjs/common';
import { sleep } from 'cloudflare/core';
import Fuse from 'fuse.js';
import { NavigateAppToolOutput } from 'twenty-shared/ai';
-import { FieldMetadataType, type ObjectRecord } from 'twenty-shared/types';
+import { FeatureFlagKey, type ObjectsPermissions } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import {
type NavigateAppInput,
NavigateAppInputZodSchema,
} from 'src/engine/core-modules/tool/tools/navigate-tool/navigate-app-tool.schema';
+import { buildNavigateToRecordOutput } from 'src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-record-output.util';
+import { buildNavigateToViewOutput } from 'src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-view-output.util';
import { type ToolInput } from 'src/engine/core-modules/tool/types/tool-input.type';
import { ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
import { type ToolExecutionContext } from 'src/engine/core-modules/tool/types/tool-execution-context.type';
import { type Tool } from 'src/engine/core-modules/tool/types/tool.type';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
-import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { NavigationMenuItemType } from 'src/engine/metadata-modules/navigation-menu-item/enums/navigation-menu-item-type.enum';
import { NavigationMenuItemService } from 'src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.service';
-import { ViewService } from 'src/engine/metadata-modules/view/services/view.service';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
-import { resolveEffectiveFlatEntityProperty } from 'src/engine/metadata-modules/overrides/utils/resolve-effective-flat-entity-property.util';
+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
+import { getObjectsPermissionsFromRolePermissionConfig } from 'src/engine/twenty-orm/utils/get-objects-permissions-from-role-permission-config.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
@Injectable()
export class NavigateAppTool implements Tool {
description = `Navigate the application.
- Use navigateToRecord when the user wants to go to a specific record by name.
+ Use navigateToRecord to open a specific record. It needs the record id: find it first with the find_* tools, or take it from the result of the tool that created the record.
Default to navigateToObject for all other navigation requests.
- Only use navigateToView when the user explicitly mentions the word "view" in their request.
+ Only use navigateToView when the user explicitly mentions the word "view" in their request, or right after creating a view. It needs the view id from get_views or from the tool that created the view.
If the user asks to wait, use the wait tool with the specified duration.`;
inputSchema = NavigateAppInputZodSchema;
constructor(
private readonly navigationMenuItemService: NavigationMenuItemService,
- private readonly viewService: ViewService,
+ private readonly featureFlagService: FeatureFlagService,
private readonly workspaceManyOrAllFlatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
- private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly workspaceCacheService: WorkspaceCacheService,
) {}
async execute(
@@ -59,22 +60,23 @@ export class NavigateAppTool implements Tool {
switch (input.type) {
case 'navigateToView':
- return this.navigateToView(
- input.viewName,
- context.workspaceId,
- context.userWorkspaceId,
- );
+ return this.navigateToView({
+ viewId: input.viewId,
+ workspaceId: context.workspaceId,
+ userWorkspaceId: context.userWorkspaceId,
+ });
case 'navigateToObject':
return this.navigateToObject(
input.objectNameSingular,
context.workspaceId,
);
case 'navigateToRecord':
- return this.navigateToRecord(
- input.objectNameSingular,
- input.recordName,
- context.workspaceId,
- );
+ return this.navigateToRecord({
+ objectNameSingular: input.objectNameSingular,
+ recordId: input.recordId,
+ workspaceId: context.workspaceId,
+ rolePermissionConfig: context.rolePermissionConfig,
+ });
case 'wait':
return this.wait(input.durationMs);
}
@@ -95,71 +97,39 @@ export class NavigateAppTool implements Tool {
};
}
- private async navigateToView(
- viewName: string,
- workspaceId: string,
- userWorkspaceId?: string,
- ): Promise<ToolOutput<NavigateAppToolOutput>> {
- const views = await this.viewService.findByWorkspaceId(
- workspaceId,
- userWorkspaceId,
- );
-
- const fuse = new Fuse(views, {
- keys: ['name'],
- threshold: 0.4,
- });
-
- const results = fuse.search(viewName);
- const matchingView = results[0]?.item;
-
- if (!matchingView) {
- const availableViewNames = views.map((view) => view.name).join(', ');
-
- return {
- success: false,
- message: `View "${viewName}" not found`,
- error: `No view matching "${viewName}" was found in this workspace. Available views: ${availableViewNames}`,
- };
- }
-
- const { flatObjectMetadataMaps } =
+ private async navigateToView({
+ viewId,
+ workspaceId,
+ userWorkspaceId,
+ }: {
+ viewId: string;
+ workspaceId: string;
+ userWorkspaceId?: string;
+ }): Promise<ToolOutput<NavigateAppToolOutput>> {
+ const { flatObjectMetadataMaps, flatViewMaps } =
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
- flatMapsKeys: ['flatObjectMetadataMaps'],
+ flatMapsKeys: ['flatObjectMetadataMaps', 'flatViewMaps'],
},
);
- const objectMetadataUniversalIdentifier =
- flatObjectMetadataMaps.universalIdentifierById[
- matchingView.objectMetadataId
- ];
-
- const objectMetadata = isDefined(objectMetadataUniversalIdentifier)
- ? flatObjectMetadataMaps.byUniversalIdentifier[
- objectMetadataUniversalIdentifier
- ]
- : undefined;
-
- if (!isDefined(objectMetadata)) {
- return {
- success: false,
- message: `Object metadata for view "${matchingView.name}" not found`,
- error: `Could not resolve the object associated with view "${matchingView.name}"`,
- };
- }
+ const isInitialObjectViewEnabled =
+ await this.featureFlagService.isFeatureEnabled(
+ FeatureFlagKey.IS_INITIAL_OBJECT_VIEW_ENABLED,
+ workspaceId,
+ );
- return {
- success: true,
- message: `Navigating to view "${matchingView.name}"`,
- result: {
- action: 'navigateToView',
- viewId: matchingView.id,
- viewName: matchingView.name,
- objectNameSingular: objectMetadata.nameSingular,
- },
- };
+ return buildNavigateToViewOutput({
+ viewId,
+ flatView: findFlatEntityByIdInFlatEntityMaps({
+ flatEntityId: viewId,
+ flatEntityMaps: flatViewMaps,
+ }),
+ userWorkspaceId,
+ isInitialObjectViewEnabled,
+ flatObjectMetadataMaps,
+ });
}
private async navigateToObject(
@@ -260,147 +230,60 @@ export class NavigateAppTool implements Tool {
};
}
- private async navigateToRecord(
- objectNameSingular: string,
- recordName: string,
- workspaceId: string,
- ): Promise<ToolOutput<NavigateAppToolOutput>> {
- const { flatObjectMetadataMaps, flatFieldMetadataMaps } =
+ private async navigateToRecord({
+ objectNameSingular,
+ recordId,
+ workspaceId,
+ rolePermissionConfig,
+ }: {
+ objectNameSingular: string;
+ recordId: string;
+ workspaceId: string;
+ rolePermissionConfig?: RolePermissionConfig;
+ }): Promise<ToolOutput<NavigateAppToolOutput>> {
+ const { flatObjectMetadataMaps } =
await this.workspaceManyOrAllFlatEntityMapsCacheService.getOrRecomputeManyOrAllFlatEntityMaps(
{
workspaceId,
- flatMapsKeys: ['flatObjectMetadataMaps', 'flatFieldMetadataMaps'],
+ flatMapsKeys: ['flatObjectMetadataMaps'],
},
);
- const flatObjectMetadata = Object.values(
- flatObjectMetadataMaps.byUniversalIdentifier,
- ).find(
- (metadata): metadata is FlatObjectMetadata =>
- isDefined(metadata) &&
- metadata.nameSingular === objectNameSingular &&
- resolveEffectiveFlatEntityProperty({
- metadataName: 'objectMetadata',
- flatEntity: metadata,
- property: 'isActive',
- }),
- );
-
- if (!isDefined(flatObjectMetadata)) {
- const availableObjectNames = Object.values(
- flatObjectMetadataMaps.byUniversalIdentifier,
- )
- .filter(
- (metadata): metadata is FlatObjectMetadata =>
- isDefined(metadata) &&
- resolveEffectiveFlatEntityProperty({
- metadataName: 'objectMetadata',
- flatEntity: metadata,
- property: 'isActive',
- }),
- )
- .map((metadata) => metadata.nameSingular)
- .join(', ');
-
- return {
- success: false,
- message: `Object "${objectNameSingular}" not found`,
- error: `No object with singular name "${objectNameSingular}" was found. Available objects: ${availableObjectNames}`,
- };
- }
-
- if (!isDefined(flatObjectMetadata.labelIdentifierFieldMetadataId)) {
- return {
- success: false,
- message: `Object "${objectNameSingular}" has no label identifier field`,
- error: `Cannot search records by name for object "${objectNameSingular}" because it has no label identifier field configured.`,
- };
- }
-
- const labelIdentifierField = findFlatEntityByIdInFlatEntityMaps({
- flatEntityId: flatObjectMetadata.labelIdentifierFieldMetadataId,
- flatEntityMaps: flatFieldMetadataMaps,
+ return buildNavigateToRecordOutput({
+ objectNameSingular,
+ recordId,
+ flatObjectMetadataMaps,
+ objectsPermissions: await this.getObjectsPermissions({
+ workspaceId,
+ rolePermissionConfig,
+ }),
});
+ }
- if (!isDefined(labelIdentifierField)) {
- return {
- success: false,
- message: `Label identifier field not found for object "${objectNameSingular}"`,
- error: `The label identifier field metadata could not be resolved for object "${objectNameSingular}".`,
- };
+ // Missing or unloadable permissions fail closed into the not found result
+ private async getObjectsPermissions({
+ workspaceId,
+ rolePermissionConfig,
+ }: {
+ workspaceId: string;
+ rolePermissionConfig?: RolePermissionConfig;
+ }): Promise<ObjectsPermissions> {
+ if (!isDefined(rolePermissionConfig)) {
+ return {};
}
- const isFullName =
- labelIdentifierField.type === FieldMetadataType.FULL_NAME;
-
- const selectColumns = isFullName
- ? [
- 'id',
- `${labelIdentifierField.name}FirstName`,
- `${labelIdentifierField.name}LastName`,
- ]
- : ['id', labelIdentifierField.name];
-
- const authContext = buildSystemAuthContext(workspaceId);
-
- const records = await this.workspaceOrmManager.executeInWorkspaceContext(
- async () => {
- const repository = this.workspaceOrmManager.getRepository<ObjectRecord>(
- objectNameSingular,
- { shouldBypassPermissionChecks: true },
- );
-
- return repository.find({
- select: selectColumns,
- });
- },
- authContext,
- );
-
- const recordsWithDisplayName = records.map((record) => {
- let displayName: string;
-
- if (isFullName) {
- const firstName =
- (record[`${labelIdentifierField.name}FirstName`] as string) ?? '';
- const lastName =
- (record[`${labelIdentifierField.name}LastName`] as string) ?? '';
-
- displayName = `${firstName} ${lastName}`.trim();
- } else {
- displayName = String(record[labelIdentifierField.name] ?? '');
- }
-
- return {
- id: record.id as string,
- displayName,
- };
- });
-
- const fuse = new Fuse(recordsWithDisplayName, {
- keys: ['displayName'],
- threshold: 0.4,
- });
-
- const results = fuse.search(recordName);
- const matchingRecord = results[0]?.item;
-
- if (!isDefined(matchingRecord)) {
- return {
- success: false,
- message: `Record "${recordName}" not found in ${objectNameSingular}`,
- error: `No ${objectNameSingular} record matching "${recordName}" was found.`,
- };
+ try {
+ const { rolesPermissions } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'rolesPermissions',
+ ]);
+
+ return getObjectsPermissionsFromRolePermissionConfig({
+ rolesPermissions,
+ rolePermissionConfig,
+ });
+ } catch {
+ return {};
}
-
- return {
- success: true,
- message: `Navigating to ${objectNameSingular} record "${matchingRecord.displayName}"`,
- result: {
- action: 'navigateToRecord',
- objectNameSingular,
- recordId: matchingRecord.id,
- },
- };
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/__tests__/build-navigate-to-record-output.util.spec.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/__tests__/build-navigate-to-record-output.util.spec.ts
new file mode 100644
index 00000000000..b5a0620a300
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/__tests__/build-navigate-to-record-output.util.spec.ts
@@ -0,0 +1,112 @@
+import { type ObjectPermissions } from 'twenty-shared/types';
+
+import { buildNavigateToRecordOutput } from 'src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-record-output.util';
+import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+
+const RECORD_ID = '20202020-0000-4000-8000-000000000001';
+
+const COMPANY_OBJECT = getFlatObjectMetadataMock({
+ universalIdentifier: 'company-universal-identifier',
+ id: 'company-object-id',
+ nameSingular: 'company',
+});
+
+const ARCHIVED_OBJECT = getFlatObjectMetadataMock({
+ universalIdentifier: 'archived-universal-identifier',
+ id: 'archived-object-id',
+ nameSingular: 'archived',
+ isActive: false,
+});
+
+const EMPTY_FLAT_OBJECT_METADATA_MAPS: FlatEntityMaps<FlatObjectMetadata> =
+ createEmptyFlatEntityMaps();
+
+const FLAT_OBJECT_METADATA_MAPS = [COMPANY_OBJECT, ARCHIVED_OBJECT].reduce(
+ (flatEntityMaps, flatEntity) =>
+ addFlatEntityToFlatEntityMapsOrThrow({ flatEntity, flatEntityMaps }),
+ EMPTY_FLAT_OBJECT_METADATA_MAPS,
+);
+
+const buildObjectPermissions = (
+ canReadObjectRecords: boolean,
+): ObjectPermissions => ({
+ canReadObjectRecords,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ restrictedFields: {},
+ rowLevelPermissionPredicates: [],
+ rowLevelPermissionPredicateGroups: [],
+});
+
+const NOT_FOUND_ERROR = `No company record with id "${RECORD_ID}" was found, or you do not have access to it.`;
+
+describe('buildNavigateToRecordOutput', () => {
+ it('should return the record route when the caller can read the object', () => {
+ const output = buildNavigateToRecordOutput({
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ objectsPermissions: {
+ [COMPANY_OBJECT.id]: buildObjectPermissions(true),
+ },
+ });
+
+ expect(output).toMatchObject({
+ success: true,
+ result: {
+ action: 'navigateToRecord',
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ },
+ });
+ });
+
+ it('should return not found when the caller cannot read the object', () => {
+ const output = buildNavigateToRecordOutput({
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ objectsPermissions: {
+ [COMPANY_OBJECT.id]: buildObjectPermissions(false),
+ },
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.result).toBeUndefined();
+ expect(output.error).toBe(NOT_FOUND_ERROR);
+ });
+
+ it('should return not found when the caller has no permissions on the object', () => {
+ const output = buildNavigateToRecordOutput({
+ objectNameSingular: 'company',
+ recordId: RECORD_ID,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ objectsPermissions: {},
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.error).toBe(NOT_FOUND_ERROR);
+ });
+
+ it.each(['unknown', 'archived'])(
+ 'should return not found for an %s object',
+ (objectNameSingular) => {
+ const output = buildNavigateToRecordOutput({
+ objectNameSingular,
+ recordId: RECORD_ID,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ objectsPermissions: {
+ [ARCHIVED_OBJECT.id]: buildObjectPermissions(true),
+ },
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.result).toBeUndefined();
+ },
+ );
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/__tests__/build-navigate-to-view-output.util.spec.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/__tests__/build-navigate-to-view-output.util.spec.ts
new file mode 100644
index 00000000000..a807797afc0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/__tests__/build-navigate-to-view-output.util.spec.ts
@@ -0,0 +1,193 @@
+import { ViewVisibility } from 'twenty-shared/types';
+
+import { buildNavigateToViewOutput } from 'src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-view-output.util';
+import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { getInitialObjectViewUniversalIdentifier } from 'src/engine/metadata-modules/view/utils/get-initial-object-view-universal-identifier.util';
+
+const VIEW_ID = '20202020-0000-4000-8000-000000000002';
+const CALLER_USER_WORKSPACE_ID = 'caller-user-workspace-id';
+const OTHER_USER_WORKSPACE_ID = 'other-user-workspace-id';
+const VIEW_APPLICATION_UNIVERSAL_IDENTIFIER =
+ '20202020-0000-4000-8000-000000000003';
+
+const COMPANY_OBJECT = getFlatObjectMetadataMock({
+ universalIdentifier: 'company-universal-identifier',
+ id: 'company-object-id',
+ nameSingular: 'company',
+});
+
+const EMPTY_FLAT_OBJECT_METADATA_MAPS: FlatEntityMaps<FlatObjectMetadata> =
+ createEmptyFlatEntityMaps();
+
+const FLAT_OBJECT_METADATA_MAPS = addFlatEntityToFlatEntityMapsOrThrow({
+ flatEntity: COMPANY_OBJECT,
+ flatEntityMaps: EMPTY_FLAT_OBJECT_METADATA_MAPS,
+});
+
+const INITIAL_VIEW_UNIVERSAL_IDENTIFIER =
+ getInitialObjectViewUniversalIdentifier({
+ viewApplicationUniversalIdentifier: VIEW_APPLICATION_UNIVERSAL_IDENTIFIER,
+ objectUniversalIdentifier: COMPANY_OBJECT.universalIdentifier,
+ });
+
+const buildView = ({
+ visibility = ViewVisibility.WORKSPACE,
+ createdByUserWorkspaceId = OTHER_USER_WORKSPACE_ID,
+ objectMetadataId = COMPANY_OBJECT.id,
+ universalIdentifier = 'key-accounts-view-universal-identifier',
+ deletedAt = null,
+}: {
+ visibility?: ViewVisibility;
+ createdByUserWorkspaceId?: string;
+ objectMetadataId?: string;
+ universalIdentifier?: string;
+ deletedAt?: string | null;
+}) => ({
+ id: VIEW_ID,
+ name: 'Key accounts',
+ objectMetadataId,
+ visibility,
+ createdByUserWorkspaceId,
+ deletedAt,
+ universalIdentifier,
+ applicationUniversalIdentifier: VIEW_APPLICATION_UNIVERSAL_IDENTIFIER,
+ objectMetadataUniversalIdentifier: COMPANY_OBJECT.universalIdentifier,
+});
+
+const NOT_FOUND_ERROR = `No view with id "${VIEW_ID}" was found, or you do not have access to it. Use get_views to list the views you can open.`;
+
+describe('buildNavigateToViewOutput', () => {
+ it('should return the view route for a workspace view', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({ visibility: ViewVisibility.WORKSPACE }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output).toMatchObject({
+ success: true,
+ result: {
+ action: 'navigateToView',
+ viewId: VIEW_ID,
+ viewName: 'Key accounts',
+ objectNameSingular: 'company',
+ },
+ });
+ });
+
+ it('should return the view route for an unlisted view created by the caller', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({
+ visibility: ViewVisibility.UNLISTED,
+ createdByUserWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(true);
+ });
+
+ it("should return not found for another user's unlisted view", () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({ visibility: ViewVisibility.UNLISTED }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.result).toBeUndefined();
+ expect(output.error).toBe(NOT_FOUND_ERROR);
+ });
+
+ it('should return not found for an unlisted view when the caller has no user workspace', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({ visibility: ViewVisibility.UNLISTED }),
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(false);
+ });
+
+ it('should return not found for a missing view', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: undefined,
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.error).toBe(NOT_FOUND_ERROR);
+ });
+
+ it('should return not found when the view object no longer exists', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({
+ visibility: ViewVisibility.WORKSPACE,
+ objectMetadataId: 'deleted-object-id',
+ }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(false);
+ });
+
+ it('should return not found for a deleted view', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({ deletedAt: '2026-01-01T00:00:00.000Z' }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(false);
+ });
+
+ it('should return not found for an initial object view while initial object views are disabled', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({
+ universalIdentifier: INITIAL_VIEW_UNIVERSAL_IDENTIFIER,
+ }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: false,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(false);
+ expect(output.error).toBe(NOT_FOUND_ERROR);
+ });
+
+ it('should return the view route for an initial object view while initial object views are enabled', () => {
+ const output = buildNavigateToViewOutput({
+ viewId: VIEW_ID,
+ flatView: buildView({
+ universalIdentifier: INITIAL_VIEW_UNIVERSAL_IDENTIFIER,
+ }),
+ userWorkspaceId: CALLER_USER_WORKSPACE_ID,
+ isInitialObjectViewEnabled: true,
+ flatObjectMetadataMaps: FLAT_OBJECT_METADATA_MAPS,
+ });
+
+ expect(output.success).toBe(true);
+ expect(output.result).toMatchObject({ viewId: VIEW_ID });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-record-output.util.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-record-output.util.ts
new file mode 100644
index 00000000000..f685180a6ae
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-record-output.util.ts
@@ -0,0 +1,55 @@
+import { type NavigateAppToolOutput } from 'twenty-shared/ai';
+import { type ObjectsPermissions } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { resolveEffectiveFlatEntityProperty } from 'src/engine/metadata-modules/overrides/utils/resolve-effective-flat-entity-property.util';
+
+// The record itself is never read: the record page applies the caller's permissions when it loads
+export const buildNavigateToRecordOutput = ({
+ objectNameSingular,
+ recordId,
+ flatObjectMetadataMaps,
+ objectsPermissions,
+}: {
+ objectNameSingular: string;
+ recordId: string;
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
+ objectsPermissions: ObjectsPermissions;
+}): ToolOutput<NavigateAppToolOutput> => {
+ const flatObjectMetadata = Object.values(
+ flatObjectMetadataMaps.byUniversalIdentifier,
+ ).find(
+ (metadata): metadata is FlatObjectMetadata =>
+ isDefined(metadata) &&
+ metadata.nameSingular === objectNameSingular &&
+ resolveEffectiveFlatEntityProperty({
+ metadataName: 'objectMetadata',
+ flatEntity: metadata,
+ property: 'isActive',
+ }),
+ );
+
+ if (
+ !isDefined(flatObjectMetadata) ||
+ !objectsPermissions[flatObjectMetadata.id]?.canReadObjectRecords
+ ) {
+ return {
+ success: false,
+ message: `Record not found in ${objectNameSingular}`,
+ error: `No ${objectNameSingular} record with id "${recordId}" was found, or you do not have access to it.`,
+ };
+ }
+
+ return {
+ success: true,
+ message: `Navigating to ${objectNameSingular} record "${recordId}"`,
+ result: {
+ action: 'navigateToRecord',
+ objectNameSingular,
+ recordId,
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-view-output.util.ts b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-view-output.util.ts
new file mode 100644
index 00000000000..d1d57212377
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool/tools/navigate-tool/utils/build-navigate-to-view-output.util.ts
@@ -0,0 +1,70 @@
+import { type NavigateAppToolOutput } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
+import { type FlatView } from 'src/engine/metadata-modules/flat-view/types/flat-view.type';
+import { isViewAvailableToUser } from 'src/engine/metadata-modules/view/utils/is-view-available-to-user.util';
+
+export const buildNavigateToViewOutput = ({
+ viewId,
+ flatView,
+ userWorkspaceId,
+ isInitialObjectViewEnabled,
+ flatObjectMetadataMaps,
+}: {
+ viewId: string;
+ flatView:
+ | Pick<
+ FlatView,
+ | 'id'
+ | 'name'
+ | 'objectMetadataId'
+ | 'deletedAt'
+ | 'visibility'
+ | 'createdByUserWorkspaceId'
+ | 'universalIdentifier'
+ | 'applicationUniversalIdentifier'
+ | 'objectMetadataUniversalIdentifier'
+ >
+ | undefined;
+ userWorkspaceId?: string;
+ isInitialObjectViewEnabled: boolean;
+ flatObjectMetadataMaps: FlatEntityMaps<FlatObjectMetadata>;
+}): ToolOutput<NavigateAppToolOutput> => {
+ const flatObjectMetadata = isDefined(flatView)
+ ? findFlatEntityByIdInFlatEntityMaps({
+ flatEntityId: flatView.objectMetadataId,
+ flatEntityMaps: flatObjectMetadataMaps,
+ })
+ : undefined;
+
+ if (
+ !isDefined(flatView) ||
+ !isViewAvailableToUser({
+ flatView,
+ userWorkspaceId,
+ isInitialObjectViewEnabled,
+ }) ||
+ !isDefined(flatObjectMetadata)
+ ) {
+ return {
+ success: false,
+ message: 'View not found',
+ error: `No view with id "${viewId}" was found, or you do not have access to it. Use get_views to list the views you can open.`,
+ };
+ }
+
+ return {
+ success: true,
+ message: `Navigating to view "${flatView.name}"`,
+ result: {
+ action: 'navigateToView',
+ viewId: flatView.id,
+ viewName: flatView.name,
+ objectNameSingular: flatObjectMetadata.nameSingular,
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts b/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
index aed3c2a2a8b..205f57c2f53 100644
--- a/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool/types/tool-execution-context.type.ts
@@ -1,9 +1,11 @@
import { type CodeExecutionStreamEmitter } from 'src/engine/core-modules/tool-provider/interfaces/code-execution-stream-emitter.type';
+import { type RolePermissionConfig } from 'src/engine/twenty-orm/types/role-permission-config.type';
export type ToolExecutionContext = {
workspaceId: string;
userId?: string;
userWorkspaceId?: string;
threadId?: string;
+ rolePermissionConfig?: RolePermissionConfig;
onCodeExecutionUpdate?: CodeExecutionStreamEmitter;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/services/view.service.ts b/packages/twenty-server/src/engine/metadata-modules/view/services/view.service.ts
index edcec49aca1..a607d6c19cb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/view/services/view.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/view/services/view.service.ts
@@ -6,7 +6,6 @@ import { isDefined } from 'twenty-shared/utils';
import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
-import { isInitialObjectView } from 'src/engine/metadata-modules/view/utils/is-initial-object-view.util';
import { findFlatEntityByIdInFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps-or-throw.util';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { findFlatEntityByUniversalIdentifierOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier-or-throw.util';
@@ -32,7 +31,7 @@ import { UpdateViewInput } from 'src/engine/metadata-modules/view/dtos/inputs/up
import { ViewDTO } from 'src/engine/metadata-modules/view/dtos/view.dto';
import { ViewEntity } from 'src/engine/metadata-modules/view/entities/view.entity';
import { fromFlatViewToViewDto } from 'src/engine/metadata-modules/view/utils/from-flat-view-to-view-dto.util';
-import { isViewVisibleToUser } from 'src/engine/metadata-modules/view/utils/is-view-visible-to-user.util';
+import { isViewAvailableToUser } from 'src/engine/metadata-modules/view/utils/is-view-available-to-user.util';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';
@@ -353,23 +352,24 @@ export class ViewService {
return Object.values(flatViewMaps.byUniversalIdentifier)
.filter(isDefined)
- .filter(
- (flatView) =>
- isInitialObjectViewEnabled || !isInitialObjectView(flatView),
- )
.filter((flatView) => flatView.workspaceId === workspaceId)
.filter(
(flatView) =>
!objectMetadataId || flatView.objectMetadataId === objectMetadataId,
)
- .filter((flatView) => flatView.deletedAt === null)
.filter(
(flatView) =>
!viewTypes ||
viewTypes.length === 0 ||
viewTypes.includes(flatView.type),
)
- .filter((flatView) => isViewVisibleToUser(flatView, userWorkspaceId))
+ .filter((flatView) =>
+ isViewAvailableToUser({
+ flatView,
+ userWorkspaceId,
+ isInitialObjectViewEnabled,
+ }),
+ )
.sort((a, b) => a.position - b.position || a.id.localeCompare(b.id));
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/view/utils/is-view-available-to-user.util.ts b/packages/twenty-server/src/engine/metadata-modules/view/utils/is-view-available-to-user.util.ts
new file mode 100644
index 00000000000..0b9c094bd30
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/view/utils/is-view-available-to-user.util.ts
@@ -0,0 +1,24 @@
+import { type FlatView } from 'src/engine/metadata-modules/flat-view/types/flat-view.type';
+import { isInitialObjectView } from 'src/engine/metadata-modules/view/utils/is-initial-object-view.util';
+import { isViewVisibleToUser } from 'src/engine/metadata-modules/view/utils/is-view-visible-to-user.util';
+
+export const isViewAvailableToUser = ({
+ flatView,
+ userWorkspaceId,
+ isInitialObjectViewEnabled,
+}: {
+ flatView: Pick<
+ FlatView,
+ | 'deletedAt'
+ | 'visibility'
+ | 'createdByUserWorkspaceId'
+ | 'universalIdentifier'
+ | 'applicationUniversalIdentifier'
+ | 'objectMetadataUniversalIdentifier'
+ >;
+ userWorkspaceId?: string;
+ isInitialObjectViewEnabled: boolean;
+}): boolean =>
+ flatView.deletedAt === null &&
+ (isInitialObjectViewEnabled || !isInitialObjectView(flatView)) &&
+ isViewVisibleToUser(flatView, userWorkspaceId);
diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts
index ca9b5edd36e..99a11c3f402 100644
--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts
@@ -408,14 +408,14 @@ STEP 8: For each new custom object, repeat ALL of the following sub-steps before
- **KANBAN views**: Sort by a CURRENCY or NUMERIC field DESC (biggest value first) if one exists, or by createdAt DESC. Add a filter to exclude archived/cancelled records if such a SELECT option exists.
- **CALENDAR views**: Sort by the date field ASC (earliest events first). Add a filter using IS_IN_FUTURE or IS_RELATIVE to show only upcoming records by default.
- **TABLE with groups**: Sort by createdAt DESC (most recent first) and add a filter on a meaningful field (e.g. status IS_NOT "CANCELLED", or amount GREATER_THAN_OR_EQUAL to some threshold that keeps ~80% of the records visible).
- - **MANDATORY**: Navigate to this view immediately using the navigate_app tool — YOU MUST DO THIS FOR EVERY SINGLE VIEW, right after its fields/filters/sorts are set up, without exception
+ - **MANDATORY**: Navigate to this view immediately using the navigate_app tool (navigateToView with the view id returned when you created it) — YOU MUST DO THIS FOR EVERY SINGLE VIEW, right after its fields/filters/sorts are set up, without exception
- Wait 3 seconds so the user can see the view and course-correct if needed
Also create additional views for the standard objects (People, Companies, Opportunities) that showcase the new custom fields:
- For People: a KANBAN view grouped by the new SELECT field you added (e.g. "By Specialisation", "By Status")
- For Opportunities: a KANBAN view grouped by the new stage/status field (pipeline view)
- For Companies: a TABLE view grouped by the new SELECT field
-Navigate to each view after creating it. Wait 3 seconds.
+Navigate to each view after creating it, using navigate_app with the view id returned when you created it. Wait 3 seconds.
Loop STEP 8 for all the custom objects
`,
@@ -1295,7 +1295,7 @@ You help users create and configure views, and the filters and sorts that decide
- update_many_view_fields - Update column configuration
- get_view_fields - List columns in a view
- get_object_metadata / get_field_metadata - Discover objects and their fields
-- navigate_app - Navigate to a view after creation
+- navigate_app - Navigate to a view after creation, by the view id returned by the tool that created it
## upsert_complete_view (preferred)
@@ -1327,7 +1327,7 @@ Example: { "objectNameSingular": "opportunity", "type": "KANBAN", "name": "Pipel
- For CALENDAR: provide both \`calendarFieldName\` (a DATE/DATE_TIME field name) and \`calendarLayout\` ("DAY", "WEEK", or "MONTH").
- For TABLE: No special configuration needed beyond the fields list.
-4. **Navigate**: Use navigate_app to show the user their new view.
+4. **Navigate**: Use navigate_app (navigateToView with the view id returned by upsert_complete_view) to show the user their new view.
## KANBAN Best Practices
diff --git a/packages/twenty-server/test/integration/ai/suites/navigate-app-tool-permissions.integration-spec.ts b/packages/twenty-server/test/integration/ai/suites/navigate-app-tool-permissions.integration-spec.ts
new file mode 100644
index 00000000000..ec0cd303d0a
--- /dev/null
+++ b/packages/twenty-server/test/integration/ai/suites/navigate-app-tool-permissions.integration-spec.ts
@@ -0,0 +1,278 @@
+import { randomUUID } from 'node:crypto';
+
+import request from 'supertest';
+import { findManyObjectMetadata } from 'test/integration/metadata/suites/object-metadata/utils/find-many-object-metadata.util';
+import { upsertObjectPermissions } from 'test/integration/metadata/suites/object-permission/utils/upsert-object-permissions.util';
+import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
+import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';
+import { createOneView } from 'test/integration/metadata/suites/view/utils/create-one-view.util';
+import { destroyOneView } from 'test/integration/metadata/suites/view/utils/destroy-one-view.util';
+import { jestExpectToBeDefined } from 'test/utils/jest-expect-to-be-defined.util.test';
+import { ViewVisibility } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+type NavigateAppToolPayload = {
+ success: boolean;
+ message: string;
+ error?: string;
+ result?: {
+ action: string;
+ objectNameSingular?: string;
+ recordId?: string;
+ viewId?: string;
+ viewName?: string;
+ };
+};
+
+const navigate = async (
+ navigation: Record<string, unknown>,
+ token: string,
+): Promise<NavigateAppToolPayload> => {
+ const id = `call-${randomUUID()}`;
+
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .post('/mcp')
+ .set('Authorization', `Bearer ${token}`)
+ .set('Content-Type', 'application/json')
+ .set('Accept', 'application/json')
+ .send(
+ JSON.stringify({
+ jsonrpc: '2.0',
+ method: 'tools/call',
+ id,
+ params: {
+ name: 'execute_tool',
+ arguments: {
+ toolName: 'navigate_app',
+ arguments: { navigation },
+ },
+ },
+ }),
+ )
+ .expect(200);
+
+ expect(response.body.error).toBeUndefined();
+
+ const text = response.body.result?.content?.[0]?.text;
+
+ expect(typeof text).toBe('string');
+
+ return JSON.parse(text) as NavigateAppToolPayload;
+};
+
+describe('navigate_app tool respects the caller permissions (integration)', () => {
+ const recordId = randomUUID();
+ let restrictedRoleId: string | undefined;
+ let originalMemberRoleId: string | undefined;
+ let unlistedViewId: string | undefined;
+ let workspaceViewId: string | undefined;
+
+ beforeAll(async () => {
+ const { objects } = await findManyObjectMetadata({
+ expectToFail: false,
+ input: { filter: {}, paging: { first: 1000 } },
+ gqlFields: 'id nameSingular',
+ });
+
+ const companyObjectMetadataId = objects?.find(
+ (object) => object.nameSingular === 'company',
+ )?.id;
+ const opportunityObjectMetadataId = objects?.find(
+ (object) => object.nameSingular === 'opportunity',
+ )?.id;
+
+ jestExpectToBeDefined(companyObjectMetadataId);
+ jestExpectToBeDefined(opportunityObjectMetadataId);
+
+ originalMemberRoleId = (await findOneRoleByLabel({ label: 'Member' })).id;
+
+ const { data: roleData } = await createOneRole({
+ expectToFail: false,
+ input: {
+ label: 'Navigate App Tool Test Role',
+ description: 'Role that cannot read opportunities',
+ icon: 'IconSettings',
+ canUpdateAllSettings: false,
+ canAccessAllTools: true,
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: false,
+ canSoftDeleteAllObjectRecords: false,
+ canDestroyAllObjectRecords: false,
+ canBeAssignedToUsers: true,
+ canBeAssignedToAgents: false,
+ canBeAssignedToApiKeys: false,
+ },
+ });
+
+ restrictedRoleId = roleData?.createOneRole?.id;
+
+ jestExpectToBeDefined(restrictedRoleId);
+
+ await upsertObjectPermissions({
+ expectToFail: false,
+ input: {
+ roleId: restrictedRoleId,
+ objectPermissions: [
+ {
+ objectMetadataId: opportunityObjectMetadataId,
+ canReadObjectRecords: false,
+ canUpdateObjectRecords: false,
+ canSoftDeleteObjectRecords: false,
+ canDestroyObjectRecords: false,
+ },
+ ],
+ },
+ });
+
+ await updateWorkspaceMemberRole({
+ input: {
+ roleId: restrictedRoleId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ },
+ expectToFail: false,
+ });
+
+ const { data: unlistedViewData } = await createOneView({
+ expectToFail: false,
+ input: {
+ name: 'Navigate App Tool Unlisted View',
+ objectMetadataId: companyObjectMetadataId,
+ icon: 'IconBuildingSkyscraper',
+ visibility: ViewVisibility.UNLISTED,
+ },
+ });
+
+ unlistedViewId = unlistedViewData?.createView?.id;
+
+ const { data: workspaceViewData } = await createOneView({
+ expectToFail: false,
+ input: {
+ name: 'Navigate App Tool Workspace View',
+ objectMetadataId: companyObjectMetadataId,
+ icon: 'IconBuildingSkyscraper',
+ visibility: ViewVisibility.WORKSPACE,
+ },
+ });
+
+ workspaceViewId = workspaceViewData?.createView?.id;
+
+ jestExpectToBeDefined(unlistedViewId);
+ jestExpectToBeDefined(workspaceViewId);
+ });
+
+ afterAll(async () => {
+ for (const viewId of [unlistedViewId, workspaceViewId]) {
+ if (isDefined(viewId)) {
+ await destroyOneView({ viewId, expectToFail: false });
+ }
+ }
+
+ if (isDefined(originalMemberRoleId)) {
+ await updateWorkspaceMemberRole({
+ input: {
+ roleId: originalMemberRoleId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ },
+ expectToFail: false,
+ });
+ }
+
+ if (isDefined(restrictedRoleId)) {
+ await deleteOneRole({
+ expectToFail: false,
+ input: { idToDelete: restrictedRoleId },
+ });
+ }
+ });
+
+ describe('navigateToRecord', () => {
+ it('should return the record route on an object the caller can read', async () => {
+ const payload = await navigate(
+ { type: 'navigateToRecord', objectNameSingular: 'company', recordId },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(payload.success).toBe(true);
+ expect(payload.result).toEqual({
+ action: 'navigateToRecord',
+ objectNameSingular: 'company',
+ recordId,
+ });
+ });
+
+ it('should return not found on an object the caller cannot read', async () => {
+ const payload = await navigate(
+ {
+ type: 'navigateToRecord',
+ objectNameSingular: 'opportunity',
+ recordId,
+ },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(payload.success).toBe(false);
+ expect(payload.result).toBeUndefined();
+ expect(payload.error).toBe(
+ `No opportunity record with id "${recordId}" was found, or you do not have access to it.`,
+ );
+ });
+
+ it('should return the record route on that object for a caller who can read it', async () => {
+ const payload = await navigate(
+ {
+ type: 'navigateToRecord',
+ objectNameSingular: 'opportunity',
+ recordId,
+ },
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ );
+
+ expect(payload.success).toBe(true);
+ expect(payload.result?.recordId).toBe(recordId);
+ });
+ });
+
+ describe('navigateToView', () => {
+ it('should return the view route for a workspace view', async () => {
+ const payload = await navigate(
+ { type: 'navigateToView', viewId: workspaceViewId },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(payload.success).toBe(true);
+ expect(payload.result).toEqual({
+ action: 'navigateToView',
+ viewId: workspaceViewId,
+ viewName: 'Navigate App Tool Workspace View',
+ objectNameSingular: 'company',
+ });
+ });
+
+ it("should return not found for another user's unlisted view", async () => {
+ const payload = await navigate(
+ { type: 'navigateToView', viewId: unlistedViewId },
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ );
+
+ expect(payload.success).toBe(false);
+ expect(payload.result).toBeUndefined();
+ expect(JSON.stringify(payload)).not.toContain(
+ 'Navigate App Tool Unlisted View',
+ );
+ });
+
+ it('should return the view route for an unlisted view to its creator', async () => {
+ const payload = await navigate(
+ { type: 'navigateToView', viewId: unlistedViewId },
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ );
+
+ expect(payload.success).toBe(true);
+ expect(payload.result?.viewId).toBe(unlistedViewId);
+ });
+ });
+});