Skip to content

fix(kb): fix Linear connector GraphQL type errors and tag slot reuse#3957

Closed
waleedlatif1 wants to merge 8 commits intostagingfrom
waleedlatif1/fix-linear-connector
Closed

fix(kb): fix Linear connector GraphQL type errors and tag slot reuse#3957
waleedlatif1 wants to merge 8 commits intostagingfrom
waleedlatif1/fix-linear-connector

Conversation

@waleedlatif1
Copy link
Copy Markdown
Collaborator

Re-opening of #3919 — originally merged into staging but lost when the branch was accidentally deleted and recreated from main.

TheodoreSpeaks and others added 8 commits April 3, 2026 15:24
* feat(block): add cloudwatch integration

* Fix bun lock

* Add logger, use execution timeout

* Switch metric dimensions to map style input

* Fix attribute names for dimension map

* Fix import styling

---------

Co-authored-by: Theodore Li <theo@sim.ai>
* feat(analytics): posthog audit — remove noise, add 10 new events

Remove task_marked_read (fires automatically on every task view).

Add workspace_id to task_message_sent for group analytics.

New events:
- search_result_selected: block/tool/trigger/workflow/table/file/
  knowledge_base/workspace/task/page/docs with query_length
- workflow_imported: count + format (json/zip)
- workflow_exported: count + format (json/zip)
- folder_created / folder_deleted
- logs_filter_applied: status/workflow/folder/trigger/time
- knowledge_base_document_deleted
- scheduled_task_created / scheduled_task_deleted

* fix(analytics): use usePostHog + captureEvent in hooks, track custom date range

* fix(analytics): always fire scheduled_task_deleted regardless of workspaceId

* fix(analytics): correct format field logic and add missing useCallback deps
…g billing (#3916)

* feat(knowledge): add Live sync option to KB connector modal for Max/Enterprise users

Adds a "Live" (every 5 min) sync frequency option gated to Max and Enterprise plan users.
Includes client-side badge + disabled state, shared sync intervals constant, and server-side
plan validation on both POST and PATCH connector routes.

* fix(knowledge): record embedding usage cost for KB document processing

Adds billing tracking to the KB embedding pipeline, which was previously
generating OpenAI API calls with no cost recorded. Token counts are now
captured from the actual API response and recorded via recordUsage after
successful embedding insertion. BYOK workspaces are excluded from billing.
Applies to all execution paths: direct, BullMQ, and Trigger.dev.

* fix(knowledge): simplify embedding billing — use calculateCost, return modelName

- Use calculateCost() from @/providers/utils instead of inline formula, consistent
  with how LLM billing works throughout the platform
- Return modelName from GenerateEmbeddingsResult so billing uses the actual model
  (handles custom Azure deployments) instead of a hardcoded fallback string
- Fix docs-chunker.ts empty-path fallback to satisfy full GenerateEmbeddingsResult type

* fix(knowledge): remove dev bypass from hasLiveSyncAccess

* chore(knowledge): rename sync-intervals to consts, fix stale TSDoc comment

* improvement(knowledge): extract MaxBadge component, capture billing config once per document

* fix(knowledge): add knowledge-base to usage_log_source enum, fix docs-chunker type

* fix(knowledge): generate migration for knowledge-base usage_log_source enum value

* fix(knowledge): add knowledge-base to usage_log_source enum via drizzle-kit

* fix(knowledge): fix search embedding test mocks, parallelize billing lookups

* fix(knowledge): warn when embedding model has no pricing entry

* fix(knowledge): call checkAndBillOverageThreshold after embedding usage
Clean up newTagSlotMapping into direct assignment, remove unnecessary
comment, and revert ID! back to String! to match Linear SDK types.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add fieldType check to the tag slot reuse logic so a connector with
a matching displayName but different fieldType falls through to fresh
slot allocation instead of silently reusing an incompatible slot.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 4, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
docs Skipped Skipped Apr 4, 2026 11:43pm

Request Review

@cursor
Copy link
Copy Markdown

cursor bot commented Apr 4, 2026

PR Summary

High Risk
High risk because it introduces new AWS CloudWatch APIs that accept AWS credentials and adds new billing/usage accounting paths for knowledge-base embeddings, both of which can impact security and user charges if incorrect.

Overview
Adds a full AWS CloudWatch integration: new internal API routes to query Log Insights, list log groups/streams, fetch log events, list metrics, get metric statistics, and describe alarms; plus matching tool configs, types, selector support for log group/stream pickers, a new CloudWatch block, and a CloudWatchIcon.

Tightens KB connector behavior by gating “Live” (5‑minute) sync behind Max/Enterprise via new hasLiveSyncAccess() checks in connector create/update, and improves tag-slot assignment by reusing existing slots when tag displayName+fieldType match (only creating truly new tag definitions).

Updates embeddings generation to return { embeddings, totalTokens, isBYOK, modelName }, propagates this through callers/tests, and records/bills non-BYOK KB embedding token usage (new usage-log source knowledge-base + migration).

Adds PostHog instrumentation for folder create/delete, schedule create/delete, KB document delete, workflow import/export, logs filter usage, task message sent (now includes workspace_id), and search result selection; removes the task_marked_read event and stops emitting it.

Reviewed by Cursor Bugbot for commit 8b7d5f5. Configure here.

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps bot commented Apr 4, 2026

Greptile Summary

This PR re-introduces changes from #3919, delivering two bug fixes and one new integration: (1) the Linear KB connector now builds GraphQL queries dynamically so null/empty filters are never sent as typed variables, preventing Linear API type errors; (2) the connector-creation flow now reuses existing tag-definition slots when a matching displayName+fieldType entry already exists in the knowledge base, preventing unnecessary slot exhaustion; (3) a full AWS CloudWatch integration is added (tools, block, API routes, selectors).

Key changes:

  • connectors/linear/linear.ts: buildIssuesQuery constructs varDefs and filterClauses only for non-empty values, fixing GraphQL type errors caused by declaring e.g. $teamId: ID! then passing null
  • app/api/knowledge/[id]/connectors/route.ts: Tag-slot allocation now first checks existingByName to reuse occupied slots before calling allocateTagSlots for genuinely new definitions
  • packages/db/migrations/0185_new_gravity.sql: Additive enum migration adding 'knowledge-base' to usage_log_source
  • CloudWatch integration: 7 operations via 7 API routes and a unified block; describe-log-groups and describe-log-streams routes correctly use checkSessionOrInternalAuth to support both the UI selector and tool-executor call paths
  • Two route files have an import statement placed after a const declaration, which violates the project's import-ordering convention

Confidence Score: 5/5

Safe to merge — all P0/P1 concerns are absent; only minor import-ordering style issues remain

The Linear GraphQL fix is correct (dynamic query building avoids null typed variables), the tag-slot reuse logic is sound (deduplication by displayName+fieldType before allocating fresh slots), the DB migration is additive, and the CloudWatch integration follows established patterns with correct auth split between session+internal routes (selectors) and internal-only routes (tool execution). The only findings are two P2 import-order style violations.

apps/sim/app/api/tools/cloudwatch/query-logs/route.ts and describe-log-streams/route.ts — import ordering only

Important Files Changed

Filename Overview
apps/sim/connectors/linear/linear.ts Fixes GraphQL type errors by dynamically building queries with only non-null filter variables; adds mapTags and tagDefinitions for 5 Linear metadata fields
apps/sim/app/api/knowledge/[id]/connectors/route.ts Adds tag-slot reuse: existing slots are reclaimed for matching (displayName+fieldType) definitions before allocating new ones via allocateTagSlots
packages/db/migrations/0185_new_gravity.sql Additive enum migration — adds 'knowledge-base' to usage_log_source; safe and non-destructive
apps/sim/blocks/blocks/cloudwatch.ts New CloudWatch block with 7 operations and basic/advanced mode selectors for log groups and streams
apps/sim/app/api/tools/cloudwatch/query-logs/route.ts New Log Insights query route using checkInternalAuth; import placed after const declaration (style violation)
apps/sim/app/api/tools/cloudwatch/describe-log-streams/route.ts New describe-log-streams route using checkSessionOrInternalAuth; import placed after const declaration (style violation)
apps/sim/app/api/tools/cloudwatch/describe-log-groups/route.ts New describe-log-groups route using checkSessionOrInternalAuth, correctly supporting both UI selector (session) and tool executor (internal) call paths
apps/sim/app/api/tools/cloudwatch/utils.ts Shared CloudWatch utilities for client creation, query polling with timeout fallback, and log stream/event fetching
apps/sim/lib/workflows/subblocks/context.ts Adds awsAccessKeyId, awsSecretAccessKey, awsRegion, and logGroupName to SELECTOR_CONTEXT_FIELDS for cascading CloudWatch selectors
apps/sim/hooks/selectors/types.ts Adds cloudwatch.logGroups, cloudwatch.logStreams selector keys and AWS credential/log-group context fields

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    subgraph Linear Connector Fix
        A[buildIssuesQuery] --> B{teamId set?}
        B -- yes --> C[add $teamId: ID! var + filter clause]
        B -- no --> D[skip]
        A --> E{projectId set?}
        E -- yes --> F[add $projectId: ID! var + filter clause]
        E -- no --> G[skip]
        A --> H{stateFilter set?}
        H -- yes --> I[add $stateFilter: String! var + filter clause]
        H -- no --> J[skip]
        C & F & I --> K[Execute GraphQL with only declared vars]
    end

    subgraph Tag Slot Reuse
        L[POST /connectors] --> M[Fetch existing tag defs for KB]
        M --> N{displayName + fieldType match?}
        N -- yes --> O[Reuse existing slot]
        N -- no --> P[Push to defsNeedingSlots]
        P --> Q[allocateTagSlots from unused pool]
        O & Q --> R[Store tagSlotMapping in sourceConfig]
    end

    subgraph CloudWatch Auth Split
        S[describe-log-groups
describe-log-streams] --> T[checkSessionOrInternalAuth]
        T --> U[Browser selector OR Executor]
        V[query-logs
get-log-events
get-metric-statistics
list-metrics
describe-alarms] --> W[checkInternalAuth]
        W --> X[Executor only]
    end
Loading

Reviews (1): Last reviewed commit: "fix(kb): enable search on connector sele..." | Re-trigger Greptile

Comment on lines +7 to +9
const logger = createLogger('CloudWatchQueryLogs')

import { createCloudWatchLogsClient, pollQueryResults } from '@/app/api/tools/cloudwatch/utils'
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Import after const declaration

The import on line 9 appears after the const logger statement on line 7. Per the project's import-order convention, all imports must come before any non-import statements. TypeScript hoists the import at runtime so this won't crash, but it will fail ESLint's import/first rule and is inconsistent with every other route in the codebase.

Suggested change
const logger = createLogger('CloudWatchQueryLogs')
import { createCloudWatchLogsClient, pollQueryResults } from '@/app/api/tools/cloudwatch/utils'
import { StartQueryCommand } from '@aws-sdk/client-cloudwatch-logs'
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { createCloudWatchLogsClient, pollQueryResults } from '@/app/api/tools/cloudwatch/utils'
const logger = createLogger('CloudWatchQueryLogs')

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +5 to +9

const logger = createLogger('CloudWatchDescribeLogStreams')

import { createCloudWatchLogsClient, describeLogStreams } from '@/app/api/tools/cloudwatch/utils'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Import after const declaration

Same pattern as query-logs/route.ts: the import on line 9 appears after the const logger declaration on line 6. All imports should precede any executable statements.

Suggested change
const logger = createLogger('CloudWatchDescribeLogStreams')
import { createCloudWatchLogsClient, describeLogStreams } from '@/app/api/tools/cloudwatch/utils'
import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
import { createCloudWatchLogsClient, describeLogStreams } from '@/app/api/tools/cloudwatch/utils'
const logger = createLogger('CloudWatchDescribeLogStreams')

@waleedlatif1 waleedlatif1 deleted the waleedlatif1/fix-linear-connector branch April 5, 2026 01:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants