Compare commits

..

No commits in common. "main" and "v4.10.0" have entirely different histories.

86 changed files with 1231 additions and 1564 deletions

View file

@ -21,7 +21,7 @@ AUTH_URL="http://localhost:3000"
DATA_CACHE_DIR=${PWD}/.sourcebot # Path to the sourcebot cache dir (ex. ~/sourcebot/.sourcebot)
SOURCEBOT_PUBLIC_KEY_PATH=${PWD}/public.pem
CONFIG_PATH=${PWD}/config.json # Path to the sourcebot config file (if one exists)
# CONFIG_PATH=${PWD}/config.json # Path to the sourcebot config file (if one exists)
# Email
# EMAIL_FROM_ADDRESS="" # The from address for transactional emails.
@ -29,6 +29,7 @@ CONFIG_PATH=${PWD}/config.json # Path to the sourcebot config file (if one exist
# PostHog
# POSTHOG_PAPIK=""
# NEXT_PUBLIC_POSTHOG_PAPIK=""
# Sentry
# SENTRY_BACKEND_DSN=""

View file

@ -1,4 +1,4 @@
contact_links:
- name: 👾 Discord
url: https://discord.gg/HDScTs3ptP
url: https://discord.gg/GbXMEM5H
about: Something else? Join the Discord!

View file

@ -55,6 +55,7 @@ jobs:
${{ env.IMAGE_PATH }}:latest
build-args: |
NEXT_PUBLIC_SOURCEBOT_VERSION=${{ github.ref_name }}
NEXT_PUBLIC_POSTHOG_PAPIK=${{ vars.NEXT_PUBLIC_POSTHOG_PAPIK }}
NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT=${{ vars.NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT }}
NEXT_PUBLIC_SENTRY_ENVIRONMENT=${{ vars.NEXT_PUBLIC_SENTRY_ENVIRONMENT }}
NEXT_PUBLIC_SENTRY_WEBAPP_DSN=${{ vars.NEXT_PUBLIC_SENTRY_WEBAPP_DSN }}

View file

@ -77,6 +77,7 @@ jobs:
outputs: type=image,name=${{ env.REGISTRY_IMAGE }},push-by-digest=true,name-canonical=true,push=true,annotation.org.opencontainers.image.description=Blazingly fast code search
build-args: |
NEXT_PUBLIC_SOURCEBOT_VERSION=${{ github.ref_name }}
NEXT_PUBLIC_POSTHOG_PAPIK=${{ vars.NEXT_PUBLIC_POSTHOG_PAPIK }}
- name: Export digest
run: |

View file

@ -7,37 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Fixed
- Fixed review agent so that it works with GHES instances [#611](https://github.com/sourcebot-dev/sourcebot/pull/611)
### Added
- Added support for arbitrary user IDs required for OpenShift. [#658](https://github.com/sourcebot-dev/sourcebot/pull/658)
### Updated
- Improved error messages in file source api. [#665](https://github.com/sourcebot-dev/sourcebot/pull/665)
## [4.10.2] - 2025-12-04
### Fixed
- Fixed issue where the disable telemetry flag was not being respected for web server telemetry. [#657](https://github.com/sourcebot-dev/sourcebot/pull/657)
## [4.10.1] - 2025-12-03
### Added
- Added `ALWAYS_INDEX_FILE_PATTERNS` environment variable to allow specifying a comma seperated list of glob patterns matching file paths that should always be indexed, regardless of size or # of trigrams. [#631](https://github.com/sourcebot-dev/sourcebot/pull/631)
- Added button to explore menu to toggle cross-repository search. [#647](https://github.com/sourcebot-dev/sourcebot/pull/647)
- Added server side telemetry for search metrics. [#652](https://github.com/sourcebot-dev/sourcebot/pull/652)
### Fixed
- Fixed issue where single quotes could not be used in search queries. [#629](https://github.com/sourcebot-dev/sourcebot/pull/629)
- Fixed issue where files with special characters would fail to load. [#636](https://github.com/sourcebot-dev/sourcebot/issues/636)
- Fixed Ask performance issues. [#632](https://github.com/sourcebot-dev/sourcebot/pull/632)
- Fixed regression where creating a new Ask thread when unauthenticated would result in a 404. [#641](https://github.com/sourcebot-dev/sourcebot/pull/641)
- Updated react and next package versions to fix CVE 2025-55182. [#654](https://github.com/sourcebot-dev/sourcebot/pull/654)
### Changed
- Changed the default behaviour for code nav to scope references & definitions search to the current repository. [#647](https://github.com/sourcebot-dev/sourcebot/pull/647)
## [4.10.0] - 2025-11-24
### Added

View file

@ -1,4 +1,3 @@
# syntax=docker/dockerfile:1
# ------ Global scope variables ------
# Set of global build arguments.
@ -9,6 +8,11 @@
# @see: https://docs.docker.com/build/building/variables/#scoping
ARG NEXT_PUBLIC_SOURCEBOT_VERSION
# PAPIK = Project API Key
# Note that this key does not need to be kept secret, so it's not
# necessary to use Docker build secrets here.
# @see: https://posthog.com/tutorials/api-capture-events#authenticating-with-the-project-api-key
ARG NEXT_PUBLIC_POSTHOG_PAPIK
ARG NEXT_PUBLIC_SENTRY_ENVIRONMENT
ARG NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT
ARG NEXT_PUBLIC_SENTRY_WEBAPP_DSN
@ -53,6 +57,8 @@ ENV SKIP_ENV_VALIDATION=1
# -----------
ARG NEXT_PUBLIC_SOURCEBOT_VERSION
ENV NEXT_PUBLIC_SOURCEBOT_VERSION=$NEXT_PUBLIC_SOURCEBOT_VERSION
ARG NEXT_PUBLIC_POSTHOG_PAPIK
ENV NEXT_PUBLIC_POSTHOG_PAPIK=$NEXT_PUBLIC_POSTHOG_PAPIK
ARG NEXT_PUBLIC_SENTRY_ENVIRONMENT
ENV NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT
ARG NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT
@ -142,12 +148,14 @@ fi
ENV SKIP_ENV_VALIDATION=0
# ------------------------------
# ------ Runner ------
FROM node-alpine AS runner
# -----------
ARG NEXT_PUBLIC_SOURCEBOT_VERSION
ENV NEXT_PUBLIC_SOURCEBOT_VERSION=$NEXT_PUBLIC_SOURCEBOT_VERSION
ARG NEXT_PUBLIC_POSTHOG_PAPIK
ENV NEXT_PUBLIC_POSTHOG_PAPIK=$NEXT_PUBLIC_POSTHOG_PAPIK
ARG NEXT_PUBLIC_SENTRY_ENVIRONMENT
ENV NEXT_PUBLIC_SENTRY_ENVIRONMENT=$NEXT_PUBLIC_SENTRY_ENVIRONMENT
ARG NEXT_PUBLIC_SENTRY_WEBAPP_DSN
@ -170,12 +178,6 @@ ENV DATA_CACHE_DIR=$DATA_DIR/.sourcebot
ENV DATABASE_DATA_DIR=$DATA_CACHE_DIR/db
ENV REDIS_DATA_DIR=$DATA_CACHE_DIR/redis
ENV SOURCEBOT_PUBLIC_KEY_PATH=/app/public.pem
# PAPIK = Project API Key
# Note that this key does not need to be kept secret, so it's not
# necessary to use Docker build secrets here.
# @see: https://posthog.com/tutorials/api-capture-events#authenticating-with-the-project-api-key
# @note: this is also declared in the shared env.server.ts file.
ENV POSTHOG_PAPIK=phc_lLPuFFi5LH6c94eFJcqvYVFwiJffVcV6HD8U4a1OnRW
# Valid values are: debug, info, warn, error
ENV SOURCEBOT_LOG_LEVEL=info
@ -195,7 +197,6 @@ RUN addgroup -g $GID sourcebot && \
adduser -D -u $UID -h /app -S sourcebot && \
adduser sourcebot postgres && \
adduser sourcebot redis && \
chown -R sourcebot /app && \
adduser sourcebot node && \
mkdir /var/log/sourcebot && \
chown sourcebot /var/log/sourcebot
@ -219,23 +220,22 @@ COPY --from=zoekt-builder \
/cmd/zoekt-index \
/usr/local/bin/
RUN chown -R sourcebot:sourcebot /app
# Copy zoekt proto files (needed for gRPC client at runtime)
COPY --chown=sourcebot:sourcebot vendor/zoekt/grpc/protos /app/vendor/zoekt/grpc/protos
COPY vendor/zoekt/grpc/protos /app/vendor/zoekt/grpc/protos
# Copy all of the things
COPY --chown=sourcebot:sourcebot --from=web-builder /app/packages/web/public ./packages/web/public
COPY --chown=sourcebot:sourcebot --from=web-builder /app/packages/web/.next/standalone ./
COPY --chown=sourcebot:sourcebot --from=web-builder /app/packages/web/.next/static ./packages/web/.next/static
COPY --from=web-builder /app/packages/web/public ./packages/web/public
COPY --from=web-builder /app/packages/web/.next/standalone ./
COPY --from=web-builder /app/packages/web/.next/static ./packages/web/.next/static
COPY --chown=sourcebot:sourcebot --from=backend-builder /app/node_modules ./node_modules
COPY --chown=sourcebot:sourcebot --from=backend-builder /app/packages/backend ./packages/backend
COPY --from=backend-builder /app/node_modules ./node_modules
COPY --from=backend-builder /app/packages/backend ./packages/backend
COPY --chown=sourcebot:sourcebot --from=shared-libs-builder /app/packages/db ./packages/db
COPY --chown=sourcebot:sourcebot --from=shared-libs-builder /app/packages/schemas ./packages/schemas
COPY --chown=sourcebot:sourcebot --from=shared-libs-builder /app/packages/shared ./packages/shared
COPY --chown=sourcebot:sourcebot --from=shared-libs-builder /app/packages/queryLanguage ./packages/queryLanguage
COPY --from=shared-libs-builder /app/node_modules ./node_modules
COPY --from=shared-libs-builder /app/packages/db ./packages/db
COPY --from=shared-libs-builder /app/packages/schemas ./packages/schemas
COPY --from=shared-libs-builder /app/packages/shared ./packages/shared
COPY --from=shared-libs-builder /app/packages/queryLanguage ./packages/queryLanguage
# Fixes git "dubious ownership" issues when the volume is mounted with different permissions to the container.
RUN git config --global safe.directory "*"
@ -246,11 +246,9 @@ RUN mkdir -p /run/postgresql && \
chmod 775 /run/postgresql
# Make app directory accessible to both root and sourcebot user
RUN chown -R sourcebot /app \
&& chgrp -R 0 /app \
&& chmod -R g=u /app
RUN chown -R sourcebot:sourcebot /app
# Make data directory accessible to both root and sourcebot user
RUN chown -R sourcebot /data
RUN chown -R sourcebot:sourcebot /data
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY prefix-output.sh ./prefix-output.sh

View file

@ -144,7 +144,7 @@
"socials": {
"github": "https://github.com/sourcebot-dev/sourcebot",
"twitter": "https://x.com/sourcebot_dev",
"discord": "https://discord.gg/HDScTs3ptP",
"discord": "https://discord.gg/GbXMEM5H",
"linkedin": "https://www.linkedin.com/company/sourcebot"
}
},

View file

@ -25,4 +25,4 @@ Sourcebot's built-in authentication system gates your deployment, and allows adm
# Troubleshooting
- If you experience issues logging in, logging out, or accessing an organization you should have access to, try clearing your cookies & performing a full page refresh (`Cmd/Ctrl + Shift + R` on most browsers).
- Still not working? Reach out to us on our [discord](https://discord.gg/HDScTs3ptP) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose)
- Still not working? Reach out to us on our [discord](https://discord.gg/GbXMEM5H) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose)

View file

@ -35,7 +35,6 @@ The following environment variables allow you to configure your Sourcebot deploy
| `SOURCEBOT_STRUCTURED_LOGGING_FILE` | - | <p>Optional file to log to if structured logging is enabled</p> |
| `SOURCEBOT_TELEMETRY_DISABLED` | `false` | <p>Enables/disables telemetry collection in Sourcebot. See [this doc](/docs/overview.mdx#telemetry) for more info.</p> |
| `DEFAULT_MAX_MATCH_COUNT` | `10000` | <p>The default maximum number of search results to return when using search in the web app.</p> |
| `ALWAYS_INDEX_FILE_PATTERNS` | - | <p>A comma separated list of glob patterns matching file paths that should always be indexed, regardless of size or number of trigrams.</p> |
### Enterprise Environment Variables
| Variable | Default | Description |

View file

@ -69,26 +69,6 @@ To learn more about how to create a connection for a specific code host, check o
<Note>Missing your code host? [Submit a feature request on GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new?template=feature_request.md).</Note>
## Indexing Large Files
By default, Sourcebot will skip indexing files that are larger than 2MB or have more than 20,000 trigrams. You can configure this by setting the `maxFileSize` and `maxTrigramCount` [settings](/docs/configuration/config-file#settings).
These limits can be ignored for specific files by passing in a comma separated list of glob patterns matching file paths to the `ALWAYS_INDEX_FILE_PATTERNS` environment variable. For example:
```bash
# Always index all .sum and .lock files
ALWAYS_INDEX_FILE_PATTERNS=**/*.sum,**/*.lock
```
Files that have been skipped are assigned the `skipped` language. You can view a list of all skipped files by using the following query:
```
lang:skipped
```
## Indexing Binary Files
Binary files cannot be indexed by Sourcebot. See [#575](https://github.com/sourcebot-dev/sourcebot/issues/575) for more information.
## Schema reference
---

View file

@ -21,7 +21,6 @@ import LicenseKeyRequired from '/snippets/license-key-required.mdx'
| **Go to definition** | Clicking the "go to definition" button in the popover or clicking the symbol name navigates to the symbol's definition. |
| **Find references** | Clicking the "find all references" button in the popover lists all references in the explore panel. |
| **Explore panel** | Lists all references and definitions for the symbol selected in the popover. |
| **Cross-repository navigation** | You can search across all repositories by clicking the globe icon in the explore panel. By default, references and definitions are scoped to the repository where the symbol is being resolved. |
## How does it work?

View file

@ -1,11 +1,14 @@
---
title: "Permission syncing"
sidebarTitle: "Permission syncing"
tag: "experimental"
---
import LicenseKeyRequired from '/snippets/license-key-required.mdx'
import ExperimentalFeatureWarning from '/snippets/experimental-feature-warning.mdx'
<LicenseKeyRequired />
<ExperimentalFeatureWarning />
# Overview

View file

@ -78,7 +78,7 @@ If your deployment is dependent on these features, please [reach out](https://gi
After updating your configuration file, restart your Sourcebot deployment to pick up the new changes.
</Step>
<Step title="You're done!">
Congrats, you've successfully migrated to v3! Please let us know what you think of the new features by reaching out on our [discord](https://discord.gg/HDScTs3ptP) or on [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose).
Congrats, you've successfully migrated to v3! Please let us know what you think of the new features by reaching out on our [discord](https://discord.gg/GbXMEM5H) or on [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose).
</Step>
</Steps>
@ -90,4 +90,4 @@ Some things to check:
- Make sure you have a name for each `connection`, and that the name only contains letters, digits, hyphens, or underscores
- Make sure each `connection` has a `type` field with a valid value (`gitlab`, `github`, `gitea`, `gerrit`)
Having troubles migrating from v2 to v3? Reach out to us on [discord](https://discord.gg/HDScTs3ptP) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose) and we'll try our best to help
Having troubles migrating from v2 to v3? Reach out to us on [discord](https://discord.gg/GbXMEM5H) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose) and we'll try our best to help

View file

@ -40,7 +40,7 @@ Please note that the following features are no longer supported in v4:
</Step>
<Step title="You're done!">
Congrats, you've successfully migrated to v4! Please let us know what you think of the new features by reaching out on our [discord](https://discord.gg/HDScTs3ptP) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose)
Congrats, you've successfully migrated to v4! Please let us know what you think of the new features by reaching out on our [discord](https://discord.gg/GbXMEM5H) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose)
</Step>
</Steps>
@ -58,4 +58,4 @@ to finish upgrading to v4 in single-tenant mode.
- If you're hitting issues with signing into your Sourcebot instance, make sure you're setting `AUTH_URL` correctly to your deployment domain (ex. `https://sourcebot.yourcompany.com`)
Having troubles migrating from v3 to v4? Reach out to us on [discord](https://discord.gg/HDScTs3ptP) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose) and we'll try our best to help
Having troubles migrating from v3 to v4? Reach out to us on [discord](https://discord.gg/GbXMEM5H) or [GitHub](https://github.com/sourcebot-dev/sourcebot/issues/new/choose) and we'll try our best to help

View file

@ -66,6 +66,12 @@ fi
echo -e "\e[34m[Info] Sourcebot version: $NEXT_PUBLIC_SOURCEBOT_VERSION\e[0m"
# If we don't have a PostHog key, then we need to disable telemetry.
if [ -z "$NEXT_PUBLIC_POSTHOG_PAPIK" ]; then
echo -e "\e[33m[Warning] NEXT_PUBLIC_POSTHOG_PAPIK was not set. Setting SOURCEBOT_TELEMETRY_DISABLED.\e[0m"
export SOURCEBOT_TELEMETRY_DISABLED=true
fi
if [ -n "$SOURCEBOT_TELEMETRY_DISABLED" ]; then
# Validate that SOURCEBOT_TELEMETRY_DISABLED is either "true" or "false"
if [ "$SOURCEBOT_TELEMETRY_DISABLED" != "true" ] && [ "$SOURCEBOT_TELEMETRY_DISABLED" != "false" ]; then
@ -153,7 +159,7 @@ if [ ! -f "$FIRST_RUN_FILE" ]; then
# (if telemetry is enabled)
if [ "$SOURCEBOT_TELEMETRY_DISABLED" = "false" ]; then
if ! ( curl -L --output /dev/null --silent --fail --header "Content-Type: application/json" -d '{
"api_key": "'"$POSTHOG_PAPIK"'",
"api_key": "'"$NEXT_PUBLIC_POSTHOG_PAPIK"'",
"event": "install",
"distinct_id": "'"$SOURCEBOT_INSTALL_ID"'",
"properties": {
@ -173,7 +179,7 @@ else
if [ "$SOURCEBOT_TELEMETRY_DISABLED" = "false" ]; then
if ! ( curl -L --output /dev/null --silent --fail --header "Content-Type: application/json" -d '{
"api_key": "'"$POSTHOG_PAPIK"'",
"api_key": "'"$NEXT_PUBLIC_POSTHOG_PAPIK"'",
"event": "upgrade",
"distinct_id": "'"$SOURCEBOT_INSTALL_ID"'",
"properties": {

View file

@ -5,9 +5,9 @@ import { PosthogEvent, PosthogEventMap } from './posthogEvents.js';
let posthog: PostHog | undefined = undefined;
if (env.POSTHOG_PAPIK) {
if (clientEnv.NEXT_PUBLIC_POSTHOG_PAPIK) {
posthog = new PostHog(
env.POSTHOG_PAPIK,
clientEnv.NEXT_PUBLIC_POSTHOG_PAPIK,
{
host: "https://us.i.posthog.com",
}

View file

@ -1,5 +1,5 @@
import { Repo } from "@sourcebot/db";
import { createLogger, env } from "@sourcebot/shared";
import { createLogger } from "@sourcebot/shared";
import { exec } from "child_process";
import { INDEX_CACHE_DIR } from "./constants.js";
import { Settings } from "./types.js";
@ -11,8 +11,6 @@ export const indexGitRepository = async (repo: Repo, settings: Settings, revisio
const { path: repoPath } = getRepoPath(repo);
const shardPrefix = getShardPrefix(repo.orgId, repo.id);
const largeFileGlobPatterns = env.ALWAYS_INDEX_FILE_PATTERNS?.split(',').map(pattern => pattern.trim()) ?? [];
const command = [
'zoekt-git-index',
'-allow_missing_branches',
@ -23,7 +21,6 @@ export const indexGitRepository = async (repo: Repo, settings: Settings, revisio
`-tenant_id ${repo.orgId}`,
`-repo_id ${repo.id}`,
`-shard_prefix ${shardPrefix}`,
...largeFileGlobPatterns.map((pattern) => `-large_file ${pattern}`),
repoPath
].join(' ');

View file

@ -1,5 +0,0 @@
-- First, remove the NOT NULL constraint on the createdById column.
ALTER TABLE "Chat" ALTER COLUMN "createdById" DROP NOT NULL;
-- Then, set all chats created by the guest user (id: 1) to have a NULL createdById.
UPDATE "Chat" SET "createdById" = NULL WHERE "createdById" = '1';

View file

@ -437,8 +437,8 @@ model Chat {
name String?
createdBy User? @relation(fields: [createdById], references: [id], onDelete: Cascade)
createdById String?
createdBy User @relation(fields: [createdById], references: [id], onDelete: Cascade)
createdById String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

View file

@ -7,13 +7,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.0.11] - 2025-12-03
### Changed
- Updated API client to match the latest Sourcebot release. [#652](https://github.com/sourcebot-dev/sourcebot/pull/652)
## [1.0.10] - 2025-11-24
### Changed
- Updated API client to match the latest Sourcebot release. [#555](https://github.com/sourcebot-dev/sourcebot/pull/555)

View file

@ -1,6 +1,6 @@
{
"name": "@sourcebot/mcp",
"version": "1.0.11",
"version": "1.0.9",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -8,6 +8,7 @@ export const search = async (request: SearchRequest): Promise<SearchResponse | S
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Org-Domain': '~',
...(env.SOURCEBOT_API_KEY ? { 'X-Sourcebot-Api-Key': env.SOURCEBOT_API_KEY } : {})
},
body: JSON.stringify(request)
@ -25,6 +26,7 @@ export const listRepos = async (): Promise<ListRepositoriesResponse | ServiceErr
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Org-Domain': '~',
...(env.SOURCEBOT_API_KEY ? { 'X-Sourcebot-Api-Key': env.SOURCEBOT_API_KEY } : {})
},
}).then(response => response.json());
@ -41,6 +43,7 @@ export const getFileSource = async (request: FileSourceRequest): Promise<FileSou
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Org-Domain': '~',
...(env.SOURCEBOT_API_KEY ? { 'X-Sourcebot-Api-Key': env.SOURCEBOT_API_KEY } : {})
},
body: JSON.stringify(request)

View file

@ -76,7 +76,6 @@ server.tool(
contextLines: env.DEFAULT_CONTEXT_LINES,
isRegexEnabled: true,
isCaseSensitivityEnabled: caseSensitive,
source: 'mcp'
});
if (isServiceError(response)) {

View file

@ -31,7 +31,6 @@ export const searchOptionsSchema = z.object({
export const searchRequestSchema = z.object({
query: z.string(), // The zoekt query to execute.
source: z.string().optional(), // The source of the search request.
...searchOptionsSchema.shape,
});

View file

@ -1,6 +1,6 @@
// This file was generated by lezer-generator. You probably shouldn't edit it.
export const
negate = 23,
negate = 22,
Program = 1,
OrExpr = 2,
AndExpr = 3,
@ -18,5 +18,4 @@ export const
SymExpr = 15,
RepoSetExpr = 16,
ParenExpr = 17,
QuotedTerm = 18,
Term = 19
Term = 18

File diff suppressed because one or more lines are too long

View file

@ -24,13 +24,12 @@ expr {
NegateExpr |
ParenExpr |
PrefixExpr |
QuotedTerm |
Term
}
NegateExpr { !negate negate (PrefixExpr | ParenExpr) }
ParenExpr { "(" query? ")" }
ParenExpr { "(" query ")" }
PrefixExpr {
ArchivedExpr |
@ -64,8 +63,7 @@ archivedValue { "yes" | "no" | "only" }
forkValue { "yes" | "no" | "only" }
visibilityValue { "public" | "private" | "any" }
QuotedTerm { quotedString }
Term { word }
Term { quotedString | word }
value { quotedString | word }
@ -88,7 +86,9 @@ value { quotedString | word }
quotedString { '"' (!["\\\n] | "\\" _)* '"' }
word { (![ \t\n()]) (![ \t\n():] | ":" | "-")* }
// Allow almost anything in a word except spaces, parens, quotes
// Colons and dashes are allowed anywhere in words (including at the start)
word { (![ \t\n()"]) (![ \t\n()":] | ":" | "-")* }
space { $[ \t\n]+ }

View file

@ -4,7 +4,7 @@
==>
Program(ParenExpr)
Program(ParenExpr(Term(⚠)))
# Simple grouping

View file

@ -12,7 +12,7 @@ Program(Term)
==>
Program(QuotedTerm)
Program(Term)
# Dash in middle
@ -244,7 +244,7 @@ Program(NegateExpr(ParenExpr(AndExpr(PrefixExpr(FileExpr),PrefixExpr(LangExpr)))
==>
Program(NegateExpr(ParenExpr))
Program(NegateExpr(ParenExpr(Term(⚠))))
# Negate with space after dash

View file

@ -36,7 +36,7 @@ Program(OrExpr(Term,NegateExpr(PrefixExpr(FileExpr))))
==>
Program(OrExpr(QuotedTerm,QuotedTerm))
Program(OrExpr(Term,Term))
# OR with different prefixes
@ -260,7 +260,7 @@ Program(OrExpr(PrefixExpr(FileExpr),PrefixExpr(FileExpr)))
==>
Program(OrExpr(ParenExpr,ParenExpr))
Program(OrExpr(ParenExpr(Term(⚠)),ParenExpr(Term(⚠))))
# OR with negated groups

View file

@ -156,7 +156,7 @@ Program(AndExpr(ParenExpr(OrExpr(Term,Term)),ParenExpr(OrExpr(Term,Term))))
==>
Program(QuotedTerm)
Program(Term)
# Prefix with OR value doesn't split
@ -188,7 +188,7 @@ Program(OrExpr(Term,ParenExpr(AndExpr(Term,Term))))
==>
Program(OrExpr(ParenExpr,AndExpr(Term,Term)))
Program(OrExpr(ParenExpr(Term(⚠)),AndExpr(Term,Term)))
# Negation of empty group
@ -196,5 +196,5 @@ Program(OrExpr(ParenExpr,AndExpr(Term,Term)))
==>
Program(AndExpr(NegateExpr(ParenExpr),Term))
Program(AndExpr(NegateExpr(ParenExpr(Term(⚠))),Term))

View file

@ -4,22 +4,6 @@
==>
Program(QuotedTerm)
# Leading unclosed quote
"hello
==>
Program(Term)
# Trailing unclosed quote
hello"
==>
Program(Term)
# Quoted string with spaces
@ -28,7 +12,7 @@ Program(Term)
==>
Program(QuotedTerm)
Program(Term)
# Multiple words in quotes
@ -36,7 +20,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with escaped quote
@ -44,7 +28,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with escaped backslash
@ -52,7 +36,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Double backslash
@ -60,7 +44,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Multiple escaped quotes
@ -68,7 +52,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Mixed escaped characters
@ -76,7 +60,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Empty quoted string
@ -84,7 +68,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with only spaces
@ -92,7 +76,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string in file prefix
@ -132,7 +116,7 @@ Program(PrefixExpr(RevisionExpr))
==>
Program(AndExpr(QuotedTerm,QuotedTerm))
Program(AndExpr(Term,Term))
# Quoted and unquoted mixed
@ -140,7 +124,7 @@ unquoted "quoted string" another
==>
Program(AndExpr(Term,QuotedTerm,Term))
Program(AndExpr(Term,Term,Term))
# Quoted string with parentheses inside
@ -148,7 +132,7 @@ Program(AndExpr(Term,QuotedTerm,Term))
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with brackets
@ -156,7 +140,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with special chars
@ -164,7 +148,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with colons
@ -172,7 +156,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with dashes
@ -180,7 +164,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with dots
@ -188,7 +172,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with regex pattern
@ -196,7 +180,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with forward slashes
@ -204,7 +188,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with underscores
@ -212,7 +196,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with numbers
@ -220,7 +204,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with mixed case
@ -228,7 +212,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted prefix value with spaces
@ -252,7 +236,7 @@ Program(AndExpr(PrefixExpr(FileExpr),PrefixExpr(RepoExpr)))
==>
Program(ParenExpr(QuotedTerm))
Program(ParenExpr(Term))
# Multiple quoted in parentheses
@ -260,7 +244,7 @@ Program(ParenExpr(QuotedTerm))
==>
Program(ParenExpr(AndExpr(QuotedTerm,QuotedTerm)))
Program(ParenExpr(AndExpr(Term,Term)))
# Quoted with escaped newline
@ -268,7 +252,7 @@ Program(ParenExpr(AndExpr(QuotedTerm,QuotedTerm)))
==>
Program(QuotedTerm)
Program(Term)
# Quoted with tab character
@ -276,7 +260,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Lang prefix with quoted value
@ -308,7 +292,7 @@ Program(PrefixExpr(ContentExpr))
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with hash
@ -316,7 +300,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with dollar sign
@ -324,7 +308,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with percent
@ -332,7 +316,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with ampersand
@ -340,7 +324,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with asterisk
@ -348,7 +332,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with plus
@ -356,7 +340,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with equals
@ -364,7 +348,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with angle brackets
@ -372,7 +356,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with pipe
@ -380,7 +364,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with tilde
@ -388,7 +372,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with backtick
@ -396,7 +380,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with question mark
@ -404,7 +388,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with exclamation
@ -412,7 +396,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with semicolon
@ -420,7 +404,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted string with comma
@ -428,7 +412,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Multiple quotes in content
@ -444,7 +428,7 @@ Program(PrefixExpr(ContentExpr))
==>
Program(QuotedTerm)
Program(Term)
# Quoted file prefix as literal
@ -452,7 +436,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted lang prefix as literal
@ -460,7 +444,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Quoted partial prefix
@ -468,7 +452,7 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
Program(Term)
# Mix of quoted prefix and real prefix
@ -476,7 +460,7 @@ Program(QuotedTerm)
==>
Program(AndExpr(QuotedTerm,PrefixExpr(FileExpr)))
Program(AndExpr(Term,PrefixExpr(FileExpr)))
# Quoted short form prefix
@ -484,7 +468,7 @@ Program(AndExpr(QuotedTerm,PrefixExpr(FileExpr)))
==>
Program(QuotedTerm)
Program(Term)
# Quoted revision prefix
@ -492,12 +476,4 @@ Program(QuotedTerm)
==>
Program(QuotedTerm)
# Quotes can be used within words
name\s*=\s*"projectmanagementlugapi lang:HCL
==>
Program(AndExpr(Term, PrefixExpr(LangExpr)))
Program(Term)

View file

@ -7,6 +7,7 @@ export const env = createEnv({
client: {
NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT: z.enum(SOURCEBOT_CLOUD_ENVIRONMENT).optional(),
NEXT_PUBLIC_SOURCEBOT_VERSION: z.string().default("unknown"),
NEXT_PUBLIC_POSTHOG_PAPIK: z.string().optional(),
NEXT_PUBLIC_SENTRY_BACKEND_DSN: z.string().optional(),
NEXT_PUBLIC_SENTRY_ENVIRONMENT: z.string().optional(),
NEXT_PUBLIC_LANGFUSE_PUBLIC_KEY: z.string().optional(),
@ -15,6 +16,7 @@ export const env = createEnv({
runtimeEnvStrict: {
NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT: process.env.NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT,
NEXT_PUBLIC_SOURCEBOT_VERSION: process.env.NEXT_PUBLIC_SOURCEBOT_VERSION,
NEXT_PUBLIC_POSTHOG_PAPIK: process.env.NEXT_PUBLIC_POSTHOG_PAPIK,
NEXT_PUBLIC_SENTRY_BACKEND_DSN: process.env.NEXT_PUBLIC_SENTRY_BACKEND_DSN,
NEXT_PUBLIC_SENTRY_ENVIRONMENT: process.env.NEXT_PUBLIC_SENTRY_ENVIRONMENT,
NEXT_PUBLIC_LANGFUSE_PUBLIC_KEY: process.env.NEXT_PUBLIC_LANGFUSE_PUBLIC_KEY,

View file

@ -120,8 +120,6 @@ export const env = createEnv({
CONFIG_MAX_REPOS_NO_TOKEN: numberSchema.default(Number.MAX_SAFE_INTEGER),
NODE_ENV: z.enum(["development", "test", "production"]),
SOURCEBOT_TELEMETRY_DISABLED: booleanSchema.default('false'),
// @note: this is also declared in the Dockerfile.
POSTHOG_PAPIK: z.string().default("phc_lLPuFFi5LH6c94eFJcqvYVFwiJffVcV6HD8U4a1OnRW"),
// Database variables
// Either DATABASE_URL or DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, and DATABASE_NAME must be set.
@ -221,9 +219,6 @@ export const env = createEnv({
// Configure the default maximum number of search results to return by default.
DEFAULT_MAX_MATCH_COUNT: numberSchema.default(10_000),
// A comma separated list of glob patterns that shwould always be indexed regardless of their size.
ALWAYS_INDEX_FILE_PATTERNS: z.string().optional(),
},
runtimeEnv,
emptyStringAsUndefined: true,

View file

@ -137,7 +137,6 @@
"embla-carousel-auto-scroll": "^8.3.0",
"embla-carousel-react": "^8.3.0",
"escape-string-regexp": "^5.0.0",
"fast-deep-equal": "^3.1.3",
"fuse.js": "^7.0.0",
"google-auth-library": "^10.1.0",
"graphql": "^16.9.0",
@ -147,7 +146,7 @@
"langfuse-vercel": "^3.38.4",
"lucide-react": "^0.517.0",
"micromatch": "^4.0.8",
"next": "^15.5.7",
"next": "15.5.0",
"next-auth": "^5.0.0-beta.30",
"next-navigation-guard": "^0.2.0",
"next-themes": "^0.3.0",
@ -156,12 +155,11 @@
"openai": "^4.98.0",
"parse-diff": "^0.11.1",
"posthog-js": "^1.161.5",
"posthog-node": "^5.15.0",
"pretty-bytes": "^6.1.1",
"psl": "^1.15.0",
"react": "^19.2.1",
"react": "19.1.1",
"react-device-detect": "^2.2.3",
"react-dom": "^19.2.1",
"react-dom": "19.1.1",
"react-hook-form": "^7.53.0",
"react-hotkeys-hook": "^4.5.1",
"react-icons": "^5.3.0",
@ -197,8 +195,8 @@
"@types/node": "^20",
"@types/nodemailer": "^6.4.17",
"@types/psl": "^1.1.3",
"@types/react": "19.2.1",
"@types/react-dom": "19.2.1",
"@types/react": "19.1.10",
"@types/react-dom": "19.1.7",
"@typescript-eslint/eslint-plugin": "^8.40.0",
"@typescript-eslint/parser": "^8.40.0",
"cross-env": "^7.0.3",
@ -218,7 +216,7 @@
"vitest-mock-extended": "^3.1.0"
},
"resolutions": {
"@types/react": "19.2.1",
"@types/react-dom": "19.2.1"
"@types/react": "19.1.10",
"@types/react-dom": "19.1.7"
}
}

View file

@ -38,8 +38,8 @@ const auditService = getAuditService();
/**
* "Service Error Wrapper".
*
* Captures any thrown exceptions, logs them to the console and Sentry,
* and returns a generic unexpected service error.
* Captures any thrown exceptions and converts them to a unexpected
* service error. Also logs them with Sentry.
*/
export const sew = async <T>(fn: () => Promise<T>): Promise<T | ServiceError> => {
try {
@ -52,6 +52,10 @@ export const sew = async <T>(fn: () => Promise<T>): Promise<T | ServiceError> =>
return e.serviceError;
}
if (e instanceof Error) {
return unexpectedError(e.message);
}
return unexpectedError(`An unexpected error occurred. Please try again later.`);
}
}

View file

@ -22,12 +22,8 @@ export const CodePreviewPanel = async ({ path, repoName, revisionName }: CodePre
getRepoInfoByName(repoName),
]);
if (isServiceError(fileSourceResponse)) {
return <div>Error loading file source: {fileSourceResponse.message}</div>
}
if (isServiceError(repoInfoResponse)) {
return <div>Error loading repo info: {repoInfoResponse.message}</div>
if (isServiceError(fileSourceResponse) || isServiceError(repoInfoResponse)) {
return <div>Error loading file source</div>
}
const codeHostInfo = getCodeHostInfoForRepo({

View file

@ -3,6 +3,7 @@
import { ScrollArea } from "@/components/ui/scroll-area";
import { SymbolHoverPopup } from "@/ee/features/codeNav/components/symbolHoverPopup";
import { symbolHoverTargetsExtension } from "@/ee/features/codeNav/components/symbolHoverPopup/symbolHoverTargetsExtension";
import { SymbolDefinition } from "@/ee/features/codeNav/components/symbolHoverPopup/useHoveredOverSymbolInfo";
import { useHasEntitlement } from "@/features/entitlements/useHasEntitlement";
import { useCodeMirrorLanguageExtension } from "@/hooks/useCodeMirrorLanguageExtension";
import { useCodeMirrorTheme } from "@/hooks/useCodeMirrorTheme";
@ -10,10 +11,15 @@ import { useKeymapExtension } from "@/hooks/useKeymapExtension";
import { useNonEmptyQueryParam } from "@/hooks/useNonEmptyQueryParam";
import { search } from "@codemirror/search";
import CodeMirror, { EditorSelection, EditorView, ReactCodeMirrorRef, SelectionRange, ViewUpdate } from "@uiw/react-codemirror";
import { useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { EditorContextMenu } from "../../../components/editorContextMenu";
import { useBrowseNavigation } from "../../hooks/useBrowseNavigation";
import { BrowseHighlightRange, HIGHLIGHT_RANGE_QUERY_PARAM } from "../../hooks/utils";
import { useBrowseState } from "../../hooks/useBrowseState";
import { rangeHighlightingExtension } from "./rangeHighlightingExtension";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { createAuditAction } from "@/ee/features/audit/actions";
import { useDomain } from "@/hooks/useDomain";
interface PureCodePreviewPanelProps {
path: string;
@ -35,6 +41,10 @@ export const PureCodePreviewPanel = ({
const [currentSelection, setCurrentSelection] = useState<SelectionRange>();
const keymapExtension = useKeymapExtension(editorRef?.view);
const hasCodeNavEntitlement = useHasEntitlement("code-nav");
const { updateBrowseState } = useBrowseState();
const { navigateToPath } = useBrowseNavigation();
const domain = useDomain();
const captureEvent = useCaptureEvent();
const highlightRangeQuery = useNonEmptyQueryParam(HIGHLIGHT_RANGE_QUERY_PARAM);
const highlightRange = useMemo((): BrowseHighlightRange | undefined => {
@ -80,6 +90,7 @@ export const PureCodePreviewPanel = ({
}
}
}
}, [highlightRangeQuery]);
const extensions = useMemo(() => {
@ -107,31 +118,90 @@ export const PureCodePreviewPanel = ({
// Scroll the highlighted range into view.
useEffect(() => {
if (!highlightRange || !editorRef || !editorRef.state || !editorRef.view) {
if (!highlightRange || !editorRef || !editorRef.state) {
return;
}
const doc = editorRef.state.doc;
const { start, end } = highlightRange;
const selection = EditorSelection.range(
doc.line(start.lineNumber).from,
doc.line(end.lineNumber).from,
);
const from = doc.line(start.lineNumber).from;
const to = doc.line(end.lineNumber).to;
const selection = EditorSelection.range(from, to);
// When the selection is in view, we don't want to perform any scrolling
// as it could be jarring for the user. If it is not in view, scroll to the
// center of the viewport.
const viewport = editorRef.view.viewport;
const isInView = from >= viewport.from && to <= viewport.to;
const scrollStrategy = isInView ? "nearest" : "center";
editorRef.view?.dispatch({
effects: [
EditorView.scrollIntoView(selection, { y: scrollStrategy }),
EditorView.scrollIntoView(selection, { y: "center" }),
]
});
}, [editorRef, highlightRange]);
const onFindReferences = useCallback((symbolName: string) => {
captureEvent('wa_find_references_pressed', {
source: 'browse',
});
createAuditAction({
action: "user.performed_find_references",
metadata: {
message: symbolName,
},
}, domain)
updateBrowseState({
selectedSymbolInfo: {
repoName,
symbolName,
revisionName,
language,
},
isBottomPanelCollapsed: false,
activeExploreMenuTab: "references",
})
}, [captureEvent, updateBrowseState, repoName, revisionName, language, domain]);
// If we resolve multiple matches, instead of navigating to the first match, we should
// instead popup the bottom sheet with the list of matches.
const onGotoDefinition = useCallback((symbolName: string, symbolDefinitions: SymbolDefinition[]) => {
captureEvent('wa_goto_definition_pressed', {
source: 'browse',
});
createAuditAction({
action: "user.performed_goto_definition",
metadata: {
message: symbolName,
},
}, domain)
if (symbolDefinitions.length === 0) {
return;
}
if (symbolDefinitions.length === 1) {
const symbolDefinition = symbolDefinitions[0];
const { fileName, repoName } = symbolDefinition;
navigateToPath({
repoName,
revisionName,
path: fileName,
pathType: 'blob',
highlightRange: symbolDefinition.range,
})
} else {
updateBrowseState({
selectedSymbolInfo: {
symbolName,
repoName,
revisionName,
language,
},
activeExploreMenuTab: "definitions",
isBottomPanelCollapsed: false,
})
}
}, [captureEvent, navigateToPath, revisionName, updateBrowseState, repoName, language, domain]);
const theme = useCodeMirrorTheme();
return (
@ -155,12 +225,11 @@ export const PureCodePreviewPanel = ({
)}
{editorRef && hasCodeNavEntitlement && (
<SymbolHoverPopup
source="preview"
editorRef={editorRef}
revisionName={revisionName}
language={language}
fileName={path}
repoName={repoName}
onFindReferences={onFindReferences}
onGotoDefinition={onGotoDefinition}
/>
)}
</CodeMirror>

View file

@ -10,7 +10,6 @@ import { useBrowseParams } from "./hooks/useBrowseParams";
import { FileSearchCommandDialog } from "./components/fileSearchCommandDialog";
import { useDomain } from "@/hooks/useDomain";
import { SearchBar } from "../components/searchBar";
import escapeStringRegexp from "escape-string-regexp";
interface LayoutProps {
children: React.ReactNode;
@ -31,7 +30,7 @@ export default function Layout({
<SearchBar
size="sm"
defaults={{
query: `repo:^${escapeStringRegexp(repoName)}$${revisionName ? ` rev:${revisionName}` : ''} `,
query: `repo:${repoName}${revisionName ? ` rev:${revisionName}` : ''} `,
}}
className="w-full"
/>

View file

@ -24,9 +24,9 @@ export default async function Page(props: PageProps) {
const languageModels = await getConfiguredLanguageModelsInfo();
const repos = await getRepos();
const searchContexts = await getSearchContexts(params.domain);
const chatInfo = await getChatInfo({ chatId: params.id });
const chatInfo = await getChatInfo({ chatId: params.id }, params.domain);
const session = await auth();
const chatHistory = session ? await getUserChatHistory() : [];
const chatHistory = session ? await getUserChatHistory(params.domain) : [];
if (isServiceError(chatHistory)) {
throw new ServiceErrorException(chatHistory);

View file

@ -4,6 +4,7 @@ import { useToast } from "@/components/hooks/use-toast";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { updateChatName } from "@/features/chat/actions";
import { useDomain } from "@/hooks/useDomain";
import { isServiceError } from "@/lib/utils";
import { GlobeIcon } from "@radix-ui/react-icons";
import { ChatVisibility } from "@sourcebot/db";
@ -22,6 +23,7 @@ interface ChatNameProps {
export const ChatName = ({ name, visibility, id, isReadonly }: ChatNameProps) => {
const [isRenameDialogOpen, setIsRenameDialogOpen] = useState(false);
const { toast } = useToast();
const domain = useDomain();
const router = useRouter();
const onRenameChat = useCallback(async (name: string) => {
@ -29,7 +31,7 @@ export const ChatName = ({ name, visibility, id, isReadonly }: ChatNameProps) =>
const response = await updateChatName({
chatId: id,
name: name,
});
}, domain);
if (isServiceError(response)) {
toast({
@ -41,7 +43,7 @@ export const ChatName = ({ name, visibility, id, isReadonly }: ChatNameProps) =>
});
router.refresh();
}
}, [id, toast, router]);
}, [id, domain, toast, router]);
return (
<>

View file

@ -9,6 +9,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { deleteChat, updateChatName } from "@/features/chat/actions";
import { useDomain } from "@/hooks/useDomain";
import { cn, isServiceError } from "@/lib/utils";
import { CirclePlusIcon, EllipsisIcon, PencilIcon, TrashIcon } from "lucide-react";
import { useRouter } from "next/navigation";
@ -22,7 +23,6 @@ import { useChatId } from "../useChatId";
import { RenameChatDialog } from "./renameChatDialog";
import { DeleteChatDialog } from "./deleteChatDialog";
import Link from "next/link";
import { SINGLE_TENANT_ORG_DOMAIN } from "@/lib/constants";
interface ChatSidePanelProps {
order: number;
@ -41,6 +41,7 @@ export const ChatSidePanel = ({
isAuthenticated,
isCollapsedInitially,
}: ChatSidePanelProps) => {
const domain = useDomain();
const [isCollapsed, setIsCollapsed] = useState(isCollapsedInitially);
const sidePanelRef = useRef<ImperativePanelHandle>(null);
const router = useRouter();
@ -71,7 +72,7 @@ export const ChatSidePanel = ({
const response = await updateChatName({
chatId,
name: name,
});
}, domain);
if (isServiceError(response)) {
toast({
@ -83,14 +84,14 @@ export const ChatSidePanel = ({
});
router.refresh();
}
}, [router, toast]);
}, [router, toast, domain]);
const onDeleteChat = useCallback(async (chatIdToDelete: string) => {
if (!chatIdToDelete) {
return;
}
const response = await deleteChat({ chatId: chatIdToDelete });
const response = await deleteChat({ chatId: chatIdToDelete }, domain);
if (isServiceError(response)) {
toast({
@ -103,12 +104,12 @@ export const ChatSidePanel = ({
// If we just deleted the current chat, navigate to new chat
if (chatIdToDelete === chatId) {
router.push(`/${SINGLE_TENANT_ORG_DOMAIN}/chat`);
router.push(`/${domain}/chat`);
}
router.refresh();
}
}, [chatId, router, toast]);
}, [chatId, router, toast, domain]);
return (
<>
@ -130,7 +131,7 @@ export const ChatSidePanel = ({
size="sm"
className="w-full"
onClick={() => {
router.push(`/${SINGLE_TENANT_ORG_DOMAIN}/chat`);
router.push(`/${domain}/chat`);
}}
>
<CirclePlusIcon className="w-4 h-4 mr-1" />
@ -144,7 +145,7 @@ export const ChatSidePanel = ({
<div className="flex flex-col">
<p className="text-sm text-muted-foreground mb-4">
<Link
href={`/login?callbackUrl=${encodeURIComponent(`/${SINGLE_TENANT_ORG_DOMAIN}/chat`)}`}
href={`/login?callbackUrl=${encodeURIComponent(`/${domain}/chat`)}`}
className="text-sm text-link hover:underline cursor-pointer"
>
Sign in
@ -162,7 +163,7 @@ export const ChatSidePanel = ({
chat.id === chatId && "bg-muted"
)}
onClick={() => {
router.push(`/${SINGLE_TENANT_ORG_DOMAIN}/chat/${chat.id}`);
router.push(`/${domain}/chat/${chat.id}`);
}}
>
<span className="text-sm truncate">{chat.name ?? 'Untitled chat'}</span>

View file

@ -20,7 +20,7 @@ import { NavigationItems } from "./navigationItems";
import { ProgressIndicator } from "./progressIndicator";
import { TrialIndicator } from "./trialIndicator";
const SOURCEBOT_DISCORD_URL = "https://discord.gg/HDScTs3ptP";
const SOURCEBOT_DISCORD_URL = "https://discord.gg/GbXMEM5H";
const SOURCEBOT_GITHUB_URL = "https://github.com/sourcebot-dev/sourcebot";
interface NavigationMenuProps {

View file

@ -221,7 +221,7 @@ export const SearchBar = ({
metadata: {
message: query,
},
})
}, domain)
const url = createPathWithQueryParams(`/${domain}/search`,
[SearchQueryParams.query, query],

View file

@ -55,7 +55,6 @@ export const useSuggestionsData = ({
query: `file:${suggestionQuery}`,
matches: 15,
contextLines: 1,
source: 'search-bar-file-suggestions'
}),
select: (data): Suggestion[] => {
if (isServiceError(data)) {
@ -76,7 +75,6 @@ export const useSuggestionsData = ({
query: `sym:${suggestionQuery.length > 0 ? suggestionQuery : ".*"}`,
matches: 15,
contextLines: 1,
source: 'search-bar-symbol-suggestions'
}),
select: (data): Suggestion[] => {
if (isServiceError(data)) {

View file

@ -1,16 +1,12 @@
'use client';
import { useBrowseNavigation } from "@/app/[domain]/browse/hooks/useBrowseNavigation";
import { EditorContextMenu } from "@/app/[domain]/components/editorContextMenu";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { SymbolHoverPopup } from "@/ee/features/codeNav/components/symbolHoverPopup";
import { symbolHoverTargetsExtension } from "@/ee/features/codeNav/components/symbolHoverPopup/symbolHoverTargetsExtension";
import { useHasEntitlement } from "@/features/entitlements/useHasEntitlement";
import { SearchResultChunk } from "@/features/search";
import { useCodeMirrorLanguageExtension } from "@/hooks/useCodeMirrorLanguageExtension";
import { useCodeMirrorTheme } from "@/hooks/useCodeMirrorTheme";
import { useKeymapExtension } from "@/hooks/useKeymapExtension";
import { useCodeMirrorLanguageExtension } from "@/hooks/useCodeMirrorLanguageExtension";
import { gutterWidthExtension } from "@/lib/extensions/gutterWidthExtension";
import { highlightRanges, searchResultHighlightExtension } from "@/lib/extensions/searchResultHighlightExtension";
import { search } from "@codemirror/search";
@ -20,6 +16,15 @@ import { Scrollbar } from "@radix-ui/react-scroll-area";
import CodeMirror, { ReactCodeMirrorRef, SelectionRange } from '@uiw/react-codemirror';
import { ArrowDown, ArrowUp } from "lucide-react";
import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useState } from "react";
import { useBrowseNavigation } from "@/app/[domain]/browse/hooks/useBrowseNavigation";
import { SymbolHoverPopup } from "@/ee/features/codeNav/components/symbolHoverPopup";
import { symbolHoverTargetsExtension } from "@/ee/features/codeNav/components/symbolHoverPopup/symbolHoverTargetsExtension";
import { useHasEntitlement } from "@/features/entitlements/useHasEntitlement";
import { SymbolDefinition } from "@/ee/features/codeNav/components/symbolHoverPopup/useHoveredOverSymbolInfo";
import { createAuditAction } from "@/ee/features/audit/actions";
import { useDomain } from "@/hooks/useDomain";
import useCaptureEvent from "@/hooks/useCaptureEvent";
export interface CodePreviewFile {
content: string;
@ -48,6 +53,7 @@ export const CodePreview = ({
const [editorRef, setEditorRef] = useState<ReactCodeMirrorRef | null>(null);
const { navigateToPath } = useBrowseNavigation();
const hasCodeNavEntitlement = useHasEntitlement("code-nav");
const domain = useDomain();
const [gutterWidth, setGutterWidth] = useState(0);
const theme = useCodeMirrorTheme();
@ -56,6 +62,8 @@ export const CodePreview = ({
const languageExtension = useCodeMirrorLanguageExtension(file?.language ?? '', editorRef?.view);
const [currentSelection, setCurrentSelection] = useState<SelectionRange>();
const captureEvent = useCaptureEvent();
const extensions = useMemo(() => {
return [
keymapExtension,
@ -110,6 +118,81 @@ export const CodePreview = ({
onSelectedMatchIndexChange((prev) => prev + 1);
}, [onSelectedMatchIndexChange]);
const onGotoDefinition = useCallback((symbolName: string, symbolDefinitions: SymbolDefinition[]) => {
captureEvent('wa_goto_definition_pressed', {
source: 'preview',
});
createAuditAction({
action: "user.performed_goto_definition",
metadata: {
message: symbolName,
},
}, domain)
if (symbolDefinitions.length === 0) {
return;
}
if (symbolDefinitions.length === 1) {
const symbolDefinition = symbolDefinitions[0];
const { fileName, repoName } = symbolDefinition;
navigateToPath({
repoName,
revisionName: file.revision,
path: fileName,
pathType: 'blob',
highlightRange: symbolDefinition.range,
})
} else {
navigateToPath({
repoName,
revisionName: file.revision,
path: file.filepath,
pathType: 'blob',
setBrowseState: {
selectedSymbolInfo: {
symbolName,
repoName,
revisionName: file.revision,
language: file.language,
},
activeExploreMenuTab: "definitions",
isBottomPanelCollapsed: false,
}
});
}
}, [captureEvent, file.filepath, file.language, file.revision, navigateToPath, repoName, domain]);
const onFindReferences = useCallback((symbolName: string) => {
captureEvent('wa_find_references_pressed', {
source: 'preview',
});
createAuditAction({
action: "user.performed_find_references",
metadata: {
message: symbolName,
},
}, domain)
navigateToPath({
repoName,
revisionName: file.revision,
path: file.filepath,
pathType: 'blob',
setBrowseState: {
selectedSymbolInfo: {
repoName,
symbolName,
revisionName: file.revision,
language: file.language,
},
activeExploreMenuTab: "references",
isBottomPanelCollapsed: false,
}
})
}, [captureEvent, file.filepath, file.language, file.revision, navigateToPath, repoName, domain]);
return (
<div className="flex flex-col h-full">
<div className="flex flex-row bg-accent items-center justify-between pr-3 py-0.5 mt-7">
@ -206,12 +289,11 @@ export const CodePreview = ({
{editorRef && hasCodeNavEntitlement && (
<SymbolHoverPopup
source="preview"
editorRef={editorRef}
language={file.language}
revisionName={file.revision}
fileName={file.filepath}
repoName={repoName}
onFindReferences={onFindReferences}
onGotoDefinition={onGotoDefinition}
/>
)}
</CodeMirror>

View file

@ -129,8 +129,7 @@ export const useStreamedSearch = ({ query, matches, contextLines, whole, isRegex
whole,
isRegexEnabled,
isCaseSensitivityEnabled,
source: 'sourcebot-web-client'
} satisfies SearchRequest),
}),
signal: abortControllerRef.current.signal,
});

View file

@ -1,4 +1,4 @@
import { sew } from "@/actions";
import { sew, withAuth, withOrgMembership } from "@/actions";
import { _getConfiguredLanguageModelsFull, _getAISDKLanguageModelAndOptions, updateChatMessages } from "@/features/chat/actions";
import { createAgentStream } from "@/features/chat/agent";
import { additionalChatRequestParamsSchema, LanguageModelInfo, SBChatMessage, SearchScope } from "@/features/chat/types";
@ -6,10 +6,10 @@ import { getAnswerPartFromAssistantMessage, getLanguageModelKey } from "@/featur
import { ErrorCode } from "@/lib/errorCodes";
import { notFound, schemaValidationError, serviceErrorResponse } from "@/lib/serviceError";
import { isServiceError } from "@/lib/utils";
import { withOptionalAuthV2 } from "@/withAuthV2";
import { prisma } from "@/prisma";
import { LanguageModelV2 as AISDKLanguageModelV2 } from "@ai-sdk/provider";
import * as Sentry from "@sentry/nextjs";
import { PrismaClient } from "@sourcebot/db";
import { OrgRole } from "@sourcebot/db";
import { createLogger } from "@sourcebot/shared";
import {
createUIMessageStream,
@ -34,6 +34,15 @@ const chatRequestSchema = z.object({
})
export async function POST(req: Request) {
const domain = req.headers.get("X-Org-Domain");
if (!domain) {
return serviceErrorResponse({
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.MISSING_ORG_DOMAIN_HEADER,
message: "Missing X-Org-Domain header",
});
}
const requestBody = await req.json();
const parsed = await chatRequestSchema.safeParseAsync(requestBody);
if (!parsed.success) {
@ -47,54 +56,56 @@ export async function POST(req: Request) {
const languageModel = _languageModel as LanguageModelInfo;
const response = await sew(() =>
withOptionalAuthV2(async ({ org, prisma }) => {
// Validate that the chat exists and is not readonly.
const chat = await prisma.chat.findUnique({
where: {
orgId: org.id,
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
// Validate that the chat exists and is not readonly.
const chat = await prisma.chat.findUnique({
where: {
orgId: org.id,
id,
},
});
if (!chat) {
return notFound();
}
if (chat.isReadonly) {
return serviceErrorResponse({
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.INVALID_REQUEST_BODY,
message: "Chat is readonly and cannot be edited.",
});
}
// From the language model ID, attempt to find the
// corresponding config in `config.json`.
const languageModelConfig =
(await _getConfiguredLanguageModelsFull())
.find((model) => getLanguageModelKey(model) === getLanguageModelKey(languageModel));
if (!languageModelConfig) {
return serviceErrorResponse({
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.INVALID_REQUEST_BODY,
message: `Language model ${languageModel.model} is not configured.`,
});
}
const { model, providerOptions } = await _getAISDKLanguageModelAndOptions(languageModelConfig);
return createMessageStreamResponse({
messages,
id,
},
});
if (!chat) {
return notFound();
}
if (chat.isReadonly) {
return serviceErrorResponse({
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.INVALID_REQUEST_BODY,
message: "Chat is readonly and cannot be edited.",
selectedSearchScopes,
model,
modelName: languageModelConfig.displayName ?? languageModelConfig.model,
modelProviderOptions: providerOptions,
domain,
orgId: org.id,
});
}
// From the language model ID, attempt to find the
// corresponding config in `config.json`.
const languageModelConfig =
(await _getConfiguredLanguageModelsFull())
.find((model) => getLanguageModelKey(model) === getLanguageModelKey(languageModel));
if (!languageModelConfig) {
return serviceErrorResponse({
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.INVALID_REQUEST_BODY,
message: `Language model ${languageModel.model} is not configured.`,
});
}
const { model, providerOptions } = await _getAISDKLanguageModelAndOptions(languageModelConfig);
return createMessageStreamResponse({
messages,
id,
selectedSearchScopes,
model,
modelName: languageModelConfig.displayName ?? languageModelConfig.model,
modelProviderOptions: providerOptions,
orgId: org.id,
prisma,
});
})
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true
)
)
if (isServiceError(response)) {
@ -121,8 +132,8 @@ interface CreateMessageStreamResponseProps {
model: AISDKLanguageModelV2;
modelName: string;
modelProviderOptions?: Record<string, Record<string, JSONValue>>;
domain: string;
orgId: number;
prisma: PrismaClient;
}
const createMessageStreamResponse = async ({
@ -132,8 +143,8 @@ const createMessageStreamResponse = async ({
model,
modelName,
modelProviderOptions,
domain,
orgId,
prisma,
}: CreateMessageStreamResponseProps) => {
const latestMessage = messages[messages.length - 1];
const sources = latestMessage.parts
@ -243,7 +254,7 @@ const createMessageStreamResponse = async ({
await updateChatMessages({
chatId: id,
messages
});
}, domain);
},
});

View file

@ -1,25 +1,46 @@
'use server';
import { NextRequest } from "next/server";
import { fetchAuditRecords } from "@/ee/features/audit/actions";
import { ErrorCode } from "@/lib/errorCodes";
import { serviceErrorResponse } from "@/lib/serviceError";
import { isServiceError } from "@/lib/utils";
import { getEntitlements } from "@sourcebot/shared";
import { serviceErrorResponse } from "@/lib/serviceError";
import { StatusCodes } from "http-status-codes";
import { ErrorCode } from "@/lib/errorCodes";
import { env } from "@sourcebot/shared";
import { getEntitlements } from "@sourcebot/shared";
export const GET = async () => {
const entitlements = getEntitlements();
if (!entitlements.includes('audit')) {
return serviceErrorResponse({
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.NOT_FOUND,
message: "Audit logging is not enabled for your license",
});
}
export const GET = async (request: NextRequest) => {
const domain = request.headers.get("X-Org-Domain");
const apiKey = request.headers.get("X-Sourcebot-Api-Key") ?? undefined;
const result = await fetchAuditRecords();
if (isServiceError(result)) {
return serviceErrorResponse(result);
}
return Response.json(result);
if (!domain) {
return serviceErrorResponse({
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.MISSING_ORG_DOMAIN_HEADER,
message: "Missing X-Org-Domain header",
});
}
if (env.SOURCEBOT_EE_AUDIT_LOGGING_ENABLED === 'false') {
return serviceErrorResponse({
statusCode: StatusCodes.NOT_FOUND,
errorCode: ErrorCode.NOT_FOUND,
message: "Audit logging is not enabled",
});
}
const entitlements = getEntitlements();
if (!entitlements.includes('audit')) {
return serviceErrorResponse({
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.NOT_FOUND,
message: "Audit logging is not enabled for your license",
});
}
const result = await fetchAuditRecords(domain, apiKey);
if (isServiceError(result)) {
return serviceErrorResponse(result);
}
return Response.json(result);
};

View file

@ -4,7 +4,6 @@ import { search, searchRequestSchema } from "@/features/search";
import { isServiceError } from "@/lib/utils";
import { NextRequest } from "next/server";
import { schemaValidationError, serviceErrorResponse } from "@/lib/serviceError";
import { captureEvent } from "@/lib/posthog";
export const POST = async (request: NextRequest) => {
const body = await request.json();
@ -17,14 +16,8 @@ export const POST = async (request: NextRequest) => {
const {
query,
source,
...options
} = parsed.data;
await captureEvent('api_code_search_request', {
source: source ?? 'unknown',
type: 'blocking',
});
const response = await search({
queryType: 'string',
@ -35,6 +28,5 @@ export const POST = async (request: NextRequest) => {
if (isServiceError(response)) {
return serviceErrorResponse(response);
}
return Response.json(response);
}

View file

@ -1,7 +1,6 @@
'use server';
import { streamSearch, searchRequestSchema } from '@/features/search';
import { captureEvent } from '@/lib/posthog';
import { schemaValidationError, serviceErrorResponse } from '@/lib/serviceError';
import { isServiceError } from '@/lib/utils';
import { NextRequest } from 'next/server';
@ -16,15 +15,9 @@ export const POST = async (request: NextRequest) => {
const {
query,
source,
...options
} = parsed.data;
await captureEvent('api_code_search_request', {
source: source ?? 'unknown',
type: 'streamed',
});
const stream = await streamSearch({
queryType: 'string',
query,

View file

@ -6,32 +6,28 @@ import { WebhookEventDefinition} from "@octokit/webhooks/types";
import { EndpointDefaults } from "@octokit/types";
import { env } from "@sourcebot/shared";
import { processGitHubPullRequest } from "@/features/agents/review-agent/app";
import { throttling, type ThrottlingOptions } from "@octokit/plugin-throttling";
import { throttling } from "@octokit/plugin-throttling";
import fs from "fs";
import { GitHubPullRequest } from "@/features/agents/review-agent/types";
import { createLogger } from "@sourcebot/shared";
const logger = createLogger('github-webhook');
const DEFAULT_GITHUB_API_BASE_URL = "https://api.github.com";
type GitHubAppBaseOptions = Omit<ConstructorParameters<typeof App>[0], "Octokit"> & { throttle: ThrottlingOptions };
let githubAppBaseOptions: GitHubAppBaseOptions | undefined;
const githubAppCache = new Map<string, App>();
let githubApp: App | undefined;
if (env.GITHUB_REVIEW_AGENT_APP_ID && env.GITHUB_REVIEW_AGENT_APP_WEBHOOK_SECRET && env.GITHUB_REVIEW_AGENT_APP_PRIVATE_KEY_PATH) {
try {
const privateKey = fs.readFileSync(env.GITHUB_REVIEW_AGENT_APP_PRIVATE_KEY_PATH, "utf8");
githubAppBaseOptions = {
const throttledOctokit = Octokit.plugin(throttling);
githubApp = new App({
appId: env.GITHUB_REVIEW_AGENT_APP_ID,
privateKey,
privateKey: privateKey,
webhooks: {
secret: env.GITHUB_REVIEW_AGENT_APP_WEBHOOK_SECRET,
},
Octokit: throttledOctokit,
throttle: {
enabled: true,
onRateLimit: (retryAfter, _options, _octokit, retryCount) => {
onRateLimit: (retryAfter: number, options: Required<EndpointDefaults>, octokit: Octokit, retryCount: number) => {
if (retryCount > 3) {
logger.warn(`Rate limit exceeded: ${retryAfter} seconds`);
return false;
@ -39,55 +35,13 @@ if (env.GITHUB_REVIEW_AGENT_APP_ID && env.GITHUB_REVIEW_AGENT_APP_WEBHOOK_SECRET
return true;
},
onSecondaryRateLimit: (_retryAfter, options) => {
// no retries on secondary rate limits
logger.warn(`SecondaryRateLimit detected for ${options.method} ${options.url}`);
}
},
};
}
});
} catch (error) {
logger.error(`Error initializing GitHub app: ${error}`);
}
}
const normalizeGithubApiBaseUrl = (baseUrl?: string) => {
if (!baseUrl) {
return DEFAULT_GITHUB_API_BASE_URL;
}
return baseUrl.replace(/\/+$/, "");
};
const resolveGithubApiBaseUrl = (headers: Record<string, string>) => {
const enterpriseHost = headers["x-github-enterprise-host"];
if (enterpriseHost) {
return normalizeGithubApiBaseUrl(`https://${enterpriseHost}/api/v3`);
}
return DEFAULT_GITHUB_API_BASE_URL;
};
const getGithubAppForBaseUrl = (baseUrl: string) => {
if (!githubAppBaseOptions) {
return undefined;
}
const normalizedBaseUrl = normalizeGithubApiBaseUrl(baseUrl);
const cachedApp = githubAppCache.get(normalizedBaseUrl);
if (cachedApp) {
return cachedApp;
}
const OctokitWithBaseUrl = Octokit.plugin(throttling).defaults({ baseUrl: normalizedBaseUrl });
const app = new App({
...githubAppBaseOptions,
Octokit: OctokitWithBaseUrl,
});
githubAppCache.set(normalizedBaseUrl, app);
return app;
};
function isPullRequestEvent(eventHeader: string, payload: unknown): payload is WebhookEventDefinition<"pull-request-opened"> | WebhookEventDefinition<"pull-request-synchronize"> {
return eventHeader === "pull_request" && typeof payload === "object" && payload !== null && "action" in payload && typeof payload.action === "string" && (payload.action === "opened" || payload.action === "synchronize");
}
@ -98,16 +52,12 @@ function isIssueCommentEvent(eventHeader: string, payload: unknown): payload is
export const POST = async (request: NextRequest) => {
const body = await request.json();
const headers = Object.fromEntries(Array.from(request.headers.entries(), ([key, value]) => [key.toLowerCase(), value]));
const headers = Object.fromEntries(request.headers.entries());
const githubEvent = headers['x-github-event'];
const githubEvent = headers['x-github-event'] || headers['X-GitHub-Event'];
if (githubEvent) {
logger.info('GitHub event received:', githubEvent);
const githubApiBaseUrl = resolveGithubApiBaseUrl(headers);
logger.debug('Using GitHub API base URL for event', { githubApiBaseUrl });
const githubApp = getGithubAppForBaseUrl(githubApiBaseUrl);
if (!githubApp) {
logger.warn('Received GitHub webhook event but GitHub app env vars are not set');
return Response.json({ status: 'ok' });
@ -163,4 +113,4 @@ export const POST = async (request: NextRequest) => {
}
return Response.json({ status: 'ok' });
}
}

View file

@ -1,15 +1,13 @@
import { cn } from '@/lib/utils'
import React from 'react'
interface KeyboardShortcutHintProps {
shortcut: string
label?: string
className?: string
}
export function KeyboardShortcutHint({ shortcut, label, className }: KeyboardShortcutHintProps) {
export function KeyboardShortcutHint({ shortcut, label }: KeyboardShortcutHintProps) {
return (
<div className={cn("inline-flex items-center", className)} aria-label={label || `Keyboard shortcut: ${shortcut}`}>
<div className="inline-flex items-center" aria-label={label || `Keyboard shortcut: ${shortcut}`}>
<kbd
className="px-2 py-1 font-semibold font-sans border rounded-md"
style={{

View file

@ -37,12 +37,7 @@ export default function RootLayout({
<Toaster />
<SessionProvider>
<PlanProvider entitlements={getEntitlements()}>
<PostHogProvider
isDisabled={env.SOURCEBOT_TELEMETRY_DISABLED === "true"}
// @note: the posthog api key doesn't need to be kept secret,
// so we are safe to send it to the client.
posthogApiKey={env.POSTHOG_PAPIK}
>
<PostHogProvider disabled={env.SOURCEBOT_TELEMETRY_DISABLED === "true"}>
<ThemeProvider
attribute="class"
defaultTheme="system"

View file

@ -32,16 +32,16 @@ function PostHogPageView() {
interface PostHogProviderProps {
children: React.ReactNode
isDisabled: boolean
posthogApiKey: string
disabled: boolean
}
export function PostHogProvider({ children, isDisabled, posthogApiKey }: PostHogProviderProps) {
export function PostHogProvider({ children, disabled }: PostHogProviderProps) {
const { data: session } = useSession();
useEffect(() => {
if (!isDisabled) {
posthog.init(posthogApiKey, {
if (!disabled && env.NEXT_PUBLIC_POSTHOG_PAPIK) {
console.debug(`PostHog telemetry enabled. Cloud environment: ${env.NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT}`);
posthog.init(env.NEXT_PUBLIC_POSTHOG_PAPIK, {
// @see next.config.mjs for path rewrites to the "/ingest" route.
api_host: "/ingest",
person_profiles: 'identified_only',
@ -66,7 +66,7 @@ export function PostHogProvider({ children, isDisabled, posthogApiKey }: PostHog
} else {
console.debug("PostHog telemetry disabled");
}
}, [isDisabled, posthogApiKey]);
}, [disabled]);
useEffect(() => {
if (!session) {

View file

@ -7,7 +7,7 @@ import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 gap-2 cursor-pointer",
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 gap-2",
{
variants: {
variant: {
@ -16,7 +16,9 @@ const toggleVariants = cva(
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-7 w-7 min-w-7 p-0",
default: "h-10 px-3 min-w-10",
sm: "h-9 px-2.5 min-w-9",
lg: "h-11 px-5 min-w-11",
},
},
defaultVariants: {

View file

@ -1,64 +1,59 @@
"use server";
import { sew } from "@/actions";
import { getAuditService } from "@/ee/features/audit/factory";
import { ErrorCode } from "@/lib/errorCodes";
import { ServiceError } from "@/lib/serviceError";
import { prisma } from "@/prisma";
import { withAuthV2, withMinimumOrgRole } from "@/withAuthV2";
import { createLogger } from "@sourcebot/shared";
import { ErrorCode } from "@/lib/errorCodes";
import { StatusCodes } from "http-status-codes";
import { AuditEvent } from "./types";
import { sew, withAuth, withOrgMembership } from "@/actions";
import { OrgRole } from "@sourcebot/db";
import { createLogger } from "@sourcebot/shared";
import { ServiceError } from "@/lib/serviceError";
import { getAuditService } from "@/ee/features/audit/factory";
import { AuditEvent } from "./types";
const auditService = getAuditService();
const logger = createLogger('audit-utils');
export const createAuditAction = async (event: Omit<AuditEvent, 'sourcebotVersion' | 'orgId' | 'actor' | 'target'>) => sew(async () =>
withAuthV2(async ({ user, org }) => {
await auditService.createAudit({
...event,
export const createAuditAction = async (event: Omit<AuditEvent, 'sourcebotVersion' | 'orgId' | 'actor' | 'target'>, domain: string) => sew(async () =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
await auditService.createAudit({ ...event, orgId: org.id, actor: { id: userId, type: "user" }, target: { id: org.id.toString(), type: "org" } })
}, /* minRequiredRole = */ OrgRole.MEMBER), /* allowAnonymousAccess = */ true)
);
export const fetchAuditRecords = async (domain: string, apiKey: string | undefined = undefined) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
try {
const auditRecords = await prisma.audit.findMany({
where: {
orgId: org.id,
actor: { id: user.id, type: "user" },
target: { id: org.id.toString(), type: "org" },
},
orderBy: {
timestamp: 'desc'
}
});
await auditService.createAudit({
action: "audit.fetch",
actor: {
id: userId,
type: "user"
},
target: {
id: org.id.toString(),
type: "org"
},
orgId: org.id
})
})
);
export const fetchAuditRecords = async () => sew(() =>
withAuthV2(async ({ user, org, role }) =>
withMinimumOrgRole(role, OrgRole.OWNER, async () => {
try {
const auditRecords = await prisma.audit.findMany({
where: {
orgId: org.id,
},
orderBy: {
timestamp: 'desc'
}
});
await auditService.createAudit({
action: "audit.fetch",
actor: {
id: user.id,
type: "user"
},
target: {
id: org.id.toString(),
type: "org"
},
orgId: org.id
})
return auditRecords;
} catch (error) {
logger.error('Error fetching audit logs', { error });
return {
statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
errorCode: ErrorCode.UNEXPECTED_ERROR,
message: "Failed to fetch audit logs",
} satisfies ServiceError;
}
}))
return auditRecords;
} catch (error) {
logger.error('Error fetching audit logs', { error });
return {
statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
errorCode: ErrorCode.UNEXPECTED_ERROR,
message: "Failed to fetch audit logs",
} satisfies ServiceError;
}
}, /* minRequiredRole = */ OrgRole.OWNER), /* allowAnonymousAccess = */ true, apiKey ? { apiKey, domain } : undefined)
);

View file

@ -1,23 +1,19 @@
'use client';
import { useBrowseState } from "@/app/[domain]/browse/hooks/useBrowseState";
import { findSearchBasedSymbolDefinitions, findSearchBasedSymbolReferences } from "@/app/api/(client)/client";
import { findSearchBasedSymbolReferences, findSearchBasedSymbolDefinitions} from "@/app/api/(client)/client";
import { AnimatedResizableHandle } from "@/components/ui/animatedResizableHandle";
import { Badge } from "@/components/ui/badge";
import { ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
import { Toggle } from "@/components/ui/toggle";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useDomain } from "@/hooks/useDomain";
import { measure, unwrapServiceError } from "@/lib/utils";
import { unwrapServiceError } from "@/lib/utils";
import { useQuery } from "@tanstack/react-query";
import clsx from "clsx";
import { GlobeIcon, Loader2 } from "lucide-react";
import { useMemo, useState } from "react";
import { Loader2 } from "lucide-react";
import { useMemo } from "react";
import { VscSymbolMisc } from "react-icons/vsc";
import { ReferenceList } from "./referenceList";
import { KeyboardShortcutHint } from "@/app/components/keyboardShortcutHint";
import { useHotkeys } from "react-hotkeys-hook";
import useCaptureEvent from "@/hooks/useCaptureEvent";
interface ExploreMenuProps {
selectedSymbolInfo: {
@ -31,39 +27,27 @@ interface ExploreMenuProps {
export const ExploreMenu = ({
selectedSymbolInfo,
}: ExploreMenuProps) => {
const domain = useDomain();
const captureEvent = useCaptureEvent();
const {
state: { activeExploreMenuTab },
updateBrowseState,
} = useBrowseState();
const [isGlobalSearchEnabled, setIsGlobalSearchEnabled] = useState(false);
const {
data: referencesResponse,
isError: isReferencesResponseError,
isPending: isReferencesResponsePending,
isLoading: isReferencesResponseLoading,
} = useQuery({
queryKey: ["references", selectedSymbolInfo.symbolName, selectedSymbolInfo.repoName, selectedSymbolInfo.revisionName, selectedSymbolInfo.language, domain, isGlobalSearchEnabled],
queryFn: async () => {
const response = await measure(() => unwrapServiceError(
findSearchBasedSymbolReferences({
symbolName: selectedSymbolInfo.symbolName,
language: selectedSymbolInfo.language,
revisionName: selectedSymbolInfo.revisionName,
repoName: isGlobalSearchEnabled ? undefined : selectedSymbolInfo.repoName
})
), 'findSearchBasedSymbolReferences', false);
captureEvent('wa_explore_menu_references_loaded', {
durationMs: response.durationMs,
isGlobalSearchEnabled,
queryKey: ["references", selectedSymbolInfo.symbolName, selectedSymbolInfo.repoName, selectedSymbolInfo.revisionName, selectedSymbolInfo.language, domain],
queryFn: () => unwrapServiceError(
findSearchBasedSymbolReferences({
symbolName: selectedSymbolInfo.symbolName,
language: selectedSymbolInfo.language,
revisionName: selectedSymbolInfo.revisionName,
})
return response.data;
}
),
});
const {
@ -72,32 +56,14 @@ export const ExploreMenu = ({
isPending: isDefinitionsResponsePending,
isLoading: isDefinitionsResponseLoading,
} = useQuery({
queryKey: ["definitions", selectedSymbolInfo.symbolName, selectedSymbolInfo.repoName, selectedSymbolInfo.revisionName, selectedSymbolInfo.language, domain, isGlobalSearchEnabled],
queryFn: async () => {
const response = await measure(() => unwrapServiceError(
findSearchBasedSymbolDefinitions({
symbolName: selectedSymbolInfo.symbolName,
language: selectedSymbolInfo.language,
revisionName: selectedSymbolInfo.revisionName,
repoName: isGlobalSearchEnabled ? undefined : selectedSymbolInfo.repoName
})
), 'findSearchBasedSymbolDefinitions', false);
captureEvent('wa_explore_menu_definitions_loaded', {
durationMs: response.durationMs,
isGlobalSearchEnabled,
queryKey: ["definitions", selectedSymbolInfo.symbolName, selectedSymbolInfo.repoName, selectedSymbolInfo.revisionName, selectedSymbolInfo.language, domain],
queryFn: () => unwrapServiceError(
findSearchBasedSymbolDefinitions({
symbolName: selectedSymbolInfo.symbolName,
language: selectedSymbolInfo.language,
revisionName: selectedSymbolInfo.revisionName,
})
return response.data;
}
});
useHotkeys('shift+a', () => {
setIsGlobalSearchEnabled(prev => !prev);
}, {
enableOnFormTags: true,
enableOnContentEditable: true,
description: "Search all repositories",
),
});
const isPending = isReferencesResponsePending || isDefinitionsResponsePending;
@ -132,52 +98,29 @@ export const ExploreMenu = ({
<ResizablePanel
minSize={10}
maxSize={20}
className="flex flex-col h-full"
>
<div className="flex flex-col p-2">
<div className="flex flex-row items-center justify-between">
<Tooltip
delayDuration={100}
<Tooltip
delayDuration={100}
>
<TooltipTrigger
disabled={true}
className="mr-auto"
>
<TooltipTrigger
disabled={true}
className="mr-auto"
<Badge
variant="outline"
className="w-fit h-fit flex-shrink-0 select-none"
>
<Badge
variant="outline"
className="w-fit h-fit flex-shrink-0 select-none"
>
Search Based
</Badge>
</TooltipTrigger>
<TooltipContent
side="top"
align="center"
>
Symbol references and definitions found using a best-guess search heuristic.
</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<span>
<Toggle
pressed={isGlobalSearchEnabled}
onPressedChange={setIsGlobalSearchEnabled}
>
<GlobeIcon className="w-4 h-4" />
</Toggle>
</span>
</TooltipTrigger>
<TooltipContent side="top" align="center">
Search all repositories
<KeyboardShortcutHint
shortcut="⇧ A"
className="ml-2"
/>
</TooltipContent>
</Tooltip>
</div>
Search Based
</Badge>
</TooltipTrigger>
<TooltipContent
side="top"
align="start"
>
Symbol references and definitions found using a best-guess search heuristic.
</TooltipContent>
</Tooltip>
<div className="flex flex-col gap-1 mt-4">
<Entry
name="References"

View file

@ -1,50 +1,42 @@
import { useBrowseNavigation } from "@/app/[domain]/browse/hooks/useBrowseNavigation";
import { KeyboardShortcutHint } from "@/app/components/keyboardShortcutHint";
import { useToast } from "@/components/hooks/use-toast";
import { Button } from "@/components/ui/button";
import { LoadingButton } from "@/components/ui/loading-button";
import { Separator } from "@/components/ui/separator";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { createAuditAction } from "@/ee/features/audit/actions";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { computePosition, flip, offset, shift, VirtualElement } from "@floating-ui/react";
import { ReactCodeMirrorRef } from "@uiw/react-codemirror";
import { Loader2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { SymbolDefinition, useHoveredOverSymbolInfo } from "./useHoveredOverSymbolInfo";
import { SymbolDefinitionPreview } from "./symbolDefinitionPreview";
import { createPortal } from "react-dom";
import { useHotkeys } from "react-hotkeys-hook";
import { SymbolDefinitionPreview } from "./symbolDefinitionPreview";
import { useHoveredOverSymbolInfo } from "./useHoveredOverSymbolInfo";
import { useToast } from "@/components/hooks/use-toast";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { KeyboardShortcutHint } from "@/app/components/keyboardShortcutHint";
interface SymbolHoverPopupProps {
editorRef: ReactCodeMirrorRef;
language: string;
revisionName: string;
repoName: string;
fileName: string;
source: 'browse' | 'preview' | 'chat';
onFindReferences: (symbolName: string) => void;
onGotoDefinition: (symbolName: string, symbolDefinitions: SymbolDefinition[]) => void;
}
export const SymbolHoverPopup: React.FC<SymbolHoverPopupProps> = ({
editorRef,
revisionName,
language,
repoName,
fileName,
source,
onFindReferences,
onGotoDefinition: _onGotoDefinition,
}) => {
const ref = useRef<HTMLDivElement>(null);
const [isSticky, setIsSticky] = useState(false);
const { toast } = useToast();
const { navigateToPath } = useBrowseNavigation();
const captureEvent = useCaptureEvent();
const symbolInfo = useHoveredOverSymbolInfo({
editorRef,
isSticky,
revisionName,
language,
repoName,
});
// Positions the popup relative to the symbol
@ -85,118 +77,13 @@ export const SymbolHoverPopup: React.FC<SymbolHoverPopupProps> = ({
}
}, [symbolInfo, editorRef]);
// Multiple symbol definitions can exist for the same symbol, but we can only navigate
// and display a preview of one. If the symbol definition exists in the current file,
// then we use that one, otherwise we fallback to the first definition in the list.
const previewedSymbolDefinition = useMemo(() => {
if (!symbolInfo?.symbolDefinitions || symbolInfo.symbolDefinitions.length === 0) {
return undefined;
}
const matchingDefinition = symbolInfo.symbolDefinitions.find(
(definition) => (
definition.fileName === fileName && definition.repoName === repoName
)
);
if (matchingDefinition) {
return matchingDefinition;
}
return symbolInfo.symbolDefinitions[0];
}, [fileName, repoName, symbolInfo?.symbolDefinitions]);
const onGotoDefinition = useCallback(() => {
if (
!symbolInfo ||
!symbolInfo.symbolDefinitions ||
!previewedSymbolDefinition
) {
if (!symbolInfo || !symbolInfo.symbolDefinitions) {
return;
}
captureEvent('wa_goto_definition_pressed', {
source,
});
createAuditAction({
action: "user.performed_goto_definition",
metadata: {
message: symbolInfo.symbolName,
},
});
const {
fileName,
repoName,
revisionName,
language,
range: highlightRange,
} = previewedSymbolDefinition;
navigateToPath({
// Always navigate to the preview symbol definition.
repoName,
revisionName,
path: fileName,
pathType: 'blob',
highlightRange,
// If there are multiple definitions, we should open the Explore panel with the definitions.
...(symbolInfo.symbolDefinitions.length > 1 ? {
setBrowseState: {
selectedSymbolInfo: {
symbolName: symbolInfo.symbolName,
repoName,
revisionName,
language,
},
activeExploreMenuTab: "definitions",
isBottomPanelCollapsed: false,
}
} : {}),
});
}, [
captureEvent,
previewedSymbolDefinition,
navigateToPath,
source,
symbolInfo
]);
const onFindReferences = useCallback(() => {
if (!symbolInfo) {
return;
}
captureEvent('wa_find_references_pressed', {
source,
});
createAuditAction({
action: "user.performed_find_references",
metadata: {
message: symbolInfo.symbolName,
},
})
navigateToPath({
repoName,
revisionName,
path: fileName,
pathType: 'blob',
highlightRange: symbolInfo.range,
setBrowseState: {
selectedSymbolInfo: {
symbolName: symbolInfo.symbolName,
repoName,
revisionName,
language,
},
activeExploreMenuTab: "references",
isBottomPanelCollapsed: false,
}
})
}, [captureEvent, fileName, language, navigateToPath, repoName, revisionName, source, symbolInfo]);
_onGotoDefinition(symbolInfo.symbolName, symbolInfo.symbolDefinitions);
}, [symbolInfo, _onGotoDefinition]);
// @todo: We should probably make the behaviour s.t., the ctrl / cmd key needs to be held
// down to navigate to the definition. We should also only show the underline when the key
@ -213,7 +100,9 @@ export const SymbolHoverPopup: React.FC<SymbolHoverPopupProps> = ({
}, [symbolInfo, onGotoDefinition]);
useHotkeys('alt+shift+f12', () => {
onFindReferences();
if (symbolInfo?.symbolName) {
onFindReferences(symbolInfo.symbolName);
}
}, {
enableOnFormTags: true,
enableOnContentEditable: true,
@ -258,9 +147,9 @@ export const SymbolHoverPopup: React.FC<SymbolHoverPopupProps> = ({
<Loader2 className="w-4 h-4 animate-spin" />
Loading...
</div>
) : previewedSymbolDefinition ? (
) : symbolInfo.symbolDefinitions && symbolInfo.symbolDefinitions.length > 0 ? (
<SymbolDefinitionPreview
symbolDefinition={previewedSymbolDefinition}
symbolDefinition={symbolInfo.symbolDefinitions[0]}
/>
) : (
<p className="text-sm font-medium text-muted-foreground">No hover info found</p>
@ -271,13 +160,13 @@ export const SymbolHoverPopup: React.FC<SymbolHoverPopupProps> = ({
<TooltipTrigger asChild>
<LoadingButton
loading={symbolInfo.isSymbolDefinitionsLoading}
disabled={!previewedSymbolDefinition}
disabled={!symbolInfo.symbolDefinitions || symbolInfo.symbolDefinitions.length === 0}
variant="outline"
size="sm"
onClick={onGotoDefinition}
>
{
!symbolInfo.isSymbolDefinitionsLoading && !previewedSymbolDefinition ?
!symbolInfo.isSymbolDefinitionsLoading && (!symbolInfo.symbolDefinitions || symbolInfo.symbolDefinitions.length === 0) ?
"No definition found" :
`Go to ${symbolInfo.symbolDefinitions && symbolInfo.symbolDefinitions.length > 1 ? "definitions" : "definition"}`
}
@ -297,7 +186,7 @@ export const SymbolHoverPopup: React.FC<SymbolHoverPopupProps> = ({
<Button
variant="outline"
size="sm"
onClick={onFindReferences}
onClick={() => onFindReferences(symbolInfo.symbolName)}
>
Find references
</Button>

View file

@ -1,8 +1,7 @@
import { findSearchBasedSymbolDefinitions } from "@/app/api/(client)/client";
import { SourceRange } from "@/features/search";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { useDomain } from "@/hooks/useDomain";
import { measure, unwrapServiceError } from "@/lib/utils";
import { unwrapServiceError } from "@/lib/utils";
import { useQuery } from "@tanstack/react-query";
import { ReactCodeMirrorRef } from "@uiw/react-codemirror";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@ -13,7 +12,6 @@ interface UseHoveredOverSymbolInfoProps {
isSticky: boolean;
revisionName: string;
language: string;
repoName: string;
}
export type SymbolDefinition = {
@ -21,14 +19,12 @@ export type SymbolDefinition = {
language: string;
fileName: string;
repoName: string;
revisionName: string;
range: SourceRange;
}
interface HoveredOverSymbolInfo {
element: HTMLElement;
symbolName: string;
range: SourceRange;
isSymbolDefinitionsLoading: boolean;
symbolDefinitions?: SymbolDefinition[];
}
@ -41,7 +37,6 @@ export const useHoveredOverSymbolInfo = ({
isSticky,
revisionName,
language,
repoName,
}: UseHoveredOverSymbolInfoProps): HoveredOverSymbolInfo | undefined => {
const mouseOverTimerRef = useRef<NodeJS.Timeout | null>(null);
const mouseOutTimerRef = useRef<NodeJS.Timeout | null>(null);
@ -54,26 +49,15 @@ export const useHoveredOverSymbolInfo = ({
return (symbolElement && symbolElement.textContent) ?? undefined;
}, [symbolElement]);
const captureEvent = useCaptureEvent();
const { data: symbolDefinitions, isLoading: isSymbolDefinitionsLoading } = useQuery({
queryKey: ["definitions", symbolName, revisionName, language, domain, repoName],
queryFn: async () => {
const response = await measure(() => unwrapServiceError(
findSearchBasedSymbolDefinitions({
symbolName: symbolName!,
language,
revisionName,
repoName,
})
), 'findSearchBasedSymbolDefinitions', false);
captureEvent('wa_symbol_hover_popup_definitions_loaded', {
durationMs: response.durationMs,
});
return response.data;
},
queryKey: ["definitions", symbolName, revisionName, language, domain],
queryFn: () => unwrapServiceError(
findSearchBasedSymbolDefinitions({
symbolName: symbolName!,
language,
revisionName,
})
),
select: ((data) => {
return data.files.flatMap((file) => {
return file.matches.map((match) => {
@ -82,7 +66,6 @@ export const useHoveredOverSymbolInfo = ({
language: file.language,
fileName: file.fileName,
repoName: file.repository,
revisionName: revisionName,
range: match.range,
}
})
@ -124,7 +107,7 @@ export const useHoveredOverSymbolInfo = ({
const handleMouseOut = () => {
clearTimers();
mouseOutTimerRef.current = setTimeout(() => {
setIsVisible(false);
}, SYMBOL_HOVER_POPUP_MOUSE_OUT_TIMEOUT_MS);
@ -139,64 +122,17 @@ export const useHoveredOverSymbolInfo = ({
};
}, [editorRef, domain, clearTimers]);
// Extract the highlight range of the symbolElement from the editor view.
const highlightRange = useMemo((): SourceRange | undefined => {
if (!symbolElement || !editorRef.view) {
return undefined;
}
const view = editorRef.view;
const rect = symbolElement.getBoundingClientRect();
// Get the start position (left edge, middle vertically)
const startPos = view.posAtCoords({
x: rect.left,
y: rect.top + rect.height / 2,
});
// Get the end position (right edge, middle vertically)
const endPos = view.posAtCoords({
x: rect.right,
y: rect.top + rect.height / 2,
});
if (startPos === null || endPos === null) {
return undefined;
}
// Convert CodeMirror positions to SourceRange format
const startLine = view.state.doc.lineAt(startPos);
const endLine = view.state.doc.lineAt(endPos);
const startColumn = startPos - startLine.from + 1; // 1-based column
const endColumn = endPos - endLine.from + 1; // 1-based column
return {
start: {
byteOffset: startPos, // 0-based byte offset
lineNumber: startLine.number, // 1-based line number
column: startColumn, // 1-based column
},
end: {
byteOffset: endPos, // 0-based byte offset
lineNumber: endLine.number, // 1-based line number
column: endColumn, // 1-based column
},
};
}, [symbolElement, editorRef.view]);
if (!isVisible && !isSticky) {
return undefined;
}
if (!symbolElement || !symbolName || !highlightRange) {
if (!symbolElement || !symbolName) {
return undefined;
}
return {
element: symbolElement,
symbolName,
range: highlightRange,
isSymbolDefinitionsLoading: isSymbolDefinitionsLoading,
symbolDefinitions,
};

View file

@ -1,8 +1,10 @@
'use server';
import { sew } from "@/actions";
import { sew, withAuth, withOrgMembership } from "@/actions";
import { SOURCEBOT_GUEST_USER_ID } from "@/lib/constants";
import { ErrorCode } from "@/lib/errorCodes";
import { chatIsReadonly, notFound, ServiceError, serviceErrorResponse } from "@/lib/serviceError";
import { prisma } from "@/prisma";
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';
import { AnthropicProviderOptions, createAnthropic } from '@ai-sdk/anthropic';
import { createAzure } from '@ai-sdk/azure';
@ -18,7 +20,7 @@ import { createXai } from '@ai-sdk/xai';
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { getTokenFromConfig, createLogger, env } from "@sourcebot/shared";
import { ChatVisibility, Prisma } from "@sourcebot/db";
import { ChatVisibility, OrgRole, Prisma } from "@sourcebot/db";
import { LanguageModel } from "@sourcebot/schemas/v3/languageModel.type";
import { Token } from "@sourcebot/schemas/v3/shared.type";
import { generateText, JSONValue, extractReasoningMiddleware, wrapLanguageModel } from "ai";
@ -27,161 +29,168 @@ import fs from 'fs';
import { StatusCodes } from "http-status-codes";
import path from 'path';
import { LanguageModelInfo, SBChatMessage } from "./types";
import { withAuthV2, withOptionalAuthV2 } from "@/withAuthV2";
const logger = createLogger('chat-actions');
export const createChat = async () => sew(() =>
withOptionalAuthV2(async ({ org, user, prisma }) => {
const isGuestUser = user === undefined;
export const createChat = async (domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chat = await prisma.chat.create({
data: {
orgId: org.id,
messages: [] as unknown as Prisma.InputJsonValue,
createdById: user?.id,
visibility: isGuestUser ? ChatVisibility.PUBLIC : ChatVisibility.PRIVATE,
},
});
const isGuestUser = userId === SOURCEBOT_GUEST_USER_ID;
return {
id: chat.id,
}
})
const chat = await prisma.chat.create({
data: {
orgId: org.id,
messages: [] as unknown as Prisma.InputJsonValue,
createdById: userId,
visibility: isGuestUser ? ChatVisibility.PUBLIC : ChatVisibility.PRIVATE,
},
});
return {
id: chat.id,
}
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true)
);
export const getChatInfo = async ({ chatId }: { chatId: string }) => sew(() =>
withOptionalAuthV2(async ({ org, user, prisma }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
export const getChatInfo = async ({ chatId }: { chatId: string }, domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
if (!chat) {
return notFound();
}
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== user?.id) {
return notFound();
}
return {
messages: chat.messages as unknown as SBChatMessage[],
visibility: chat.visibility,
name: chat.name,
isReadonly: chat.isReadonly,
};
})
);
export const updateChatMessages = async ({ chatId, messages }: { chatId: string, messages: SBChatMessage[] }) => sew(() =>
withOptionalAuthV2(async ({ org, user, prisma }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
if (!chat) {
return notFound();
}
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== user?.id) {
return notFound();
}
if (chat.isReadonly) {
return chatIsReadonly();
}
await prisma.chat.update({
where: {
id: chatId,
},
data: {
messages: messages as unknown as Prisma.InputJsonValue,
},
});
if (env.DEBUG_WRITE_CHAT_MESSAGES_TO_FILE) {
const chatDir = path.join(env.DATA_CACHE_DIR, 'chats');
if (!fs.existsSync(chatDir)) {
fs.mkdirSync(chatDir, { recursive: true });
if (!chat) {
return notFound();
}
const chatFile = path.join(chatDir, `${chatId}.json`);
fs.writeFileSync(chatFile, JSON.stringify(messages, null, 2));
}
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== userId) {
return notFound();
}
return {
success: true,
}
})
return {
messages: chat.messages as unknown as SBChatMessage[],
visibility: chat.visibility,
name: chat.name,
isReadonly: chat.isReadonly,
};
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true)
);
export const getUserChatHistory = async () => sew(() =>
withAuthV2(async ({ org, user, prisma }) => {
const chats = await prisma.chat.findMany({
where: {
orgId: org.id,
createdById: user.id,
},
orderBy: {
updatedAt: 'desc',
},
});
export const updateChatMessages = async ({ chatId, messages }: { chatId: string, messages: SBChatMessage[] }, domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
return chats.map((chat) => ({
id: chat.id,
createdAt: chat.createdAt,
name: chat.name,
visibility: chat.visibility,
}))
})
if (!chat) {
return notFound();
}
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== userId) {
return notFound();
}
if (chat.isReadonly) {
return chatIsReadonly();
}
await prisma.chat.update({
where: {
id: chatId,
},
data: {
messages: messages as unknown as Prisma.InputJsonValue,
},
});
if (env.DEBUG_WRITE_CHAT_MESSAGES_TO_FILE) {
const chatDir = path.join(env.DATA_CACHE_DIR, 'chats');
if (!fs.existsSync(chatDir)) {
fs.mkdirSync(chatDir, { recursive: true });
}
const chatFile = path.join(chatDir, `${chatId}.json`);
fs.writeFileSync(chatFile, JSON.stringify(messages, null, 2));
}
return {
success: true,
}
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true)
);
export const updateChatName = async ({ chatId, name }: { chatId: string, name: string }) => sew(() =>
withOptionalAuthV2(async ({ org, user, prisma }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
export const getUserChatHistory = async (domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chats = await prisma.chat.findMany({
where: {
orgId: org.id,
createdById: userId,
},
orderBy: {
updatedAt: 'desc',
},
});
if (!chat) {
return notFound();
}
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== user?.id) {
return notFound();
}
if (chat.isReadonly) {
return chatIsReadonly();
}
await prisma.chat.update({
where: {
id: chatId,
orgId: org.id,
},
data: {
name,
},
});
return {
success: true,
}
})
return chats.map((chat) => ({
id: chat.id,
createdAt: chat.createdAt,
name: chat.name,
visibility: chat.visibility,
}))
})
)
);
export const generateAndUpdateChatNameFromMessage = async ({ chatId, languageModelId, message }: { chatId: string, languageModelId: string, message: string }) => sew(() =>
withOptionalAuthV2(async () => {
export const updateChatName = async ({ chatId, name }: { chatId: string, name: string }, domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
if (!chat) {
return notFound();
}
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== userId) {
return notFound();
}
if (chat.isReadonly) {
return chatIsReadonly();
}
await prisma.chat.update({
where: {
id: chatId,
orgId: org.id,
},
data: {
name,
},
});
return {
success: true,
}
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true)
);
export const generateAndUpdateChatNameFromMessage = async ({ chatId, languageModelId, message }: { chatId: string, languageModelId: string, message: string }, domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async () => {
// From the language model ID, attempt to find the
// corresponding config in `config.json`.
const languageModelConfig =
@ -222,6 +231,48 @@ User question: ${message}`;
await updateChatName({
chatId,
name: result.text,
}, domain);
return {
success: true,
}
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true
)
);
export const deleteChat = async ({ chatId }: { chatId: string }, domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
if (!chat) {
return notFound();
}
// Public chats cannot be deleted.
if (chat.visibility === ChatVisibility.PUBLIC) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.UNEXPECTED_ERROR,
message: 'You are not allowed to delete this chat.',
} satisfies ServiceError;
}
// Only the creator of a chat can delete it.
if (chat.createdById !== userId) {
return notFound();
}
await prisma.chat.delete({
where: {
id: chatId,
orgId: org.id,
},
});
return {
@ -229,45 +280,6 @@ User question: ${message}`;
}
})
)
export const deleteChat = async ({ chatId }: { chatId: string }) => sew(() =>
withAuthV2(async ({ org, user, prisma }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
if (!chat) {
return notFound();
}
// Public chats cannot be deleted.
if (chat.visibility === ChatVisibility.PUBLIC) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.UNEXPECTED_ERROR,
message: 'You are not allowed to delete this chat.',
} satisfies ServiceError;
}
// Only the creator of a chat can delete it.
if (chat.createdById !== user.id) {
return notFound();
}
await prisma.chat.delete({
where: {
id: chatId,
orgId: org.id,
},
});
return {
success: true,
}
})
);
export const submitFeedback = async ({
@ -278,55 +290,56 @@ export const submitFeedback = async ({
chatId: string,
messageId: string,
feedbackType: 'like' | 'dislike'
}) => sew(() =>
withOptionalAuthV2(async ({ org, user, prisma }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
}, domain: string) => sew(() =>
withAuth((userId) =>
withOrgMembership(userId, domain, async ({ org }) => {
const chat = await prisma.chat.findUnique({
where: {
id: chatId,
orgId: org.id,
},
});
if (!chat) {
return notFound();
}
// When a chat is private, only the creator can submit feedback.
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== user?.id) {
return notFound();
}
const messages = chat.messages as unknown as SBChatMessage[];
const updatedMessages = messages.map(message => {
if (message.id === messageId && message.role === 'assistant') {
return {
...message,
metadata: {
...message.metadata,
feedback: [
...(message.metadata?.feedback ?? []),
{
type: feedbackType,
timestamp: new Date().toISOString(),
userId: user?.id,
}
]
}
} satisfies SBChatMessage;
if (!chat) {
return notFound();
}
return message;
});
await prisma.chat.update({
where: { id: chatId },
data: {
messages: updatedMessages as unknown as Prisma.InputJsonValue,
},
});
// When a chat is private, only the creator can submit feedback.
if (chat.visibility === ChatVisibility.PRIVATE && chat.createdById !== userId) {
return notFound();
}
return { success: true };
})
)
const messages = chat.messages as unknown as SBChatMessage[];
const updatedMessages = messages.map(message => {
if (message.id === messageId && message.role === 'assistant') {
return {
...message,
metadata: {
...message.metadata,
feedback: [
...(message.metadata?.feedback ?? []),
{
type: feedbackType,
timestamp: new Date().toISOString(),
userId: userId,
}
]
}
} satisfies SBChatMessage;
}
return message;
});
await prisma.chat.update({
where: { id: chatId },
data: {
messages: updatedMessages as unknown as Prisma.InputJsonValue,
},
});
return { success: true };
}, /* minRequiredRole = */ OrgRole.GUEST), /* allowSingleTenantUnauthedAccess = */ true)
);
/**
* Returns the subset of information about the configured language models

View file

@ -8,7 +8,7 @@ import { insertMention, slateContentToString } from "@/features/chat/utils";
import { cn, IS_MAC } from "@/lib/utils";
import { computePosition, flip, offset, shift, VirtualElement } from "@floating-ui/react";
import { ArrowUp, Loader2, StopCircleIcon, TriangleAlertIcon } from "lucide-react";
import { Fragment, KeyboardEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Fragment, KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useHotkeys } from "react-hotkeys-hook";
import { Descendant, insertText } from "slate";
import { Editable, ReactEditor, RenderElementProps, RenderLeafProps, useFocused, useSelected, useSlate } from "slate-react";
@ -19,7 +19,6 @@ import { useSuggestionModeAndQuery } from "./useSuggestionModeAndQuery";
import { useSuggestionsData } from "./useSuggestionsData";
import { useToast } from "@/components/hooks/use-toast";
import { SearchContextQuery } from "@/lib/types";
import isEqual from "fast-deep-equal/react";
interface ChatBoxProps {
onSubmit: (children: Descendant[], editor: CustomEditor) => void;
@ -35,7 +34,7 @@ interface ChatBoxProps {
onContextSelectorOpenChanged: (isOpen: boolean) => void;
}
const ChatBoxComponent = ({
export const ChatBox = ({
onSubmit: _onSubmit,
onStop,
preferredSuggestionsBoxPlacement = "bottom-start",
@ -369,8 +368,6 @@ const ChatBoxComponent = ({
)
}
export const ChatBox = memo(ChatBoxComponent, isEqual);
const DefaultElement = (props: RenderElementProps) => {
return <p {...props.attributes}>{props.children}</p>
}

View file

@ -32,22 +32,15 @@ export const useSuggestionsData = ({
const { data: fileSuggestions, isLoading: _isLoadingFileSuggestions } = useQuery({
queryKey: ["fileSuggestions-agentic", suggestionQuery, domain, selectedRepos],
queryFn: () => {
const query = [];
if (suggestionQuery.length > 0) {
query.push(`file:${suggestionQuery}`);
} else {
query.push('file:.*');
}
let query = `file:${suggestionQuery}`;
if (selectedRepos.length > 0) {
query.push(`reposet:${selectedRepos.join(',')}`);
query += ` reposet:${selectedRepos.join(',')}`;
}
return unwrapServiceError(search({
query: query.join(' '),
query,
matches: 10,
contextLines: 1,
source: 'chat-file-suggestions'
}))
},
select: (data): FileSuggestion[] => {

View file

@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import { TableOfContentsIcon, ThumbsDown, ThumbsUp } from "lucide-react";
import { Separator } from "@/components/ui/separator";
import { MarkdownRenderer } from "./markdownRenderer";
import { forwardRef, memo, useCallback, useImperativeHandle, useRef, useState } from "react";
import { forwardRef, useCallback, useImperativeHandle, useRef, useState } from "react";
import { Toggle } from "@/components/ui/toggle";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { CopyIconButton } from "@/app/[domain]/components/copyIconButton";
@ -14,10 +14,10 @@ import { useToast } from "@/components/hooks/use-toast";
import { convertLLMOutputToPortableMarkdown } from "../../utils";
import { submitFeedback } from "../../actions";
import { isServiceError } from "@/lib/utils";
import { useDomain } from "@/hooks/useDomain";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { LangfuseWeb } from "langfuse";
import { env } from "@sourcebot/shared/client";
import isEqual from "fast-deep-equal/react";
interface AnswerCardProps {
answerText: string;
@ -31,7 +31,7 @@ const langfuseWeb = (env.NEXT_PUBLIC_SOURCEBOT_CLOUD_ENVIRONMENT !== undefined &
baseUrl: env.NEXT_PUBLIC_LANGFUSE_BASE_URL,
}) : null;
const AnswerCardComponent = forwardRef<HTMLDivElement, AnswerCardProps>(({
export const AnswerCard = forwardRef<HTMLDivElement, AnswerCardProps>(({
answerText,
messageId,
chatId,
@ -41,6 +41,7 @@ const AnswerCardComponent = forwardRef<HTMLDivElement, AnswerCardProps>(({
const { tocItems, activeId } = useExtractTOCItems({ target: markdownRendererRef.current });
const [isTOCButtonToggled, setIsTOCButtonToggled] = useState(false);
const { toast } = useToast();
const domain = useDomain();
const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);
const [feedback, setFeedback] = useState<'like' | 'dislike' | undefined>(undefined);
const captureEvent = useCaptureEvent();
@ -66,7 +67,7 @@ const AnswerCardComponent = forwardRef<HTMLDivElement, AnswerCardProps>(({
chatId,
messageId,
feedbackType
});
}, domain);
if (isServiceError(response)) {
toast({
@ -92,7 +93,7 @@ const AnswerCardComponent = forwardRef<HTMLDivElement, AnswerCardProps>(({
}
setIsSubmittingFeedback(false);
}, [chatId, messageId, toast, captureEvent, traceId]);
}, [chatId, messageId, domain, toast, captureEvent, traceId]);
return (
<div className="flex flex-row w-full relative scroll-mt-16">
@ -177,6 +178,4 @@ const AnswerCardComponent = forwardRef<HTMLDivElement, AnswerCardProps>(({
)
})
AnswerCardComponent.displayName = 'AnswerCard';
export const AnswerCard = memo(AnswerCardComponent, isEqual);
AnswerCard.displayName = 'AnswerCard';

View file

@ -7,6 +7,7 @@ import { Separator } from '@/components/ui/separator';
import { CustomSlateEditor } from '@/features/chat/customSlateEditor';
import { AdditionalChatRequestParams, CustomEditor, LanguageModelInfo, SBChatMessage, SearchScope, Source } from '@/features/chat/types';
import { createUIMessage, getAllMentionElements, resetEditor, slateContentToString } from '@/features/chat/utils';
import { useDomain } from '@/hooks/useDomain';
import { useChat } from '@ai-sdk/react';
import { CreateUIMessage, DefaultChatTransport } from 'ai';
import { ArrowDownIcon } from 'lucide-react';
@ -53,6 +54,7 @@ export const ChatThread = ({
onSelectedSearchScopesChange,
isChatReadonly,
}: ChatThreadProps) => {
const domain = useDomain();
const [isErrorBannerVisible, setIsErrorBannerVisible] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const latestMessagePairRef = useRef<HTMLDivElement>(null);
@ -87,6 +89,9 @@ export const ChatThread = ({
messages: initialMessages,
transport: new DefaultChatTransport({
api: '/api/chat',
headers: {
"X-Org-Domain": domain,
}
}),
onData: (dataPart) => {
// Keeps sources added by the assistant in sync.
@ -129,6 +134,7 @@ export const ChatThread = ({
languageModelId: selectedLanguageModel.model,
message: message.parts[0].text,
},
domain
).then((response) => {
if (isServiceError(response)) {
toast({
@ -147,6 +153,7 @@ export const ChatThread = ({
messages.length,
toast,
chatId,
domain,
router,
]);
@ -217,7 +224,7 @@ export const ChatThread = ({
'',
window.location.href
);
}, 500);
}, 300);
};
scrollElement.addEventListener('scroll', handleScroll, { passive: true });
@ -236,17 +243,11 @@ export const ChatThread = ({
return;
}
// @hack: without this setTimeout, the scroll position would not be restored
// at the correct position (it was slightly too high). The theory is that the
// content hasn't fully rendered yet, so restoring the scroll position too
// early results in weirdness. Waiting 10ms seems to fix the issue.
setTimeout(() => {
const { scrollOffset } = (history.state ?? {}) as ChatHistoryState;
scrollElement.scrollTo({
top: scrollOffset ?? 0,
behavior: 'instant',
});
}, 10);
const { scrollOffset } = (history.state ?? {}) as ChatHistoryState;
scrollElement.scrollTo({
top: scrollOffset ?? 0,
behavior: 'instant',
});
}, []);
// When messages are being streamed, scroll to the latest message
@ -312,11 +313,9 @@ export const ChatThread = ({
{messagePairs.map(([userMessage, assistantMessage], index) => {
const isLastPair = index === messagePairs.length - 1;
const isStreaming = isLastPair && (status === "streaming" || status === "submitted");
// Use a stable key based on user message ID
const key = userMessage.id;
return (
<Fragment key={key}>
<Fragment key={index}>
<ChatThreadListItem
index={index}
chatId={chatId}

View file

@ -4,17 +4,16 @@ import { AnimatedResizableHandle } from '@/components/ui/animatedResizableHandle
import { ResizablePanel, ResizablePanelGroup } from '@/components/ui/resizable';
import { Skeleton } from '@/components/ui/skeleton';
import { CheckCircle, Loader2 } from 'lucide-react';
import { CSSProperties, forwardRef, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CSSProperties, forwardRef, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import scrollIntoView from 'scroll-into-view-if-needed';
import { Reference, referenceSchema, SBChatMessage, Source } from "../../types";
import { useExtractReferences } from '../../useExtractReferences';
import { getAnswerPartFromAssistantMessage, groupMessageIntoSteps, repairReferences, tryResolveFileReference } from '../../utils';
import { getAnswerPartFromAssistantMessage, groupMessageIntoSteps, repairReferences } from '../../utils';
import { AnswerCard } from './answerCard';
import { DetailsCard } from './detailsCard';
import { MarkdownRenderer, REFERENCE_PAYLOAD_ATTRIBUTE } from './markdownRenderer';
import { ReferencedSourcesListView } from './referencedSourcesListView';
import { uiVisiblePartTypes } from '../../constants';
import isEqual from "fast-deep-equal/react";
interface ChatThreadListItemProps {
userMessage: SBChatMessage;
@ -25,7 +24,7 @@ interface ChatThreadListItemProps {
index: number;
}
const ChatThreadListItemComponent = forwardRef<HTMLDivElement, ChatThreadListItemProps>(({
export const ChatThreadListItem = forwardRef<HTMLDivElement, ChatThreadListItemProps>(({
userMessage,
assistantMessage: _assistantMessage,
isStreaming,
@ -81,6 +80,7 @@ const ChatThreadListItemComponent = forwardRef<HTMLDivElement, ChatThreadListIte
return getAnswerPartFromAssistantMessage(assistantMessage, isStreaming);
}, [assistantMessage, isStreaming]);
const references = useExtractReferences(answerPart);
// Groups parts into steps that are associated with thinking steps that
// should be visible to the user. By "steps", we mean parts that originated
@ -279,26 +279,6 @@ const ChatThreadListItemComponent = forwardRef<HTMLDivElement, ChatThreadListIte
};
}, [hoveredReference]);
const references = useExtractReferences(answerPart);
// Extract the file sources that are referenced by the answer part.
const referencedFileSources = useMemo(() => {
const fileSources = sources.filter((source) => source.type === 'file');
return references
.filter((reference) => reference.type === 'file')
.map((reference) => tryResolveFileReference(reference, fileSources))
.filter((file) => file !== undefined)
// de-duplicate files
.filter((file, index, self) =>
index === self.findIndex((t) =>
t?.path === file?.path
&& t?.repo === file?.repo
&& t?.revision === file?.revision
)
);
}, [references, sources]);
return (
<div
@ -384,11 +364,11 @@ const ChatThreadListItemComponent = forwardRef<HTMLDivElement, ChatThreadListIte
<div
className="sticky top-0"
>
{referencedFileSources.length > 0 ? (
{references.length > 0 ? (
<ReferencedSourcesListView
index={index}
references={references}
sources={referencedFileSources}
sources={sources}
hoveredReference={hoveredReference}
selectedReference={selectedReference}
onSelectedReferenceChanged={setSelectedReference}
@ -413,34 +393,7 @@ const ChatThreadListItemComponent = forwardRef<HTMLDivElement, ChatThreadListIte
)
});
ChatThreadListItemComponent.displayName = 'ChatThreadListItem';
// Custom comparison function that handles the known issue where useChat mutates
// message objects in place during streaming, causing fast-deep-equal to return
// true even when content changes (because it checks reference equality first).
// See: https://github.com/vercel/ai/issues/6466
const arePropsEqual = (
prevProps: ChatThreadListItemProps,
nextProps: ChatThreadListItemProps
): boolean => {
// Always re-render if streaming status changes
if (prevProps.isStreaming !== nextProps.isStreaming) {
return false;
}
// If currently streaming, always allow re-render
// This bypasses the fast-deep-equal reference check issue when useChat
// mutates message objects in place during token streaming
if (nextProps.isStreaming) {
return false;
}
// For non-streaming messages, use deep equality
// At this point, useChat should have finished and created final objects
return isEqual(prevProps, nextProps);
};
export const ChatThreadListItem = memo(ChatThreadListItemComponent, arePropsEqual);
ChatThreadListItem.displayName = 'ChatThreadListItem';
// Finds the nearest reference element to the viewport center.
const getNearestReferenceElement = (referenceElements: Element[]) => {

View file

@ -7,7 +7,6 @@ import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
import { Brain, ChevronDown, ChevronRight, Clock, InfoIcon, Loader2, List, ScanSearchIcon, Zap } from 'lucide-react';
import { memo } from 'react';
import { MarkdownRenderer } from './markdownRenderer';
import { FindSymbolDefinitionsToolComponent } from './tools/findSymbolDefinitionsToolComponent';
import { FindSymbolReferencesToolComponent } from './tools/findSymbolReferencesToolComponent';
@ -17,7 +16,6 @@ import { SearchReposToolComponent } from './tools/searchReposToolComponent';
import { ListAllReposToolComponent } from './tools/listAllReposToolComponent';
import { SBChatMessageMetadata, SBChatMessagePart } from '../../types';
import { SearchScopeIcon } from '../searchScopeIcon';
import isEqual from "fast-deep-equal/react";
interface DetailsCardProps {
@ -29,7 +27,7 @@ interface DetailsCardProps {
metadata?: SBChatMessageMetadata;
}
const DetailsCardComponent = ({
export const DetailsCard = ({
isExpanded,
onExpandedChanged,
isThinking,
@ -37,6 +35,7 @@ const DetailsCardComponent = ({
metadata,
thinkingSteps,
}: DetailsCardProps) => {
return (
<Card className="mb-4">
<Collapsible open={isExpanded} onOpenChange={onExpandedChanged}>
@ -210,6 +209,4 @@ const DetailsCardComponent = ({
</Collapsible>
</Card>
)
}
export const DetailsCard = memo(DetailsCardComponent, isEqual);
}

View file

@ -1,6 +1,7 @@
'use client';
import { CodeSnippet } from '@/app/components/codeSnippet';
import { useDomain } from '@/hooks/useDomain';
import { SearchQueryParams } from '@/lib/types';
import { cn, createPathWithQueryParams } from '@/lib/utils';
import type { Element, Root } from "hast";
@ -9,7 +10,7 @@ import { CopyIcon, SearchIcon } from 'lucide-react';
import type { Heading, Nodes } from "mdast";
import { findAndReplace } from 'mdast-util-find-and-replace';
import { useRouter } from 'next/navigation';
import React, { useCallback, useMemo, forwardRef, memo } from 'react';
import React, { useCallback, useMemo, forwardRef } from 'react';
import Markdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
@ -19,8 +20,6 @@ import { visit } from 'unist-util-visit';
import { CodeBlock } from './codeBlock';
import { FILE_REFERENCE_REGEX } from '@/features/chat/constants';
import { createFileReference } from '@/features/chat/utils';
import { SINGLE_TENANT_ORG_DOMAIN } from '@/lib/constants';
import isEqual from "fast-deep-equal/react";
export const REFERENCE_PAYLOAD_ATTRIBUTE = 'data-reference-payload';
@ -103,7 +102,8 @@ interface MarkdownRendererProps {
className?: string;
}
const MarkdownRendererComponent = forwardRef<HTMLDivElement, MarkdownRendererProps>(({ content, className }, ref) => {
export const MarkdownRenderer = forwardRef<HTMLDivElement, MarkdownRendererProps>(({ content, className }, ref) => {
const domain = useDomain();
const router = useRouter();
const remarkPlugins = useMemo((): PluggableList => {
@ -176,7 +176,7 @@ const MarkdownRendererComponent = forwardRef<HTMLDivElement, MarkdownRendererPro
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
const url = createPathWithQueryParams(`/${SINGLE_TENANT_ORG_DOMAIN}/search`, [SearchQueryParams.query, `"${text}"`])
const url = createPathWithQueryParams(`/${domain}/search`, [SearchQueryParams.query, `"${text}"`])
router.push(url);
}}
title="Search for snippet"
@ -199,7 +199,7 @@ const MarkdownRendererComponent = forwardRef<HTMLDivElement, MarkdownRendererPro
</span>
)
}, [router]);
}, [domain, router]);
return (
<div
@ -220,6 +220,4 @@ const MarkdownRendererComponent = forwardRef<HTMLDivElement, MarkdownRendererPro
);
});
MarkdownRendererComponent.displayName = 'MarkdownRenderer';
export const MarkdownRenderer = memo(MarkdownRendererComponent, isEqual);
MarkdownRenderer.displayName = 'MarkdownRenderer';

View file

@ -1,8 +1,10 @@
'use client';
import { useBrowseNavigation } from "@/app/[domain]/browse/hooks/useBrowseNavigation";
import { PathHeader } from "@/app/[domain]/components/pathHeader";
import { SymbolHoverPopup } from '@/ee/features/codeNav/components/symbolHoverPopup';
import { symbolHoverTargetsExtension } from "@/ee/features/codeNav/components/symbolHoverPopup/symbolHoverTargetsExtension";
import { SymbolDefinition } from '@/ee/features/codeNav/components/symbolHoverPopup/useHoveredOverSymbolInfo';
import { useHasEntitlement } from "@/features/entitlements/useHasEntitlement";
import { useCodeMirrorLanguageExtension } from "@/hooks/useCodeMirrorLanguageExtension";
import { useCodeMirrorTheme } from "@/hooks/useCodeMirrorTheme";
@ -10,13 +12,15 @@ import { useKeymapExtension } from "@/hooks/useKeymapExtension";
import { cn } from "@/lib/utils";
import { Range } from "@codemirror/state";
import { Decoration, DecorationSet, EditorView } from '@codemirror/view';
import { CodeHostType } from "@sourcebot/db";
import CodeMirror, { ReactCodeMirrorRef, StateField } from '@uiw/react-codemirror';
import isEqual from "fast-deep-equal/react";
import { ChevronDown, ChevronRight } from "lucide-react";
import { forwardRef, memo, Ref, useCallback, useImperativeHandle, useMemo, useState } from "react";
import { forwardRef, Ref, useCallback, useImperativeHandle, useMemo, useState } from "react";
import { FileReference } from "../../types";
import { createCodeFoldingExtension } from "./codeFoldingExtension";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { createAuditAction } from "@/ee/features/audit/actions";
import { useDomain } from "@/hooks/useDomain";
import { CodeHostType } from "@sourcebot/db";
const lineDecoration = Decoration.line({
attributes: { class: "cm-range-border-radius chat-lineHighlight" },
@ -70,6 +74,8 @@ const ReferencedFileSourceListItem = ({
}: ReferencedFileSourceListItemProps, forwardedRef: Ref<ReactCodeMirrorRef>) => {
const theme = useCodeMirrorTheme();
const [editorRef, setEditorRef] = useState<ReactCodeMirrorRef | null>(null);
const captureEvent = useCaptureEvent();
const domain = useDomain();
useImperativeHandle(
forwardedRef,
@ -79,6 +85,7 @@ const ReferencedFileSourceListItem = ({
const hasCodeNavEntitlement = useHasEntitlement("code-nav");
const languageExtension = useCodeMirrorLanguageExtension(language, editorRef?.view);
const { navigateToPath } = useBrowseNavigation();
const getReferenceAtPos = useCallback((x: number, y: number, view: EditorView): FileReference | undefined => {
const pos = view.posAtCoords({ x, y });
@ -211,6 +218,83 @@ const ReferencedFileSourceListItem = ({
codeFoldingExtension,
]);
const onGotoDefinition = useCallback((symbolName: string, symbolDefinitions: SymbolDefinition[]) => {
if (symbolDefinitions.length === 0) {
return;
}
captureEvent('wa_goto_definition_pressed', {
source: 'chat',
});
createAuditAction({
action: "user.performed_goto_definition",
metadata: {
message: symbolName,
},
}, domain);
if (symbolDefinitions.length === 1) {
const symbolDefinition = symbolDefinitions[0];
const { fileName, repoName } = symbolDefinition;
navigateToPath({
repoName,
revisionName: revision,
path: fileName,
pathType: 'blob',
highlightRange: symbolDefinition.range,
})
} else {
navigateToPath({
repoName,
revisionName: revision,
path: fileName,
pathType: 'blob',
setBrowseState: {
selectedSymbolInfo: {
symbolName,
repoName,
revisionName: revision,
language: language,
},
activeExploreMenuTab: "definitions",
isBottomPanelCollapsed: false,
}
});
}
}, [captureEvent, domain, navigateToPath, revision, repoName, fileName, language]);
const onFindReferences = useCallback((symbolName: string) => {
captureEvent('wa_find_references_pressed', {
source: 'chat',
});
createAuditAction({
action: "user.performed_find_references",
metadata: {
message: symbolName,
},
}, domain);
navigateToPath({
repoName,
revisionName: revision,
path: fileName,
pathType: 'blob',
setBrowseState: {
selectedSymbolInfo: {
symbolName,
repoName,
revisionName: revision,
language: language,
},
activeExploreMenuTab: "references",
isBottomPanelCollapsed: false,
}
})
}, [captureEvent, domain, fileName, language, navigateToPath, repoName, revision]);
const ExpandCollapseIcon = useMemo(() => {
return isExpanded ? ChevronDown : ChevronRight;
}, [isExpanded]);
@ -258,12 +342,11 @@ const ReferencedFileSourceListItem = ({
>
{editorRef && hasCodeNavEntitlement && (
<SymbolHoverPopup
source="chat"
editorRef={editorRef}
revisionName={revision}
language={language}
repoName={repoName}
fileName={fileName}
onFindReferences={onFindReferences}
onGotoDefinition={onGotoDefinition}
/>
)}
</CodeMirror>
@ -272,6 +355,6 @@ const ReferencedFileSourceListItem = ({
)
}
export default memo(forwardRef(ReferencedFileSourceListItem), isEqual) as (
export default forwardRef(ReferencedFileSourceListItem) as (
props: ReferencedFileSourceListItemProps & { ref?: Ref<ReactCodeMirrorRef> },
) => ReturnType<typeof ReferencedFileSourceListItem>;

View file

@ -4,19 +4,18 @@ import { getFileSource } from "@/app/api/(client)/client";
import { VscodeFileIcon } from "@/app/components/vscodeFileIcon";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Skeleton } from "@/components/ui/skeleton";
import { useDomain } from "@/hooks/useDomain";
import { isServiceError, unwrapServiceError } from "@/lib/utils";
import { useQueries } from "@tanstack/react-query";
import { ReactCodeMirrorRef } from '@uiw/react-codemirror';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import scrollIntoView from 'scroll-into-view-if-needed';
import { FileReference, FileSource, Reference } from "../../types";
import { tryResolveFileReference } from '../../utils';
import { FileReference, FileSource, Reference, Source } from "../../types";
import ReferencedFileSourceListItem from "./referencedFileSourceListItem";
import isEqual from 'fast-deep-equal/react';
interface ReferencedSourcesListViewProps {
references: FileReference[];
sources: FileSource[];
sources: Source[];
index: number;
hoveredReference?: Reference;
onHoveredReferenceChanged: (reference?: Reference) => void;
@ -25,7 +24,14 @@ interface ReferencedSourcesListViewProps {
style: React.CSSProperties;
}
const ReferencedSourcesListViewComponent = ({
const resolveFileReference = (reference: FileReference, sources: FileSource[]): FileSource | undefined => {
return sources.find(
(source) => source.repo.endsWith(reference.repo) &&
source.path.endsWith(reference.path)
);
}
export const ReferencedSourcesListView = ({
references,
sources,
index,
@ -37,6 +43,7 @@ const ReferencedSourcesListViewComponent = ({
}: ReferencedSourcesListViewProps) => {
const scrollAreaRef = useRef<HTMLDivElement>(null);
const editorRefsMap = useRef<Map<string, ReactCodeMirrorRef>>(new Map());
const domain = useDomain();
const [collapsedFileIds, setCollapsedFileIds] = useState<string[]>([]);
const getFileId = useCallback((fileSource: FileSource) => {
@ -54,27 +61,44 @@ const ReferencedSourcesListViewComponent = ({
}
}, []);
const referencedFileSources = useMemo((): FileSource[] => {
const fileSources = sources.filter((source) => source.type === 'file');
return references
.filter((reference) => reference.type === 'file')
.map((reference) => resolveFileReference(reference, fileSources))
.filter((file) => file !== undefined)
// de-duplicate files
.filter((file, index, self) =>
index === self.findIndex((t) =>
t?.path === file?.path
&& t?.repo === file?.repo
&& t?.revision === file?.revision
)
);
}, [references, sources]);
// Memoize the computation of references grouped by file source
const referencesGroupedByFile = useMemo(() => {
const groupedReferences = new Map<string, FileReference[]>();
for (const fileSource of sources) {
for (const fileSource of referencedFileSources) {
const fileKey = getFileId(fileSource);
const referencesInFile = references.filter((reference) => {
if (reference.type !== 'file') {
return false;
}
return tryResolveFileReference(reference, [fileSource]) !== undefined;
return resolveFileReference(reference, [fileSource]) !== undefined;
});
groupedReferences.set(fileKey, referencesInFile);
}
return groupedReferences;
}, [references, sources, getFileId]);
}, [references, referencedFileSources, getFileId]);
const fileSourceQueries = useQueries({
queries: sources.map((file) => ({
queryKey: ['fileSource', file.path, file.repo, file.revision],
queries: referencedFileSources.map((file) => ({
queryKey: ['fileSource', file.path, file.repo, file.revision, domain],
queryFn: () => unwrapServiceError(getFileSource({
fileName: file.path,
repository: file.repo,
@ -90,7 +114,7 @@ const ReferencedSourcesListViewComponent = ({
return;
}
const fileSource = tryResolveFileReference(selectedReference, sources);
const fileSource = resolveFileReference(selectedReference, referencedFileSources);
if (!fileSource) {
return;
}
@ -157,28 +181,9 @@ const ReferencedSourcesListViewComponent = ({
behavior: 'smooth',
});
}
}, [getFileId, sources, selectedReference]);
}, [getFileId, referencedFileSources, selectedReference]);
const onExpandedChanged = useCallback((fileId: string, isExpanded: boolean) => {
if (isExpanded) {
setCollapsedFileIds(collapsedFileIds => collapsedFileIds.filter((id) => id !== fileId));
} else {
setCollapsedFileIds(collapsedFileIds => [...collapsedFileIds, fileId]);
}
if (!isExpanded) {
const fileSourceStart = document.getElementById(`${fileId}-start`);
if (fileSourceStart) {
scrollIntoView(fileSourceStart, {
scrollMode: 'if-needed',
block: 'start',
behavior: 'instant',
});
}
}
}, []);
if (sources.length === 0) {
if (referencedFileSources.length === 0) {
return (
<div className="p-4 text-center text-muted-foreground text-sm">
No file references found
@ -193,7 +198,7 @@ const ReferencedSourcesListViewComponent = ({
>
<div className="space-y-4 pr-2">
{fileSourceQueries.map((query, index) => {
const fileSource = sources[index];
const fileSource = referencedFileSources[index];
const fileName = fileSource.path.split('/').pop() ?? fileSource.path;
if (query.isLoading) {
@ -248,7 +253,30 @@ const ReferencedSourcesListViewComponent = ({
selectedReference={selectedReference}
hoveredReference={hoveredReference}
isExpanded={!collapsedFileIds.includes(fileId)}
onExpandedChanged={(isExpanded) => onExpandedChanged(fileId, isExpanded)}
onExpandedChanged={(isExpanded) => {
if (isExpanded) {
setCollapsedFileIds(collapsedFileIds.filter((id) => id !== fileId));
} else {
setCollapsedFileIds([...collapsedFileIds, fileId]);
}
// When collapsing a file when you are deep in a scroll, it's a better
// experience to have the scroll automatically restored to the top of the file
// s.t., header is still sticky to the top of the scroll area.
if (!isExpanded) {
const fileSourceStart = document.getElementById(`${fileId}-start`);
if (!fileSourceStart) {
return;
}
scrollIntoView(fileSourceStart, {
scrollMode: 'if-needed',
block: 'start',
behavior: 'instant',
});
}
}
}
/>
);
})}
@ -256,6 +284,3 @@ const ReferencedSourcesListViewComponent = ({
</ScrollArea>
);
}
// Memoize to prevent unnecessary re-renders
export const ReferencedSourcesListView = memo(ReferencedSourcesListViewComponent, isEqual);

View file

@ -1,6 +1,7 @@
'use client';
import { SearchCodeToolUIPart } from "@/features/chat/tools";
import { useDomain } from "@/hooks/useDomain";
import { createPathWithQueryParams, isServiceError } from "@/lib/utils";
import { useMemo, useState } from "react";
import { FileListItem, ToolHeader, TreeList } from "./shared";
@ -11,10 +12,10 @@ import Link from "next/link";
import { SearchQueryParams } from "@/lib/types";
import { PlayIcon } from "@radix-ui/react-icons";
import { buildSearchQuery } from "@/features/chat/utils";
import { SINGLE_TENANT_ORG_DOMAIN } from "@/lib/constants";
export const SearchCodeToolComponent = ({ part }: { part: SearchCodeToolUIPart }) => {
const [isExpanded, setIsExpanded] = useState(false);
const domain = useDomain();
const displayQuery = useMemo(() => {
if (part.state !== 'input-available' && part.state !== 'output-available') {
@ -77,7 +78,7 @@ export const SearchCodeToolComponent = ({ part }: { part: SearchCodeToolUIPart }
</TreeList>
)}
<Link
href={createPathWithQueryParams(`/${SINGLE_TENANT_ORG_DOMAIN}/search`,
href={createPathWithQueryParams(`/${domain}/search`,
[SearchQueryParams.query, part.output.query],
)}
className='flex flex-row items-center gap-2 text-sm text-muted-foreground mt-2 ml-auto w-fit hover:text-foreground'

View file

@ -2,12 +2,12 @@
import { VscodeFileIcon } from '@/app/components/vscodeFileIcon';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useDomain } from '@/hooks/useDomain';
import { cn } from '@/lib/utils';
import { ChevronDown, ChevronRight, Loader2 } from 'lucide-react';
import Link from 'next/link';
import React from 'react';
import { getBrowsePath } from "@/app/[domain]/browse/hooks/utils";
import { SINGLE_TENANT_ORG_DOMAIN } from "@/lib/constants";
export const FileListItem = ({
@ -17,6 +17,8 @@ export const FileListItem = ({
path: string,
repoName: string,
}) => {
const domain = useDomain();
return (
<div key={path} className="flex flex-row items-center overflow-hidden hover:bg-accent hover:text-accent-foreground rounded-sm cursor-pointer p-0.5">
<VscodeFileIcon fileName={path} className="mr-1 flex-shrink-0" />
@ -26,7 +28,7 @@ export const FileListItem = ({
repoName,
revisionName: 'HEAD',
path,
domain: SINGLE_TENANT_ORG_DOMAIN,
domain,
pathType: 'blob',
})}
>

View file

@ -26,9 +26,8 @@ export const findSymbolReferencesTool = tool({
inputSchema: z.object({
symbol: z.string().describe("The symbol to find references to"),
language: z.string().describe("The programming language of the symbol"),
repository: z.string().describe("The repository to scope the search to").optional(),
}),
execute: async ({ symbol, language, repository }) => {
execute: async ({ symbol, language }) => {
// @todo: make revision configurable.
const revision = "HEAD";
@ -36,7 +35,6 @@ export const findSymbolReferencesTool = tool({
symbolName: symbol,
language,
revisionName: "HEAD",
repoName: repository,
});
if (isServiceError(response)) {
@ -65,9 +63,8 @@ export const findSymbolDefinitionsTool = tool({
inputSchema: z.object({
symbol: z.string().describe("The symbol to find definitions of"),
language: z.string().describe("The programming language of the symbol"),
repository: z.string().describe("The repository to scope the search to").optional(),
}),
execute: async ({ symbol, language, repository }) => {
execute: async ({ symbol, language }) => {
// @todo: make revision configurable.
const revision = "HEAD";
@ -75,7 +72,6 @@ export const findSymbolDefinitionsTool = tool({
symbolName: symbol,
language,
revisionName: revision,
repoName: repository,
});
if (isServiceError(response)) {

View file

@ -70,7 +70,7 @@ export const sbChatMessageMetadataSchema = z.object({
feedback: z.array(z.object({
type: z.enum(['like', 'dislike']),
timestamp: z.string(), // ISO date string
userId: z.string().optional(),
userId: z.string(),
})).optional(),
selectedSearchScopes: z.array(searchScopeSchema).optional(),
traceId: z.string().optional(),

View file

@ -4,6 +4,7 @@ import { useCallback, useState } from "react";
import { Descendant } from "slate";
import { createUIMessage, getAllMentionElements } from "./utils";
import { slateContentToString } from "./utils";
import { useDomain } from "@/hooks/useDomain";
import { useToast } from "@/components/hooks/use-toast";
import { useRouter } from "next/navigation";
import { createChat } from "./actions";
@ -12,9 +13,9 @@ import { createPathWithQueryParams } from "@/lib/utils";
import { SearchScope, SET_CHAT_STATE_SESSION_STORAGE_KEY, SetChatStatePayload } from "./types";
import { useSessionStorage } from "usehooks-ts";
import useCaptureEvent from "@/hooks/useCaptureEvent";
import { SINGLE_TENANT_ORG_DOMAIN } from "@/lib/constants";
export const useCreateNewChatThread = () => {
const domain = useDomain();
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const router = useRouter();
@ -30,7 +31,7 @@ export const useCreateNewChatThread = () => {
const inputMessage = createUIMessage(text, mentions.map((mention) => mention.data), selectedSearchScopes);
setIsLoading(true);
const response = await createChat();
const response = await createChat(domain);
if (isServiceError(response)) {
toast({
description: `❌ Failed to create chat. Reason: ${response.message}`
@ -46,11 +47,11 @@ export const useCreateNewChatThread = () => {
selectedSearchScopes,
});
const url = createPathWithQueryParams(`/${SINGLE_TENANT_ORG_DOMAIN}/chat/${response.id}`);
const url = createPathWithQueryParams(`/${domain}/chat/${response.id}`);
router.push(url);
router.refresh();
}, [router, toast, setChatState, captureEvent]);
}, [domain, router, toast, setChatState, captureEvent]);
return {
createNewChatThread,

View file

@ -374,13 +374,3 @@ export const buildSearchQuery = (options: {
export const getLanguageModelKey = (model: LanguageModelInfo) => {
return `${model.provider}-${model.model}-${model.displayName}`;
}
/**
* Given a file reference and a list of file sources, attempts to resolve the file source that the reference points to.
*/
export const tryResolveFileReference = (reference: FileReference, sources: FileSource[]): FileSource | undefined => {
return sources.find(
(source) => source.repo.endsWith(reference.repo) &&
source.path.endsWith(reference.path)
);
}

View file

@ -8,7 +8,6 @@ import { withOptionalAuthV2 } from "@/withAuthV2";
import { SearchResponse } from "../search/types";
import { FindRelatedSymbolsRequest, FindRelatedSymbolsResponse } from "./types";
import { QueryIR } from '../search/ir';
import escapeStringRegexp from "escape-string-regexp";
// The maximum number of matches to return from the search API.
const MAX_REFERENCE_COUNT = 1000;
@ -19,7 +18,6 @@ export const findSearchBasedSymbolReferences = async (props: FindRelatedSymbolsR
symbolName,
language,
revisionName = "HEAD",
repoName,
} = props;
const languageFilter = getExpandedLanguageFilter(language);
@ -42,11 +40,6 @@ export const findSearchBasedSymbolReferences = async (props: FindRelatedSymbolsR
}
},
languageFilter,
...(repoName ? [{
repo: {
regexp: `^${escapeStringRegexp(repoName)}$`,
}
}]: [])
]
}
}
@ -74,7 +67,6 @@ export const findSearchBasedSymbolDefinitions = async (props: FindRelatedSymbols
symbolName,
language,
revisionName = "HEAD",
repoName
} = props;
const languageFilter = getExpandedLanguageFilter(language);
@ -101,11 +93,6 @@ export const findSearchBasedSymbolDefinitions = async (props: FindRelatedSymbols
}
},
languageFilter,
...(repoName ? [{
repo: {
regexp: `^${escapeStringRegexp(repoName)}$`,
}
}]: [])
]
}
}

View file

@ -4,16 +4,7 @@ import { rangeSchema, repositoryInfoSchema } from "../search/types";
export const findRelatedSymbolsRequestSchema = z.object({
symbolName: z.string(),
language: z.string(),
/**
* Optional revision name to scope search to.
* If not provided, the search will be scoped to HEAD.
*/
revisionName: z.string().optional(),
/**
* Optional repository name to scope search to.
* If not provided, the search will be across all repositories.
*/
repoName: z.string().optional(),
});
export type FindRelatedSymbolsRequest = z.infer<typeof findRelatedSymbolsRequestSchema>;

View file

@ -6,8 +6,6 @@ import { search } from "./searchApi";
import { sew } from "@/actions";
import { withOptionalAuthV2 } from "@/withAuthV2";
import { QueryIR } from './ir';
import escapeStringRegexp from "escape-string-regexp";
// @todo (bkellam) #574 : We should really be using `git show <hash>:<path>` to fetch file contents here.
// This will allow us to support permalinks to files at a specific revision that may not be indexed
// by zoekt. We should also refactor this out of the /search folder.
@ -19,16 +17,16 @@ export const getFileSource = async ({ fileName, repository, branch }: FileSource
children: [
{
repo: {
regexp: `^${escapeStringRegexp(repository)}$`,
regexp: `^${repository}$`,
},
},
{
substring: {
pattern: fileName,
regexp: {
regexp: fileName,
case_sensitive: true,
file_name: true,
content: false,
}
content: false
},
},
...(branch ? [{
branch: {

View file

@ -18,7 +18,6 @@ import {
SymExpr,
SyntaxNode,
Term,
QuotedTerm,
Tree,
VisibilityExpr,
} from '@sourcebot/query-language';
@ -176,12 +175,8 @@ const transformTreeToIR = async ({
// PrefixExpr contains specific prefix types
return transformPrefixExpr(node);
case QuotedTerm:
case Term: {
const fullText = input.substring(node.from, node.to);
// If the term is quoted, then we remove the quotes as they are
// not interpreted.
const termText = node.type.id === QuotedTerm ? fullText.replace(/^"|"$/g, '') : fullText;
const termText = input.substring(node.from, node.to).replace(/^"|"$/g, '');
return isRegexEnabled ? {
regexp: {

View file

@ -2,12 +2,13 @@ import { sew } from "@/actions";
import { getRepoPermissionFilterForUser } from "@/prisma";
import { withOptionalAuthV2 } from "@/withAuthV2";
import { PrismaClient, UserWithAccounts } from "@sourcebot/db";
import { env, hasEntitlement } from "@sourcebot/shared";
import { createLogger, env, hasEntitlement } from "@sourcebot/shared";
import { QueryIR } from './ir';
import { parseQuerySyntaxIntoIR } from './parser';
import { SearchOptions } from "./types";
import { createZoektSearchRequest, zoektSearch, zoektStreamSearch } from './zoektSearcher';
const logger = createLogger("searchApi");
type QueryStringSearchRequest = {
queryType: 'string';

View file

@ -94,7 +94,6 @@ export type SearchOptions = z.infer<typeof searchOptionsSchema>;
export const searchRequestSchema = z.object({
query: z.string(), // The zoekt query to execute.
source: z.string().optional(), // The source of the search request.
...searchOptionsSchema.shape,
});
export type SearchRequest = z.infer<typeof searchRequestSchema>;

View file

@ -1,69 +0,0 @@
import { PostHog } from 'posthog-node'
import { env } from '@sourcebot/shared'
import { RequestCookies } from 'next/dist/compiled/@edge-runtime/cookies';
import * as Sentry from "@sentry/nextjs";
import { PosthogEvent, PosthogEventMap } from './posthogEvents';
import { cookies } from 'next/headers';
/**
* @note: This is a subset of the properties stored in the
* ph_phc_<id>_posthog cookie.
*/
export type PostHogCookie = {
distinct_id: string;
}
const isPostHogCookie = (cookie: unknown): cookie is PostHogCookie => {
return typeof cookie === 'object' &&
cookie !== null &&
'distinct_id' in cookie;
}
/**
* Attempts to retrieve the PostHog cookie from the given cookie store, returning
* undefined if the cookie is not found or is invalid.
*/
const getPostHogCookie = (cookieStore: Pick<RequestCookies, 'get'>): PostHogCookie | undefined => {
const phCookieKey = `ph_${env.POSTHOG_PAPIK}_posthog`;
const cookie = cookieStore.get(phCookieKey);
if (!cookie) {
return undefined;
}
const parsedCookie = (() => {
try {
return JSON.parse(cookie.value);
} catch (e) {
Sentry.captureException(e);
return null;
}
})();
if (isPostHogCookie(parsedCookie)) {
return parsedCookie;
}
return undefined;
}
export async function captureEvent<E extends PosthogEvent>(event: E, properties: PosthogEventMap[E]) {
if (env.SOURCEBOT_TELEMETRY_DISABLED === 'true') {
return;
}
const cookieStore = await cookies();
const cookie = getPostHogCookie(cookieStore);
const posthog = new PostHog(env.POSTHOG_PAPIK, {
host: 'https://us.i.posthog.com',
flushAt: 1,
flushInterval: 0
})
posthog.capture({
event,
properties,
distinctId: cookie?.distinct_id ?? '',
});
}

View file

@ -273,6 +273,15 @@ export type PosthogEventMap = {
wa_api_key_created: {},
wa_api_key_creation_fail: {},
//////////////////////////////////////////////////////////////////
wa_goto_definition_pressed: {
source: 'chat' | 'browse' | 'preview',
},
wa_find_references_pressed: {
source: 'chat' | 'browse' | 'preview',
},
//////////////////////////////////////////////////////////////////
wa_explore_menu_reference_clicked: {},
//////////////////////////////////////////////////////////////////
wa_chat_feedback_submitted: {
feedback: 'like' | 'dislike',
chatId: string,
@ -293,31 +302,5 @@ export type PosthogEventMap = {
//////////////////////////////////////////////////////////////////
wa_github_star_toast_displayed: {},
wa_github_star_toast_clicked: {},
//////////////////////////////////////////////////////////////////
wa_goto_definition_pressed: {
source: 'chat' | 'browse' | 'preview',
},
wa_find_references_pressed: {
source: 'chat' | 'browse' | 'preview',
},
wa_symbol_hover_popup_definitions_loaded: {
durationMs: number,
},
wa_explore_menu_reference_clicked: {},
wa_explore_menu_references_loaded: {
durationMs: number,
// Whether or not the user is searching all repositories.
isGlobalSearchEnabled: boolean,
},
wa_explore_menu_definitions_loaded: {
durationMs: number,
// Whether or not the user is searching all repositories.
isGlobalSearchEnabled: boolean,
},
//////////////////////////////////////////////////////////////////
api_code_search_request: {
source: string;
type: 'streamed' | 'blocking';
},
}
export type PosthogEvent = keyof PosthogEventMap;

View file

@ -35,8 +35,7 @@
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
".next/types/**/*.ts"
],
"exclude": [
"node_modules"

422
yarn.lock
View file

@ -1649,12 +1649,12 @@ __metadata:
languageName: node
linkType: hard
"@emnapi/runtime@npm:^1.7.0":
version: 1.7.1
resolution: "@emnapi/runtime@npm:1.7.1"
"@emnapi/runtime@npm:^1.4.4":
version: 1.4.5
resolution: "@emnapi/runtime@npm:1.4.5"
dependencies:
tslib: "npm:^2.4.0"
checksum: 10c0/26b851cd3e93877d8732a985a2ebf5152325bbacc6204ef5336a47359dedcc23faeb08cdfcb8bb389b5401b3e894b882bc1a1e55b4b7c1ed1e67c991a760ddd5
checksum: 10c0/37a0278be5ac81e918efe36f1449875cbafba947039c53c65a1f8fc238001b866446fc66041513b286baaff5d6f9bec667f5164b3ca481373a8d9cb65bfc984b
languageName: node
linkType: hard
@ -2426,13 +2426,6 @@ __metadata:
languageName: node
linkType: hard
"@img/colour@npm:^1.0.0":
version: 1.0.0
resolution: "@img/colour@npm:1.0.0"
checksum: 10c0/02261719c1e0d7aa5a2d585981954f2ac126f0c432400aa1a01b925aa2c41417b7695da8544ee04fd29eba7ecea8eaf9b8bef06f19dc8faba78f94eeac40667d
languageName: node
linkType: hard
"@img/sharp-darwin-arm64@npm:0.33.5":
version: 0.33.5
resolution: "@img/sharp-darwin-arm64@npm:0.33.5"
@ -2445,11 +2438,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-darwin-arm64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-darwin-arm64@npm:0.34.5"
"@img/sharp-darwin-arm64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-darwin-arm64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-darwin-arm64": "npm:1.2.4"
"@img/sharp-libvips-darwin-arm64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-darwin-arm64":
optional: true
@ -2469,11 +2462,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-darwin-x64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-darwin-x64@npm:0.34.5"
"@img/sharp-darwin-x64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-darwin-x64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-darwin-x64": "npm:1.2.4"
"@img/sharp-libvips-darwin-x64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-darwin-x64":
optional: true
@ -2488,9 +2481,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-darwin-arm64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-darwin-arm64@npm:1.2.4"
"@img/sharp-libvips-darwin-arm64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-darwin-arm64@npm:1.2.0"
conditions: os=darwin & cpu=arm64
languageName: node
linkType: hard
@ -2502,9 +2495,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-darwin-x64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-darwin-x64@npm:1.2.4"
"@img/sharp-libvips-darwin-x64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-darwin-x64@npm:1.2.0"
conditions: os=darwin & cpu=x64
languageName: node
linkType: hard
@ -2516,9 +2509,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-linux-arm64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linux-arm64@npm:1.2.4"
"@img/sharp-libvips-linux-arm64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linux-arm64@npm:1.2.0"
conditions: os=linux & cpu=arm64 & libc=glibc
languageName: node
linkType: hard
@ -2530,27 +2523,20 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-linux-arm@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linux-arm@npm:1.2.4"
"@img/sharp-libvips-linux-arm@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linux-arm@npm:1.2.0"
conditions: os=linux & cpu=arm & libc=glibc
languageName: node
linkType: hard
"@img/sharp-libvips-linux-ppc64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linux-ppc64@npm:1.2.4"
"@img/sharp-libvips-linux-ppc64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linux-ppc64@npm:1.2.0"
conditions: os=linux & cpu=ppc64 & libc=glibc
languageName: node
linkType: hard
"@img/sharp-libvips-linux-riscv64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linux-riscv64@npm:1.2.4"
conditions: os=linux & cpu=riscv64 & libc=glibc
languageName: node
linkType: hard
"@img/sharp-libvips-linux-s390x@npm:1.0.4":
version: 1.0.4
resolution: "@img/sharp-libvips-linux-s390x@npm:1.0.4"
@ -2558,9 +2544,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-linux-s390x@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linux-s390x@npm:1.2.4"
"@img/sharp-libvips-linux-s390x@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linux-s390x@npm:1.2.0"
conditions: os=linux & cpu=s390x & libc=glibc
languageName: node
linkType: hard
@ -2572,9 +2558,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-linux-x64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linux-x64@npm:1.2.4"
"@img/sharp-libvips-linux-x64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linux-x64@npm:1.2.0"
conditions: os=linux & cpu=x64 & libc=glibc
languageName: node
linkType: hard
@ -2586,9 +2572,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-linuxmusl-arm64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linuxmusl-arm64@npm:1.2.4"
"@img/sharp-libvips-linuxmusl-arm64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linuxmusl-arm64@npm:1.2.0"
conditions: os=linux & cpu=arm64 & libc=musl
languageName: node
linkType: hard
@ -2600,9 +2586,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-libvips-linuxmusl-x64@npm:1.2.4":
version: 1.2.4
resolution: "@img/sharp-libvips-linuxmusl-x64@npm:1.2.4"
"@img/sharp-libvips-linuxmusl-x64@npm:1.2.0":
version: 1.2.0
resolution: "@img/sharp-libvips-linuxmusl-x64@npm:1.2.0"
conditions: os=linux & cpu=x64 & libc=musl
languageName: node
linkType: hard
@ -2619,11 +2605,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linux-arm64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linux-arm64@npm:0.34.5"
"@img/sharp-linux-arm64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linux-arm64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linux-arm64": "npm:1.2.4"
"@img/sharp-libvips-linux-arm64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linux-arm64":
optional: true
@ -2643,11 +2629,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linux-arm@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linux-arm@npm:0.34.5"
"@img/sharp-linux-arm@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linux-arm@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linux-arm": "npm:1.2.4"
"@img/sharp-libvips-linux-arm": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linux-arm":
optional: true
@ -2655,11 +2641,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linux-ppc64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linux-ppc64@npm:0.34.5"
"@img/sharp-linux-ppc64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linux-ppc64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linux-ppc64": "npm:1.2.4"
"@img/sharp-libvips-linux-ppc64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linux-ppc64":
optional: true
@ -2667,18 +2653,6 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linux-riscv64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linux-riscv64@npm:0.34.5"
dependencies:
"@img/sharp-libvips-linux-riscv64": "npm:1.2.4"
dependenciesMeta:
"@img/sharp-libvips-linux-riscv64":
optional: true
conditions: os=linux & cpu=riscv64 & libc=glibc
languageName: node
linkType: hard
"@img/sharp-linux-s390x@npm:0.33.5":
version: 0.33.5
resolution: "@img/sharp-linux-s390x@npm:0.33.5"
@ -2691,11 +2665,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linux-s390x@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linux-s390x@npm:0.34.5"
"@img/sharp-linux-s390x@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linux-s390x@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linux-s390x": "npm:1.2.4"
"@img/sharp-libvips-linux-s390x": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linux-s390x":
optional: true
@ -2715,11 +2689,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linux-x64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linux-x64@npm:0.34.5"
"@img/sharp-linux-x64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linux-x64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linux-x64": "npm:1.2.4"
"@img/sharp-libvips-linux-x64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linux-x64":
optional: true
@ -2739,11 +2713,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linuxmusl-arm64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linuxmusl-arm64@npm:0.34.5"
"@img/sharp-linuxmusl-arm64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linuxmusl-arm64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linuxmusl-arm64": "npm:1.2.4"
"@img/sharp-libvips-linuxmusl-arm64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linuxmusl-arm64":
optional: true
@ -2763,11 +2737,11 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-linuxmusl-x64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-linuxmusl-x64@npm:0.34.5"
"@img/sharp-linuxmusl-x64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-linuxmusl-x64@npm:0.34.3"
dependencies:
"@img/sharp-libvips-linuxmusl-x64": "npm:1.2.4"
"@img/sharp-libvips-linuxmusl-x64": "npm:1.2.0"
dependenciesMeta:
"@img/sharp-libvips-linuxmusl-x64":
optional: true
@ -2784,18 +2758,18 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-wasm32@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-wasm32@npm:0.34.5"
"@img/sharp-wasm32@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-wasm32@npm:0.34.3"
dependencies:
"@emnapi/runtime": "npm:^1.7.0"
"@emnapi/runtime": "npm:^1.4.4"
conditions: cpu=wasm32
languageName: node
linkType: hard
"@img/sharp-win32-arm64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-win32-arm64@npm:0.34.5"
"@img/sharp-win32-arm64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-win32-arm64@npm:0.34.3"
conditions: os=win32 & cpu=arm64
languageName: node
linkType: hard
@ -2807,9 +2781,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-win32-ia32@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-win32-ia32@npm:0.34.5"
"@img/sharp-win32-ia32@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-win32-ia32@npm:0.34.3"
conditions: os=win32 & cpu=ia32
languageName: node
linkType: hard
@ -2821,9 +2795,9 @@ __metadata:
languageName: node
linkType: hard
"@img/sharp-win32-x64@npm:0.34.5":
version: 0.34.5
resolution: "@img/sharp-win32-x64@npm:0.34.5"
"@img/sharp-win32-x64@npm:0.34.3":
version: 0.34.3
resolution: "@img/sharp-win32-x64@npm:0.34.3"
conditions: os=win32 & cpu=x64
languageName: node
linkType: hard
@ -3294,10 +3268,10 @@ __metadata:
languageName: node
linkType: hard
"@next/env@npm:15.5.7":
version: 15.5.7
resolution: "@next/env@npm:15.5.7"
checksum: 10c0/f92d99e5fa3516c6b7699abafd9bd813f5c1889dd257ab098f1b71f93137f5e4f49792e22f6dddf8a59efcb134e8e84277c983ff88607b2a42aac651bfde78ea
"@next/env@npm:15.5.0":
version: 15.5.0
resolution: "@next/env@npm:15.5.0"
checksum: 10c0/13ed931688c26b764499840022c9855763fb583e728cf30933b2ff71d3ca681eb71611ec4d7580ecb45197c18a1a4498ba5a61cb60edc6e18966103620d11bad
languageName: node
linkType: hard
@ -3317,9 +3291,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-darwin-arm64@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-darwin-arm64@npm:15.5.7"
"@next/swc-darwin-arm64@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-darwin-arm64@npm:15.5.0"
conditions: os=darwin & cpu=arm64
languageName: node
linkType: hard
@ -3331,9 +3305,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-darwin-x64@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-darwin-x64@npm:15.5.7"
"@next/swc-darwin-x64@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-darwin-x64@npm:15.5.0"
conditions: os=darwin & cpu=x64
languageName: node
linkType: hard
@ -3345,9 +3319,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-linux-arm64-gnu@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-linux-arm64-gnu@npm:15.5.7"
"@next/swc-linux-arm64-gnu@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-linux-arm64-gnu@npm:15.5.0"
conditions: os=linux & cpu=arm64 & libc=glibc
languageName: node
linkType: hard
@ -3359,9 +3333,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-linux-arm64-musl@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-linux-arm64-musl@npm:15.5.7"
"@next/swc-linux-arm64-musl@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-linux-arm64-musl@npm:15.5.0"
conditions: os=linux & cpu=arm64 & libc=musl
languageName: node
linkType: hard
@ -3373,9 +3347,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-linux-x64-gnu@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-linux-x64-gnu@npm:15.5.7"
"@next/swc-linux-x64-gnu@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-linux-x64-gnu@npm:15.5.0"
conditions: os=linux & cpu=x64 & libc=glibc
languageName: node
linkType: hard
@ -3387,9 +3361,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-linux-x64-musl@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-linux-x64-musl@npm:15.5.7"
"@next/swc-linux-x64-musl@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-linux-x64-musl@npm:15.5.0"
conditions: os=linux & cpu=x64 & libc=musl
languageName: node
linkType: hard
@ -3401,9 +3375,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-win32-arm64-msvc@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-win32-arm64-msvc@npm:15.5.7"
"@next/swc-win32-arm64-msvc@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-win32-arm64-msvc@npm:15.5.0"
conditions: os=win32 & cpu=arm64
languageName: node
linkType: hard
@ -3422,9 +3396,9 @@ __metadata:
languageName: node
linkType: hard
"@next/swc-win32-x64-msvc@npm:15.5.7":
version: 15.5.7
resolution: "@next/swc-win32-x64-msvc@npm:15.5.7"
"@next/swc-win32-x64-msvc@npm:15.5.0":
version: 15.5.0
resolution: "@next/swc-win32-x64-msvc@npm:15.5.0"
conditions: os=win32 & cpu=x64
languageName: node
linkType: hard
@ -4599,15 +4573,6 @@ __metadata:
languageName: node
linkType: hard
"@posthog/core@npm:1.6.0":
version: 1.6.0
resolution: "@posthog/core@npm:1.6.0"
dependencies:
cross-spawn: "npm:^7.0.6"
checksum: 10c0/28aa907bb21b18587bc5f47c44349ebc834b37d9a4cedb1a18d7b673d4d7cdad2120dda80deceaee707b2f52333e9a08a8e591e1fc4066521ce05e820b76309f
languageName: node
linkType: hard
"@prisma/client@npm:6.2.1":
version: 6.2.1
resolution: "@prisma/client@npm:6.2.1"
@ -8190,8 +8155,8 @@ __metadata:
"@types/node": "npm:^20"
"@types/nodemailer": "npm:^6.4.17"
"@types/psl": "npm:^1.1.3"
"@types/react": "npm:19.2.1"
"@types/react-dom": "npm:19.2.1"
"@types/react": "npm:19.1.10"
"@types/react-dom": "npm:19.1.7"
"@typescript-eslint/eslint-plugin": "npm:^8.40.0"
"@typescript-eslint/parser": "npm:^8.40.0"
"@uidotdev/usehooks": "npm:^2.4.1"
@ -8232,7 +8197,6 @@ __metadata:
eslint-config-next: "npm:15.5.0"
eslint-plugin-react: "npm:^7.37.5"
eslint-plugin-react-hooks: "npm:^5.2.0"
fast-deep-equal: "npm:^3.1.3"
fuse.js: "npm:^7.0.0"
google-auth-library: "npm:^10.1.0"
graphql: "npm:^16.9.0"
@ -8243,7 +8207,7 @@ __metadata:
langfuse-vercel: "npm:^3.38.4"
lucide-react: "npm:^0.517.0"
micromatch: "npm:^4.0.8"
next: "npm:^15.5.7"
next: "npm:15.5.0"
next-auth: "npm:^5.0.0-beta.30"
next-navigation-guard: "npm:^0.2.0"
next-themes: "npm:^0.3.0"
@ -8254,12 +8218,11 @@ __metadata:
parse-diff: "npm:^0.11.1"
postcss: "npm:^8"
posthog-js: "npm:^1.161.5"
posthog-node: "npm:^5.15.0"
pretty-bytes: "npm:^6.1.1"
psl: "npm:^1.15.0"
react: "npm:^19.2.1"
react: "npm:19.1.1"
react-device-detect: "npm:^2.2.3"
react-dom: "npm:^19.2.1"
react-dom: "npm:19.1.1"
react-email: "npm:3.0.3"
react-hook-form: "npm:^7.53.0"
react-hotkeys-hook: "npm:^4.5.1"
@ -8910,21 +8873,21 @@ __metadata:
languageName: node
linkType: hard
"@types/react-dom@npm:19.2.1":
version: 19.2.1
resolution: "@types/react-dom@npm:19.2.1"
"@types/react-dom@npm:19.1.7":
version: 19.1.7
resolution: "@types/react-dom@npm:19.1.7"
peerDependencies:
"@types/react": ^19.2.0
checksum: 10c0/0dbbc5b7ecd74681bfac95a413133b26118a70b8840748277abafa47e5c7a037beae6a660e6a21fb53f5cbdb0b2d33e117ea7bbd976a888c298392a8a96bc68f
"@types/react": ^19.0.0
checksum: 10c0/8db5751c1567552fe4e1ece9f5823b682f2994ec8d30ed34ba0ef984e3c8ace1435f8be93d02f55c350147e78ac8c4dbcd8ed2c3b6a60f575bc5374f588c51c9
languageName: node
linkType: hard
"@types/react@npm:19.2.1":
version: 19.2.1
resolution: "@types/react@npm:19.2.1"
"@types/react@npm:19.1.10":
version: 19.1.10
resolution: "@types/react@npm:19.1.10"
dependencies:
csstype: "npm:^3.0.2"
checksum: 10c0/c44881c275da91156ce02986ab1f59c9724db256f4850d3937c9acea561a6ab1fe1028f7a1fc4da3a2c1bcb00de29e238922e8c6d42a727ef2e6e0cd40b3db9f
checksum: 10c0/fb583deacd0a815e2775dc1b9f764532d8cacb748ddd2c2914805a46c257ce6c237b4078f44009692074db212ab61a390301c6470f07f5aa5bfdeb78a2acfda1
languageName: node
linkType: hard
@ -11346,10 +11309,10 @@ __metadata:
languageName: node
linkType: hard
"detect-libc@npm:^2.1.2":
version: 2.1.2
resolution: "detect-libc@npm:2.1.2"
checksum: 10c0/acc675c29a5649fa1fb6e255f993b8ee829e510b6b56b0910666949c80c364738833417d0edb5f90e4e46be17228b0f2b66a010513984e18b15deeeac49369c4
"detect-libc@npm:^2.0.4":
version: 2.0.4
resolution: "detect-libc@npm:2.0.4"
checksum: 10c0/c15541f836eba4b1f521e4eecc28eefefdbc10a94d3b8cb4c507689f332cc111babb95deda66f2de050b22122113189986d5190be97d51b5a2b23b938415e67c
languageName: node
linkType: hard
@ -16178,19 +16141,19 @@ __metadata:
languageName: node
linkType: hard
"next@npm:^15.5.7":
version: 15.5.7
resolution: "next@npm:15.5.7"
"next@npm:15.5.0":
version: 15.5.0
resolution: "next@npm:15.5.0"
dependencies:
"@next/env": "npm:15.5.7"
"@next/swc-darwin-arm64": "npm:15.5.7"
"@next/swc-darwin-x64": "npm:15.5.7"
"@next/swc-linux-arm64-gnu": "npm:15.5.7"
"@next/swc-linux-arm64-musl": "npm:15.5.7"
"@next/swc-linux-x64-gnu": "npm:15.5.7"
"@next/swc-linux-x64-musl": "npm:15.5.7"
"@next/swc-win32-arm64-msvc": "npm:15.5.7"
"@next/swc-win32-x64-msvc": "npm:15.5.7"
"@next/env": "npm:15.5.0"
"@next/swc-darwin-arm64": "npm:15.5.0"
"@next/swc-darwin-x64": "npm:15.5.0"
"@next/swc-linux-arm64-gnu": "npm:15.5.0"
"@next/swc-linux-arm64-musl": "npm:15.5.0"
"@next/swc-linux-x64-gnu": "npm:15.5.0"
"@next/swc-linux-x64-musl": "npm:15.5.0"
"@next/swc-win32-arm64-msvc": "npm:15.5.0"
"@next/swc-win32-x64-msvc": "npm:15.5.0"
"@swc/helpers": "npm:0.5.15"
caniuse-lite: "npm:^1.0.30001579"
postcss: "npm:8.4.31"
@ -16233,7 +16196,7 @@ __metadata:
optional: true
bin:
next: dist/bin/next
checksum: 10c0/baf5b9f42416c478702b3894479b3d7862bc4abf18afe0e43b7fc7ed35567b8dc6cb76cd94906505bab9013cb8d0f3370cdc0451c01ec15ae5a638d37b5ba7c7
checksum: 10c0/8691787562666713e9ee8bc3edad646328d9cea85d5c4c10bd05a978afa25bc9927bbfd50acc69ceb268296741b5f71e78fa0213fe65b731a55e73b0f5807c24
languageName: node
linkType: hard
@ -17245,15 +17208,6 @@ __metadata:
languageName: node
linkType: hard
"posthog-node@npm:^5.15.0":
version: 5.15.0
resolution: "posthog-node@npm:5.15.0"
dependencies:
"@posthog/core": "npm:1.6.0"
checksum: 10c0/7db929453cefc9b2d0017e1f7c9ffe7e6ecd2a495ee9861bd5e8f3873f72fa29a318dd7bccf10eb15639e1860aab396d4be502af88afba96ed15ac8b46d57e9d
languageName: node
linkType: hard
"preact-render-to-string@npm:6.5.11":
version: 6.5.11
resolution: "preact-render-to-string@npm:6.5.11"
@ -17584,14 +17538,14 @@ __metadata:
languageName: node
linkType: hard
"react-dom@npm:^19.2.1":
version: 19.2.1
resolution: "react-dom@npm:19.2.1"
"react-dom@npm:19.1.1":
version: 19.1.1
resolution: "react-dom@npm:19.1.1"
dependencies:
scheduler: "npm:^0.27.0"
scheduler: "npm:^0.26.0"
peerDependencies:
react: ^19.2.1
checksum: 10c0/e56b6b3d72314df580ca800b70a69a21c6372703c8f45d9b5451ca6519faefb2496d76ffa9c5adb94136d2bbf2fd303d0dfc208a2cd77ede3132877471af9470
react: ^19.1.1
checksum: 10c0/8c91198510521299c56e4e8d5e3a4508b2734fb5e52f29eeac33811de64e76fe586ad32c32182e2e84e070d98df67125da346c3360013357228172dbcd20bcdd
languageName: node
linkType: hard
@ -17808,10 +17762,10 @@ __metadata:
languageName: node
linkType: hard
"react@npm:^19.2.1":
version: 19.2.1
resolution: "react@npm:19.2.1"
checksum: 10c0/2b5eaf407abb3db84090434c20d6c5a8e447ab7abcd8fe9eaf1ddc299babcf31284ee9db7ea5671d21c85ac5298bd632fa1a7da1ed78d5b368a537f5e1cd5d62
"react@npm:19.1.1":
version: 19.1.1
resolution: "react@npm:19.1.1"
checksum: 10c0/8c9769a2dfd02e603af6445058325e6c8a24b47b185d0e461f66a6454765ddcaecb3f0a90184836c68bb509f3c38248359edbc42f0d07c23eb500a5c30c87b4e
languageName: node
linkType: hard
@ -18535,10 +18489,10 @@ __metadata:
languageName: node
linkType: hard
"scheduler@npm:^0.27.0":
version: 0.27.0
resolution: "scheduler@npm:0.27.0"
checksum: 10c0/4f03048cb05a3c8fddc45813052251eca00688f413a3cee236d984a161da28db28ba71bd11e7a3dd02f7af84ab28d39fb311431d3b3772fed557945beb00c452
"scheduler@npm:^0.26.0":
version: 0.26.0
resolution: "scheduler@npm:0.26.0"
checksum: 10c0/5b8d5bfddaae3513410eda54f2268e98a376a429931921a81b5c3a2873aab7ca4d775a8caac5498f8cbc7d0daeab947cf923dbd8e215d61671f9f4e392d34356
languageName: node
linkType: hard
@ -18587,12 +18541,12 @@ __metadata:
languageName: node
linkType: hard
"semver@npm:^7.7.3":
version: 7.7.3
resolution: "semver@npm:7.7.3"
"semver@npm:^7.7.2":
version: 7.7.2
resolution: "semver@npm:7.7.2"
bin:
semver: bin/semver.js
checksum: 10c0/4afe5c986567db82f44c8c6faef8fe9df2a9b1d98098fc1721f57c696c4c21cebd572f297fc21002f81889492345b8470473bc6f4aff5fb032a6ea59ea2bc45e
checksum: 10c0/aca305edfbf2383c22571cb7714f48cadc7ac95371b4b52362fb8eeffdfbc0de0669368b82b2b15978f8848f01d7114da65697e56cd8c37b0dab8c58e543f9ea
languageName: node
linkType: hard
@ -18790,36 +18744,34 @@ __metadata:
linkType: hard
"sharp@npm:^0.34.3":
version: 0.34.5
resolution: "sharp@npm:0.34.5"
version: 0.34.3
resolution: "sharp@npm:0.34.3"
dependencies:
"@img/colour": "npm:^1.0.0"
"@img/sharp-darwin-arm64": "npm:0.34.5"
"@img/sharp-darwin-x64": "npm:0.34.5"
"@img/sharp-libvips-darwin-arm64": "npm:1.2.4"
"@img/sharp-libvips-darwin-x64": "npm:1.2.4"
"@img/sharp-libvips-linux-arm": "npm:1.2.4"
"@img/sharp-libvips-linux-arm64": "npm:1.2.4"
"@img/sharp-libvips-linux-ppc64": "npm:1.2.4"
"@img/sharp-libvips-linux-riscv64": "npm:1.2.4"
"@img/sharp-libvips-linux-s390x": "npm:1.2.4"
"@img/sharp-libvips-linux-x64": "npm:1.2.4"
"@img/sharp-libvips-linuxmusl-arm64": "npm:1.2.4"
"@img/sharp-libvips-linuxmusl-x64": "npm:1.2.4"
"@img/sharp-linux-arm": "npm:0.34.5"
"@img/sharp-linux-arm64": "npm:0.34.5"
"@img/sharp-linux-ppc64": "npm:0.34.5"
"@img/sharp-linux-riscv64": "npm:0.34.5"
"@img/sharp-linux-s390x": "npm:0.34.5"
"@img/sharp-linux-x64": "npm:0.34.5"
"@img/sharp-linuxmusl-arm64": "npm:0.34.5"
"@img/sharp-linuxmusl-x64": "npm:0.34.5"
"@img/sharp-wasm32": "npm:0.34.5"
"@img/sharp-win32-arm64": "npm:0.34.5"
"@img/sharp-win32-ia32": "npm:0.34.5"
"@img/sharp-win32-x64": "npm:0.34.5"
detect-libc: "npm:^2.1.2"
semver: "npm:^7.7.3"
"@img/sharp-darwin-arm64": "npm:0.34.3"
"@img/sharp-darwin-x64": "npm:0.34.3"
"@img/sharp-libvips-darwin-arm64": "npm:1.2.0"
"@img/sharp-libvips-darwin-x64": "npm:1.2.0"
"@img/sharp-libvips-linux-arm": "npm:1.2.0"
"@img/sharp-libvips-linux-arm64": "npm:1.2.0"
"@img/sharp-libvips-linux-ppc64": "npm:1.2.0"
"@img/sharp-libvips-linux-s390x": "npm:1.2.0"
"@img/sharp-libvips-linux-x64": "npm:1.2.0"
"@img/sharp-libvips-linuxmusl-arm64": "npm:1.2.0"
"@img/sharp-libvips-linuxmusl-x64": "npm:1.2.0"
"@img/sharp-linux-arm": "npm:0.34.3"
"@img/sharp-linux-arm64": "npm:0.34.3"
"@img/sharp-linux-ppc64": "npm:0.34.3"
"@img/sharp-linux-s390x": "npm:0.34.3"
"@img/sharp-linux-x64": "npm:0.34.3"
"@img/sharp-linuxmusl-arm64": "npm:0.34.3"
"@img/sharp-linuxmusl-x64": "npm:0.34.3"
"@img/sharp-wasm32": "npm:0.34.3"
"@img/sharp-win32-arm64": "npm:0.34.3"
"@img/sharp-win32-ia32": "npm:0.34.3"
"@img/sharp-win32-x64": "npm:0.34.3"
color: "npm:^4.2.3"
detect-libc: "npm:^2.0.4"
semver: "npm:^7.7.2"
dependenciesMeta:
"@img/sharp-darwin-arm64":
optional: true
@ -18835,8 +18787,6 @@ __metadata:
optional: true
"@img/sharp-libvips-linux-ppc64":
optional: true
"@img/sharp-libvips-linux-riscv64":
optional: true
"@img/sharp-libvips-linux-s390x":
optional: true
"@img/sharp-libvips-linux-x64":
@ -18851,8 +18801,6 @@ __metadata:
optional: true
"@img/sharp-linux-ppc64":
optional: true
"@img/sharp-linux-riscv64":
optional: true
"@img/sharp-linux-s390x":
optional: true
"@img/sharp-linux-x64":
@ -18869,7 +18817,7 @@ __metadata:
optional: true
"@img/sharp-win32-x64":
optional: true
checksum: 10c0/fd79e29df0597a7d5704b8461c51f944ead91a5243691697be6e8243b966402beda53ddc6f0a53b96ea3cb8221f0b244aa588114d3ebf8734fb4aefd41ab802f
checksum: 10c0/df9e6645e3db6ed298a0ac956ba74e468c367fc038b547936fbdddc6a29fce9af40413acbef73b3716291530760f311a20e45c8983f20ee5ea69dd2f21464a2b
languageName: node
linkType: hard